]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/media/usb/em28xx/em28xx-video.c
[media] em28xx: add support for V4L2_PIX_FMT_SRGGB8
[karo-tx-linux.git] / drivers / media / usb / em28xx / em28xx-video.c
1 /*
2    em28xx-video.c - driver for Empia EM2800/EM2820/2840 USB
3                     video capture devices
4
5    Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
6                       Markus Rechberger <mrechberger@gmail.com>
7                       Mauro Carvalho Chehab <mchehab@infradead.org>
8                       Sascha Sommer <saschasommer@freenet.de>
9    Copyright (C) 2012 Frank Schäfer <fschaefer.oss@googlemail.com>
10
11         Some parts based on SN9C10x PC Camera Controllers GPL driver made
12                 by Luca Risolia <luca.risolia@studio.unibo.it>
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 2 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program; if not, write to the Free Software
26    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27  */
28
29 #include "em28xx.h"
30
31 #include <linux/init.h>
32 #include <linux/list.h>
33 #include <linux/module.h>
34 #include <linux/kernel.h>
35 #include <linux/bitmap.h>
36 #include <linux/usb.h>
37 #include <linux/i2c.h>
38 #include <linux/mm.h>
39 #include <linux/mutex.h>
40 #include <linux/slab.h>
41
42 #include "em28xx-v4l.h"
43 #include <media/v4l2-common.h>
44 #include <media/v4l2-ioctl.h>
45 #include <media/v4l2-event.h>
46 #include <media/drv-intf/msp3400.h>
47 #include <media/tuner.h>
48
49 #define DRIVER_AUTHOR "Ludovico Cavedon <cavedon@sssup.it>, " \
50                       "Markus Rechberger <mrechberger@gmail.com>, " \
51                       "Mauro Carvalho Chehab <mchehab@infradead.org>, " \
52                       "Sascha Sommer <saschasommer@freenet.de>"
53
54 static unsigned int isoc_debug;
55 module_param(isoc_debug, int, 0644);
56 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
57
58 static unsigned int disable_vbi;
59 module_param(disable_vbi, int, 0644);
60 MODULE_PARM_DESC(disable_vbi, "disable vbi support");
61
62 static int alt;
63 module_param(alt, int, 0644);
64 MODULE_PARM_DESC(alt, "alternate setting to use for video endpoint");
65
66 #define em28xx_videodbg(fmt, arg...) do {                               \
67         if (video_debug)                                                \
68                 dev_printk(KERN_DEBUG, &dev->intf->dev,                 \
69                            "video: %s: " fmt, __func__, ## arg);        \
70 } while (0)
71
72 #define em28xx_isocdbg(fmt, arg...) do {\
73         if (isoc_debug) \
74                 dev_printk(KERN_DEBUG, &dev->intf->dev,                 \
75                            "isoc: %s: " fmt, __func__, ## arg);         \
76 } while (0)
77
78 MODULE_AUTHOR(DRIVER_AUTHOR);
79 MODULE_DESCRIPTION(DRIVER_DESC " - v4l2 interface");
80 MODULE_LICENSE("GPL");
81 MODULE_VERSION(EM28XX_VERSION);
82
83 #define EM25XX_FRMDATAHDR_BYTE1                 0x02
84 #define EM25XX_FRMDATAHDR_BYTE2_STILL_IMAGE     0x20
85 #define EM25XX_FRMDATAHDR_BYTE2_FRAME_END       0x02
86 #define EM25XX_FRMDATAHDR_BYTE2_FRAME_ID        0x01
87 #define EM25XX_FRMDATAHDR_BYTE2_MASK    (EM25XX_FRMDATAHDR_BYTE2_STILL_IMAGE | \
88                                          EM25XX_FRMDATAHDR_BYTE2_FRAME_END |   \
89                                          EM25XX_FRMDATAHDR_BYTE2_FRAME_ID)
90
91 static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
92 static unsigned int vbi_nr[]   = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
93 static unsigned int radio_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
94
95 module_param_array(video_nr, int, NULL, 0444);
96 module_param_array(vbi_nr, int, NULL, 0444);
97 module_param_array(radio_nr, int, NULL, 0444);
98 MODULE_PARM_DESC(video_nr, "video device numbers");
99 MODULE_PARM_DESC(vbi_nr,   "vbi device numbers");
100 MODULE_PARM_DESC(radio_nr, "radio device numbers");
101
102 static unsigned int video_debug;
103 module_param(video_debug, int, 0644);
104 MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
105
106 /* supported video standards */
107 static struct em28xx_fmt format[] = {
108         {
109                 .name     = "16 bpp YUY2, 4:2:2, packed",
110                 .fourcc   = V4L2_PIX_FMT_YUYV,
111                 .depth    = 16,
112                 .reg      = EM28XX_OUTFMT_YUV422_Y0UY1V,
113         }, {
114                 .name     = "16 bpp RGB 565, LE",
115                 .fourcc   = V4L2_PIX_FMT_RGB565,
116                 .depth    = 16,
117                 .reg      = EM28XX_OUTFMT_RGB_16_656,
118         }, {
119                 .name     = "8 bpp Bayer RGRG..GBGB",
120                 .fourcc   = V4L2_PIX_FMT_SRGGB8,
121                 .depth    = 8,
122                 .reg      = EM28XX_OUTFMT_RGB_8_RGRG,
123         }, {
124                 .name     = "8 bpp Bayer BGBG..GRGR",
125                 .fourcc   = V4L2_PIX_FMT_SBGGR8,
126                 .depth    = 8,
127                 .reg      = EM28XX_OUTFMT_RGB_8_BGBG,
128         }, {
129                 .name     = "8 bpp Bayer GRGR..BGBG",
130                 .fourcc   = V4L2_PIX_FMT_SGRBG8,
131                 .depth    = 8,
132                 .reg      = EM28XX_OUTFMT_RGB_8_GRGR,
133         }, {
134                 .name     = "8 bpp Bayer GBGB..RGRG",
135                 .fourcc   = V4L2_PIX_FMT_SGBRG8,
136                 .depth    = 8,
137                 .reg      = EM28XX_OUTFMT_RGB_8_GBGB,
138         }, {
139                 .name     = "12 bpp YUV411",
140                 .fourcc   = V4L2_PIX_FMT_YUV411P,
141                 .depth    = 12,
142                 .reg      = EM28XX_OUTFMT_YUV411,
143         },
144 };
145
146 /*FIXME: maxw should be dependent of alt mode */
147 static inline unsigned int norm_maxw(struct em28xx *dev)
148 {
149         struct em28xx_v4l2 *v4l2 = dev->v4l2;
150
151         if (dev->board.is_webcam)
152                 return v4l2->sensor_xres;
153
154         if (dev->board.max_range_640_480)
155                 return 640;
156
157         return 720;
158 }
159
160 static inline unsigned int norm_maxh(struct em28xx *dev)
161 {
162         struct em28xx_v4l2 *v4l2 = dev->v4l2;
163
164         if (dev->board.is_webcam)
165                 return v4l2->sensor_yres;
166
167         if (dev->board.max_range_640_480)
168                 return 480;
169
170         return (v4l2->norm & V4L2_STD_625_50) ? 576 : 480;
171 }
172
173 static int em28xx_vbi_supported(struct em28xx *dev)
174 {
175         /* Modprobe option to manually disable */
176         if (disable_vbi == 1)
177                 return 0;
178
179         if (dev->board.is_webcam)
180                 return 0;
181
182         /* FIXME: check subdevices for VBI support */
183
184         if (dev->chip_id == CHIP_ID_EM2860 ||
185             dev->chip_id == CHIP_ID_EM2883)
186                 return 1;
187
188         /* Version of em28xx that does not support VBI */
189         return 0;
190 }
191
192 /*
193  * em28xx_wake_i2c()
194  * configure i2c attached devices
195  */
196 static void em28xx_wake_i2c(struct em28xx *dev)
197 {
198         struct v4l2_device *v4l2_dev = &dev->v4l2->v4l2_dev;
199
200         v4l2_device_call_all(v4l2_dev, 0, core,  reset, 0);
201         v4l2_device_call_all(v4l2_dev, 0, video, s_routing,
202                              INPUT(dev->ctl_input)->vmux, 0, 0);
203 }
204
205 static int em28xx_colorlevels_set_default(struct em28xx *dev)
206 {
207         em28xx_write_reg(dev, EM28XX_R20_YGAIN, CONTRAST_DEFAULT);
208         em28xx_write_reg(dev, EM28XX_R21_YOFFSET, BRIGHTNESS_DEFAULT);
209         em28xx_write_reg(dev, EM28XX_R22_UVGAIN, SATURATION_DEFAULT);
210         em28xx_write_reg(dev, EM28XX_R23_UOFFSET, BLUE_BALANCE_DEFAULT);
211         em28xx_write_reg(dev, EM28XX_R24_VOFFSET, RED_BALANCE_DEFAULT);
212         em28xx_write_reg(dev, EM28XX_R25_SHARPNESS, SHARPNESS_DEFAULT);
213
214         em28xx_write_reg(dev, EM28XX_R14_GAMMA, 0x20);
215         em28xx_write_reg(dev, EM28XX_R15_RGAIN, 0x20);
216         em28xx_write_reg(dev, EM28XX_R16_GGAIN, 0x20);
217         em28xx_write_reg(dev, EM28XX_R17_BGAIN, 0x20);
218         em28xx_write_reg(dev, EM28XX_R18_ROFFSET, 0x00);
219         em28xx_write_reg(dev, EM28XX_R19_GOFFSET, 0x00);
220         return em28xx_write_reg(dev, EM28XX_R1A_BOFFSET, 0x00);
221 }
222
223 static int em28xx_set_outfmt(struct em28xx *dev)
224 {
225         int ret;
226         u8 fmt, vinctrl;
227         struct em28xx_v4l2 *v4l2 = dev->v4l2;
228
229         fmt = v4l2->format->reg;
230         if (!dev->is_em25xx)
231                 fmt |= 0x20;
232         /*
233          * NOTE: it's not clear if this is really needed !
234          * The datasheets say bit 5 is a reserved bit and devices seem to work
235          * fine without it. But the Windows driver sets it for em2710/50+em28xx
236          * devices and we've always been setting it, too.
237          *
238          * em2765 (em25xx, em276x/7x/8x) devices do NOT work with this bit set,
239          * it's likely used for an additional (compressed ?) format there.
240          */
241         ret = em28xx_write_reg(dev, EM28XX_R27_OUTFMT, fmt);
242         if (ret < 0)
243                 return ret;
244
245         ret = em28xx_write_reg(dev, EM28XX_R10_VINMODE, v4l2->vinmode);
246         if (ret < 0)
247                 return ret;
248
249         vinctrl = v4l2->vinctl;
250         if (em28xx_vbi_supported(dev) == 1) {
251                 vinctrl |= EM28XX_VINCTRL_VBI_RAW;
252                 em28xx_write_reg(dev, EM28XX_R34_VBI_START_H, 0x00);
253                 em28xx_write_reg(dev, EM28XX_R36_VBI_WIDTH, v4l2->vbi_width/4);
254                 em28xx_write_reg(dev, EM28XX_R37_VBI_HEIGHT, v4l2->vbi_height);
255                 if (v4l2->norm & V4L2_STD_525_60) {
256                         /* NTSC */
257                         em28xx_write_reg(dev, EM28XX_R35_VBI_START_V, 0x09);
258                 } else if (v4l2->norm & V4L2_STD_625_50) {
259                         /* PAL */
260                         em28xx_write_reg(dev, EM28XX_R35_VBI_START_V, 0x07);
261                 }
262         }
263
264         return em28xx_write_reg(dev, EM28XX_R11_VINCTRL, vinctrl);
265 }
266
267 static int em28xx_accumulator_set(struct em28xx *dev, u8 xmin, u8 xmax,
268                                   u8 ymin, u8 ymax)
269 {
270         em28xx_videodbg("em28xx Scale: (%d,%d)-(%d,%d)\n",
271                         xmin, ymin, xmax, ymax);
272
273         em28xx_write_regs(dev, EM28XX_R28_XMIN, &xmin, 1);
274         em28xx_write_regs(dev, EM28XX_R29_XMAX, &xmax, 1);
275         em28xx_write_regs(dev, EM28XX_R2A_YMIN, &ymin, 1);
276         return em28xx_write_regs(dev, EM28XX_R2B_YMAX, &ymax, 1);
277 }
278
279 static void em28xx_capture_area_set(struct em28xx *dev, u8 hstart, u8 vstart,
280                                     u16 width, u16 height)
281 {
282         u8 cwidth = width >> 2;
283         u8 cheight = height >> 2;
284         u8 overflow = (height >> 9 & 0x02) | (width >> 10 & 0x01);
285         /* NOTE: size limit: 2047x1023 = 2MPix */
286
287         em28xx_videodbg("capture area set to (%d,%d): %dx%d\n",
288                         hstart, vstart,
289                        ((overflow & 2) << 9 | cwidth << 2),
290                        ((overflow & 1) << 10 | cheight << 2));
291
292         em28xx_write_regs(dev, EM28XX_R1C_HSTART, &hstart, 1);
293         em28xx_write_regs(dev, EM28XX_R1D_VSTART, &vstart, 1);
294         em28xx_write_regs(dev, EM28XX_R1E_CWIDTH, &cwidth, 1);
295         em28xx_write_regs(dev, EM28XX_R1F_CHEIGHT, &cheight, 1);
296         em28xx_write_regs(dev, EM28XX_R1B_OFLOW, &overflow, 1);
297
298         /* FIXME: function/meaning of these registers ? */
299         /* FIXME: align width+height to multiples of 4 ?! */
300         if (dev->is_em25xx) {
301                 em28xx_write_reg(dev, 0x34, width >> 4);
302                 em28xx_write_reg(dev, 0x35, height >> 4);
303         }
304 }
305
306 static int em28xx_scaler_set(struct em28xx *dev, u16 h, u16 v)
307 {
308         u8 mode = 0x00;
309         /* the em2800 scaler only supports scaling down to 50% */
310
311         if (dev->board.is_em2800) {
312                 mode = (v ? 0x20 : 0x00) | (h ? 0x10 : 0x00);
313         } else {
314                 u8 buf[2];
315
316                 buf[0] = h;
317                 buf[1] = h >> 8;
318                 em28xx_write_regs(dev, EM28XX_R30_HSCALELOW, (char *)buf, 2);
319
320                 buf[0] = v;
321                 buf[1] = v >> 8;
322                 em28xx_write_regs(dev, EM28XX_R32_VSCALELOW, (char *)buf, 2);
323                 /* it seems that both H and V scalers must be active
324                    to work correctly */
325                 mode = (h || v) ? 0x30 : 0x00;
326         }
327         return em28xx_write_reg(dev, EM28XX_R26_COMPR, mode);
328 }
329
330 /* FIXME: this only function read values from dev */
331 static int em28xx_resolution_set(struct em28xx *dev)
332 {
333         struct em28xx_v4l2 *v4l2 = dev->v4l2;
334         int width = norm_maxw(dev);
335         int height = norm_maxh(dev);
336
337         /* Properly setup VBI */
338         v4l2->vbi_width = 720;
339         if (v4l2->norm & V4L2_STD_525_60)
340                 v4l2->vbi_height = 12;
341         else
342                 v4l2->vbi_height = 18;
343
344         em28xx_set_outfmt(dev);
345
346         em28xx_accumulator_set(dev, 1, (width - 4) >> 2, 1, (height - 4) >> 2);
347
348         /* If we don't set the start position to 2 in VBI mode, we end up
349            with line 20/21 being YUYV encoded instead of being in 8-bit
350            greyscale.  The core of the issue is that line 21 (and line 23 for
351            PAL WSS) are inside of active video region, and as a result they
352            get the pixelformatting associated with that area.  So by cropping
353            it out, we end up with the same format as the rest of the VBI
354            region */
355         if (em28xx_vbi_supported(dev) == 1)
356                 em28xx_capture_area_set(dev, 0, 2, width, height);
357         else
358                 em28xx_capture_area_set(dev, 0, 0, width, height);
359
360         return em28xx_scaler_set(dev, v4l2->hscale, v4l2->vscale);
361 }
362
363 /* Set USB alternate setting for analog video */
364 static int em28xx_set_alternate(struct em28xx *dev)
365 {
366         struct em28xx_v4l2 *v4l2 = dev->v4l2;
367         struct usb_device *udev = interface_to_usbdev(dev->intf);
368         int errCode;
369         int i;
370         unsigned int min_pkt_size = v4l2->width * 2 + 4;
371
372         /* NOTE: for isoc transfers, only alt settings > 0 are allowed
373                  bulk transfers seem to work only with alt=0 ! */
374         dev->alt = 0;
375         if ((alt > 0) && (alt < dev->num_alt)) {
376                 em28xx_videodbg("alternate forced to %d\n", dev->alt);
377                 dev->alt = alt;
378                 goto set_alt;
379         }
380         if (dev->analog_xfer_bulk)
381                 goto set_alt;
382
383         /* When image size is bigger than a certain value,
384            the frame size should be increased, otherwise, only
385            green screen will be received.
386          */
387         if (v4l2->width * 2 * v4l2->height > 720 * 240 * 2)
388                 min_pkt_size *= 2;
389
390         for (i = 0; i < dev->num_alt; i++) {
391                 /* stop when the selected alt setting offers enough bandwidth */
392                 if (dev->alt_max_pkt_size_isoc[i] >= min_pkt_size) {
393                         dev->alt = i;
394                         break;
395                 /* otherwise make sure that we end up with the maximum bandwidth
396                    because the min_pkt_size equation might be wrong...
397                 */
398                 } else if (dev->alt_max_pkt_size_isoc[i] >
399                            dev->alt_max_pkt_size_isoc[dev->alt])
400                         dev->alt = i;
401         }
402
403 set_alt:
404         /* NOTE: for bulk transfers, we need to call usb_set_interface()
405          * even if the previous settings were the same. Otherwise streaming
406          * fails with all urbs having status = -EOVERFLOW ! */
407         if (dev->analog_xfer_bulk) {
408                 dev->max_pkt_size = 512; /* USB 2.0 spec */
409                 dev->packet_multiplier = EM28XX_BULK_PACKET_MULTIPLIER;
410         } else { /* isoc */
411                 em28xx_videodbg("minimum isoc packet size: %u (alt=%d)\n",
412                                 min_pkt_size, dev->alt);
413                 dev->max_pkt_size =
414                                   dev->alt_max_pkt_size_isoc[dev->alt];
415                 dev->packet_multiplier = EM28XX_NUM_ISOC_PACKETS;
416         }
417         em28xx_videodbg("setting alternate %d with wMaxPacketSize=%u\n",
418                         dev->alt, dev->max_pkt_size);
419         errCode = usb_set_interface(udev, dev->ifnum, dev->alt);
420         if (errCode < 0) {
421                 dev_err(&dev->intf->dev,
422                         "cannot change alternate number to %d (error=%i)\n",
423                         dev->alt, errCode);
424                 return errCode;
425         }
426         return 0;
427 }
428
429 /* ------------------------------------------------------------------
430         DMA and thread functions
431    ------------------------------------------------------------------*/
432
433 /*
434  * Finish the current buffer
435  */
436 static inline void finish_buffer(struct em28xx *dev,
437                                  struct em28xx_buffer *buf)
438 {
439         em28xx_isocdbg("[%p/%d] wakeup\n", buf, buf->top_field);
440
441         buf->vb.sequence = dev->v4l2->field_count++;
442         if (dev->v4l2->progressive)
443                 buf->vb.field = V4L2_FIELD_NONE;
444         else
445                 buf->vb.field = V4L2_FIELD_INTERLACED;
446         buf->vb.vb2_buf.timestamp = ktime_get_ns();
447
448         vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_DONE);
449 }
450
451 /*
452  * Copy picture data from USB buffer to videobuf buffer
453  */
454 static void em28xx_copy_video(struct em28xx *dev,
455                               struct em28xx_buffer *buf,
456                               unsigned char *usb_buf,
457                               unsigned long len)
458 {
459         struct em28xx_v4l2 *v4l2 = dev->v4l2;
460         void *fieldstart, *startwrite, *startread;
461         int  linesdone, currlinedone, offset, lencopy, remain;
462         int bytesperline = v4l2->width << 1;
463
464         if (buf->pos + len > buf->length)
465                 len = buf->length - buf->pos;
466
467         startread = usb_buf;
468         remain = len;
469
470         if (v4l2->progressive || buf->top_field)
471                 fieldstart = buf->vb_buf;
472         else /* interlaced mode, even nr. of lines */
473                 fieldstart = buf->vb_buf + bytesperline;
474
475         linesdone = buf->pos / bytesperline;
476         currlinedone = buf->pos % bytesperline;
477
478         if (v4l2->progressive)
479                 offset = linesdone * bytesperline + currlinedone;
480         else
481                 offset = linesdone * bytesperline * 2 + currlinedone;
482
483         startwrite = fieldstart + offset;
484         lencopy = bytesperline - currlinedone;
485         lencopy = lencopy > remain ? remain : lencopy;
486
487         if ((char *)startwrite + lencopy > (char *)buf->vb_buf + buf->length) {
488                 em28xx_isocdbg("Overflow of %zu bytes past buffer end (1)\n",
489                                ((char *)startwrite + lencopy) -
490                               ((char *)buf->vb_buf + buf->length));
491                 remain = (char *)buf->vb_buf + buf->length -
492                          (char *)startwrite;
493                 lencopy = remain;
494         }
495         if (lencopy <= 0)
496                 return;
497         memcpy(startwrite, startread, lencopy);
498
499         remain -= lencopy;
500
501         while (remain > 0) {
502                 if (v4l2->progressive)
503                         startwrite += lencopy;
504                 else
505                         startwrite += lencopy + bytesperline;
506                 startread += lencopy;
507                 if (bytesperline > remain)
508                         lencopy = remain;
509                 else
510                         lencopy = bytesperline;
511
512                 if ((char *)startwrite + lencopy > (char *)buf->vb_buf +
513                     buf->length) {
514                         em28xx_isocdbg("Overflow of %zu bytes past buffer end(2)\n",
515                                        ((char *)startwrite + lencopy) -
516                                        ((char *)buf->vb_buf + buf->length));
517                         lencopy = remain = (char *)buf->vb_buf + buf->length -
518                                 (char *)startwrite;
519                 }
520                 if (lencopy <= 0)
521                         break;
522
523                 memcpy(startwrite, startread, lencopy);
524
525                 remain -= lencopy;
526         }
527
528         buf->pos += len;
529 }
530
531 /*
532  * Copy VBI data from USB buffer to videobuf buffer
533  */
534 static void em28xx_copy_vbi(struct em28xx *dev,
535                             struct em28xx_buffer *buf,
536                             unsigned char *usb_buf,
537                             unsigned long len)
538 {
539         unsigned int offset;
540
541         if (buf->pos + len > buf->length)
542                 len = buf->length - buf->pos;
543
544         offset = buf->pos;
545         /* Make sure the bottom field populates the second half of the frame */
546         if (buf->top_field == 0)
547                 offset += dev->v4l2->vbi_width * dev->v4l2->vbi_height;
548
549         memcpy(buf->vb_buf + offset, usb_buf, len);
550         buf->pos += len;
551 }
552
553 static inline void print_err_status(struct em28xx *dev,
554                                     int packet, int status)
555 {
556         char *errmsg = "Unknown";
557
558         switch (status) {
559         case -ENOENT:
560                 errmsg = "unlinked synchronuously";
561                 break;
562         case -ECONNRESET:
563                 errmsg = "unlinked asynchronuously";
564                 break;
565         case -ENOSR:
566                 errmsg = "Buffer error (overrun)";
567                 break;
568         case -EPIPE:
569                 errmsg = "Stalled (device not responding)";
570                 break;
571         case -EOVERFLOW:
572                 errmsg = "Babble (bad cable?)";
573                 break;
574         case -EPROTO:
575                 errmsg = "Bit-stuff error (bad cable?)";
576                 break;
577         case -EILSEQ:
578                 errmsg = "CRC/Timeout (could be anything)";
579                 break;
580         case -ETIME:
581                 errmsg = "Device does not respond";
582                 break;
583         }
584         if (packet < 0) {
585                 em28xx_isocdbg("URB status %d [%s].\n", status, errmsg);
586         } else {
587                 em28xx_isocdbg("URB packet %d, status %d [%s].\n",
588                                packet, status, errmsg);
589         }
590 }
591
592 /*
593  * get the next available buffer from dma queue
594  */
595 static inline struct em28xx_buffer *get_next_buf(struct em28xx *dev,
596                                                  struct em28xx_dmaqueue *dma_q)
597 {
598         struct em28xx_buffer *buf;
599
600         if (list_empty(&dma_q->active)) {
601                 em28xx_isocdbg("No active queue to serve\n");
602                 return NULL;
603         }
604
605         /* Get the next buffer */
606         buf = list_entry(dma_q->active.next, struct em28xx_buffer, list);
607         /* Cleans up buffer - Useful for testing for frame/URB loss */
608         list_del(&buf->list);
609         buf->pos = 0;
610         buf->vb_buf = buf->mem;
611
612         return buf;
613 }
614
615 /*
616  * Finish the current buffer if completed and prepare for the next field
617  */
618 static struct em28xx_buffer *
619 finish_field_prepare_next(struct em28xx *dev,
620                           struct em28xx_buffer *buf,
621                           struct em28xx_dmaqueue *dma_q)
622 {
623         struct em28xx_v4l2 *v4l2 = dev->v4l2;
624
625         if (v4l2->progressive || v4l2->top_field) { /* Brand new frame */
626                 if (buf != NULL)
627                         finish_buffer(dev, buf);
628                 buf = get_next_buf(dev, dma_q);
629         }
630         if (buf != NULL) {
631                 buf->top_field = v4l2->top_field;
632                 buf->pos = 0;
633         }
634
635         return buf;
636 }
637
638 /*
639  * Process data packet according to the em2710/em2750/em28xx frame data format
640  */
641 static inline void process_frame_data_em28xx(struct em28xx *dev,
642                                              unsigned char *data_pkt,
643                                              unsigned int  data_len)
644 {
645         struct em28xx_v4l2      *v4l2 = dev->v4l2;
646         struct em28xx_buffer    *buf = dev->usb_ctl.vid_buf;
647         struct em28xx_buffer    *vbi_buf = dev->usb_ctl.vbi_buf;
648         struct em28xx_dmaqueue  *dma_q = &dev->vidq;
649         struct em28xx_dmaqueue  *vbi_dma_q = &dev->vbiq;
650
651         /* capture type 0 = vbi start
652            capture type 1 = vbi in progress
653            capture type 2 = video start
654            capture type 3 = video in progress */
655         if (data_len >= 4) {
656                 /* NOTE: Headers are always 4 bytes and
657                  * never split across packets */
658                 if (data_pkt[0] == 0x88 && data_pkt[1] == 0x88 &&
659                     data_pkt[2] == 0x88 && data_pkt[3] == 0x88) {
660                         /* Continuation */
661                         data_pkt += 4;
662                         data_len -= 4;
663                 } else if (data_pkt[0] == 0x33 && data_pkt[1] == 0x95) {
664                         /* Field start (VBI mode) */
665                         v4l2->capture_type = 0;
666                         v4l2->vbi_read = 0;
667                         em28xx_isocdbg("VBI START HEADER !!!\n");
668                         v4l2->top_field = !(data_pkt[2] & 1);
669                         data_pkt += 4;
670                         data_len -= 4;
671                 } else if (data_pkt[0] == 0x22 && data_pkt[1] == 0x5a) {
672                         /* Field start (VBI disabled) */
673                         v4l2->capture_type = 2;
674                         em28xx_isocdbg("VIDEO START HEADER !!!\n");
675                         v4l2->top_field = !(data_pkt[2] & 1);
676                         data_pkt += 4;
677                         data_len -= 4;
678                 }
679         }
680         /* NOTE: With bulk transfers, intermediate data packets
681          * have no continuation header */
682
683         if (v4l2->capture_type == 0) {
684                 vbi_buf = finish_field_prepare_next(dev, vbi_buf, vbi_dma_q);
685                 dev->usb_ctl.vbi_buf = vbi_buf;
686                 v4l2->capture_type = 1;
687         }
688
689         if (v4l2->capture_type == 1) {
690                 int vbi_size = v4l2->vbi_width * v4l2->vbi_height;
691                 int vbi_data_len = ((v4l2->vbi_read + data_len) > vbi_size) ?
692                                    (vbi_size - v4l2->vbi_read) : data_len;
693
694                 /* Copy VBI data */
695                 if (vbi_buf != NULL)
696                         em28xx_copy_vbi(dev, vbi_buf, data_pkt, vbi_data_len);
697                 v4l2->vbi_read += vbi_data_len;
698
699                 if (vbi_data_len < data_len) {
700                         /* Continue with copying video data */
701                         v4l2->capture_type = 2;
702                         data_pkt += vbi_data_len;
703                         data_len -= vbi_data_len;
704                 }
705         }
706
707         if (v4l2->capture_type == 2) {
708                 buf = finish_field_prepare_next(dev, buf, dma_q);
709                 dev->usb_ctl.vid_buf = buf;
710                 v4l2->capture_type = 3;
711         }
712
713         if (v4l2->capture_type == 3 && buf != NULL && data_len > 0)
714                 em28xx_copy_video(dev, buf, data_pkt, data_len);
715 }
716
717 /*
718  * Process data packet according to the em25xx/em276x/7x/8x frame data format
719  */
720 static inline void process_frame_data_em25xx(struct em28xx *dev,
721                                              unsigned char *data_pkt,
722                                              unsigned int  data_len)
723 {
724         struct em28xx_buffer    *buf = dev->usb_ctl.vid_buf;
725         struct em28xx_dmaqueue  *dmaq = &dev->vidq;
726         struct em28xx_v4l2      *v4l2 = dev->v4l2;
727         bool frame_end = false;
728
729         /* Check for header */
730         /* NOTE: at least with bulk transfers, only the first packet
731          * has a header and has always set the FRAME_END bit         */
732         if (data_len >= 2) {    /* em25xx header is only 2 bytes long */
733                 if ((data_pkt[0] == EM25XX_FRMDATAHDR_BYTE1) &&
734                     ((data_pkt[1] & ~EM25XX_FRMDATAHDR_BYTE2_MASK) == 0x00)) {
735                         v4l2->top_field = !(data_pkt[1] &
736                                            EM25XX_FRMDATAHDR_BYTE2_FRAME_ID);
737                         frame_end = data_pkt[1] &
738                                     EM25XX_FRMDATAHDR_BYTE2_FRAME_END;
739                         data_pkt += 2;
740                         data_len -= 2;
741                 }
742
743                 /* Finish field and prepare next (BULK only) */
744                 if (dev->analog_xfer_bulk && frame_end) {
745                         buf = finish_field_prepare_next(dev, buf, dmaq);
746                         dev->usb_ctl.vid_buf = buf;
747                 }
748                 /* NOTE: in ISOC mode when a new frame starts and buf==NULL,
749                  * we COULD already prepare a buffer here to avoid skipping the
750                  * first frame.
751                  */
752         }
753
754         /* Copy data */
755         if (buf != NULL && data_len > 0)
756                 em28xx_copy_video(dev, buf, data_pkt, data_len);
757
758         /* Finish frame (ISOC only) => avoids lag of 1 frame */
759         if (!dev->analog_xfer_bulk && frame_end) {
760                 buf = finish_field_prepare_next(dev, buf, dmaq);
761                 dev->usb_ctl.vid_buf = buf;
762         }
763
764         /* NOTE: Tested with USB bulk transfers only !
765          * The wording in the datasheet suggests that isoc might work different.
766          * The current code assumes that with isoc transfers each packet has a
767          * header like with the other em28xx devices.
768          */
769         /* NOTE: Support for interlaced mode is pure theory. It has not been
770          * tested and it is unknown if these devices actually support it. */
771         /* NOTE: No VBI support yet (these chips likely do not support VBI). */
772 }
773
774 /* Processes and copies the URB data content (video and VBI data) */
775 static inline int em28xx_urb_data_copy(struct em28xx *dev, struct urb *urb)
776 {
777         int xfer_bulk, num_packets, i;
778         unsigned char *usb_data_pkt;
779         unsigned int usb_data_len;
780
781         if (!dev)
782                 return 0;
783
784         if (dev->disconnected)
785                 return 0;
786
787         if (urb->status < 0)
788                 print_err_status(dev, -1, urb->status);
789
790         xfer_bulk = usb_pipebulk(urb->pipe);
791
792         if (xfer_bulk) /* bulk */
793                 num_packets = 1;
794         else /* isoc */
795                 num_packets = urb->number_of_packets;
796
797         for (i = 0; i < num_packets; i++) {
798                 if (xfer_bulk) { /* bulk */
799                         usb_data_len = urb->actual_length;
800
801                         usb_data_pkt = urb->transfer_buffer;
802                 } else { /* isoc */
803                         if (urb->iso_frame_desc[i].status < 0) {
804                                 print_err_status(dev, i,
805                                                  urb->iso_frame_desc[i].status);
806                                 if (urb->iso_frame_desc[i].status != -EPROTO)
807                                         continue;
808                         }
809
810                         usb_data_len = urb->iso_frame_desc[i].actual_length;
811                         if (usb_data_len > dev->max_pkt_size) {
812                                 em28xx_isocdbg("packet bigger than packet size");
813                                 continue;
814                         }
815
816                         usb_data_pkt = urb->transfer_buffer +
817                                        urb->iso_frame_desc[i].offset;
818                 }
819
820                 if (usb_data_len == 0) {
821                         /* NOTE: happens very often with isoc transfers */
822                         /* em28xx_usbdbg("packet %d is empty",i); - spammy */
823                         continue;
824                 }
825
826                 if (dev->is_em25xx)
827                         process_frame_data_em25xx(dev,
828                                                   usb_data_pkt, usb_data_len);
829                 else
830                         process_frame_data_em28xx(dev,
831                                                   usb_data_pkt, usb_data_len);
832
833         }
834         return 1;
835 }
836
837 static int get_ressource(enum v4l2_buf_type f_type)
838 {
839         switch (f_type) {
840         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
841                 return EM28XX_RESOURCE_VIDEO;
842         case V4L2_BUF_TYPE_VBI_CAPTURE:
843                 return EM28XX_RESOURCE_VBI;
844         default:
845                 BUG();
846         }
847 }
848
849 /* Usage lock check functions */
850 static int res_get(struct em28xx *dev, enum v4l2_buf_type f_type)
851 {
852         int res_type = get_ressource(f_type);
853
854         /* is it free? */
855         if (dev->resources & res_type) {
856                 /* no, someone else uses it */
857                 return -EBUSY;
858         }
859
860         /* it's free, grab it */
861         dev->resources |= res_type;
862         em28xx_videodbg("res: get %d\n", res_type);
863         return 0;
864 }
865
866 static void res_free(struct em28xx *dev, enum v4l2_buf_type f_type)
867 {
868         int res_type = get_ressource(f_type);
869
870         dev->resources &= ~res_type;
871         em28xx_videodbg("res: put %d\n", res_type);
872 }
873
874 static void em28xx_v4l2_media_release(struct em28xx *dev)
875 {
876 #ifdef CONFIG_MEDIA_CONTROLLER
877         int i;
878
879         for (i = 0; i < MAX_EM28XX_INPUT; i++) {
880                 if (!INPUT(i)->type)
881                         return;
882                 media_device_unregister_entity(&dev->input_ent[i]);
883         }
884 #endif
885 }
886
887 /*
888  * Media Controller helper functions
889  */
890
891 static int em28xx_enable_analog_tuner(struct em28xx *dev)
892 {
893 #ifdef CONFIG_MEDIA_CONTROLLER
894         struct media_device *mdev = dev->media_dev;
895         struct em28xx_v4l2 *v4l2 = dev->v4l2;
896         struct media_entity *source;
897         struct media_link *link, *found_link = NULL;
898         int ret, active_links = 0;
899
900         if (!mdev || !v4l2->decoder)
901                 return 0;
902
903         /*
904          * This will find the tuner that is connected into the decoder.
905          * Technically, this is not 100% correct, as the device may be
906          * using an analog input instead of the tuner. However, as we can't
907          * do DVB streaming while the DMA engine is being used for V4L2,
908          * this should be enough for the actual needs.
909          */
910         list_for_each_entry(link, &v4l2->decoder->links, list) {
911                 if (link->sink->entity == v4l2->decoder) {
912                         found_link = link;
913                         if (link->flags & MEDIA_LNK_FL_ENABLED)
914                                 active_links++;
915                         break;
916                 }
917         }
918
919         if (active_links == 1 || !found_link)
920                 return 0;
921
922         source = found_link->source->entity;
923         list_for_each_entry(link, &source->links, list) {
924                 struct media_entity *sink;
925                 int flags = 0;
926
927                 sink = link->sink->entity;
928
929                 if (sink == v4l2->decoder)
930                         flags = MEDIA_LNK_FL_ENABLED;
931
932                 ret = media_entity_setup_link(link, flags);
933                 if (ret) {
934                         dev_err(&dev->intf->dev,
935                                 "Couldn't change link %s->%s to %s. Error %d\n",
936                                 source->name, sink->name,
937                                 flags ? "enabled" : "disabled",
938                                 ret);
939                         return ret;
940                 } else
941                         em28xx_videodbg("link %s->%s was %s\n",
942                                         source->name, sink->name,
943                                         flags ? "ENABLED" : "disabled");
944         }
945 #endif
946         return 0;
947 }
948
949 static const char * const iname[] = {
950         [EM28XX_VMUX_COMPOSITE]  = "Composite",
951         [EM28XX_VMUX_SVIDEO]     = "S-Video",
952         [EM28XX_VMUX_TELEVISION] = "Television",
953         [EM28XX_RADIO]           = "Radio",
954 };
955
956 static void em28xx_v4l2_create_entities(struct em28xx *dev)
957 {
958 #if defined(CONFIG_MEDIA_CONTROLLER)
959         struct em28xx_v4l2 *v4l2 = dev->v4l2;
960         int ret, i;
961
962         /* Initialize Video, VBI and Radio pads */
963         v4l2->video_pad.flags = MEDIA_PAD_FL_SINK;
964         ret = media_entity_pads_init(&v4l2->vdev.entity, 1, &v4l2->video_pad);
965         if (ret < 0)
966                 dev_err(&dev->intf->dev,
967                         "failed to initialize video media entity!\n");
968
969         if (em28xx_vbi_supported(dev)) {
970                 v4l2->vbi_pad.flags = MEDIA_PAD_FL_SINK;
971                 ret = media_entity_pads_init(&v4l2->vbi_dev.entity, 1,
972                                              &v4l2->vbi_pad);
973                 if (ret < 0)
974                         dev_err(&dev->intf->dev,
975                                 "failed to initialize vbi media entity!\n");
976         }
977
978         /* Webcams don't have input connectors */
979         if (dev->board.is_webcam)
980                 return;
981
982         /* Create entities for each input connector */
983         for (i = 0; i < MAX_EM28XX_INPUT; i++) {
984                 struct media_entity *ent = &dev->input_ent[i];
985
986                 if (!INPUT(i)->type)
987                         break;
988
989                 ent->name = iname[INPUT(i)->type];
990                 ent->flags = MEDIA_ENT_FL_CONNECTOR;
991                 dev->input_pad[i].flags = MEDIA_PAD_FL_SOURCE;
992
993                 switch (INPUT(i)->type) {
994                 case EM28XX_VMUX_COMPOSITE:
995                         ent->function = MEDIA_ENT_F_CONN_COMPOSITE;
996                         break;
997                 case EM28XX_VMUX_SVIDEO:
998                         ent->function = MEDIA_ENT_F_CONN_SVIDEO;
999                         break;
1000                 default: /* EM28XX_VMUX_TELEVISION or EM28XX_RADIO */
1001                         if (dev->tuner_type != TUNER_ABSENT)
1002                                 ent->function = MEDIA_ENT_F_CONN_RF;
1003                         break;
1004                 }
1005
1006                 ret = media_entity_pads_init(ent, 1, &dev->input_pad[i]);
1007                 if (ret < 0)
1008                         dev_err(&dev->intf->dev,
1009                                 "failed to initialize input pad[%d]!\n", i);
1010
1011                 ret = media_device_register_entity(dev->media_dev, ent);
1012                 if (ret < 0)
1013                         dev_err(&dev->intf->dev,
1014                                 "failed to register input entity %d!\n", i);
1015         }
1016 #endif
1017 }
1018
1019
1020 /* ------------------------------------------------------------------
1021         Videobuf2 operations
1022    ------------------------------------------------------------------*/
1023
1024 static int queue_setup(struct vb2_queue *vq,
1025                        unsigned int *nbuffers, unsigned int *nplanes,
1026                        unsigned int sizes[], struct device *alloc_devs[])
1027 {
1028         struct em28xx *dev = vb2_get_drv_priv(vq);
1029         struct em28xx_v4l2 *v4l2 = dev->v4l2;
1030         unsigned long size =
1031                     (v4l2->width * v4l2->height * v4l2->format->depth + 7) >> 3;
1032
1033         if (*nplanes)
1034                 return sizes[0] < size ? -EINVAL : 0;
1035         *nplanes = 1;
1036         sizes[0] = size;
1037
1038         em28xx_enable_analog_tuner(dev);
1039
1040         return 0;
1041 }
1042
1043 static int
1044 buffer_prepare(struct vb2_buffer *vb)
1045 {
1046         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1047         struct em28xx        *dev = vb2_get_drv_priv(vb->vb2_queue);
1048         struct em28xx_v4l2   *v4l2 = dev->v4l2;
1049         unsigned long size;
1050
1051         em28xx_videodbg("%s, field=%d\n", __func__, vbuf->field);
1052
1053         size = (v4l2->width * v4l2->height * v4l2->format->depth + 7) >> 3;
1054
1055         if (vb2_plane_size(vb, 0) < size) {
1056                 em28xx_videodbg("%s data will not fit into plane (%lu < %lu)\n",
1057                                 __func__, vb2_plane_size(vb, 0), size);
1058                 return -EINVAL;
1059         }
1060         vb2_set_plane_payload(vb, 0, size);
1061
1062         return 0;
1063 }
1064
1065 int em28xx_start_analog_streaming(struct vb2_queue *vq, unsigned int count)
1066 {
1067         struct em28xx *dev = vb2_get_drv_priv(vq);
1068         struct em28xx_v4l2 *v4l2 = dev->v4l2;
1069         struct v4l2_frequency f;
1070         struct v4l2_fh *owner;
1071         int rc = 0;
1072
1073         em28xx_videodbg("%s\n", __func__);
1074
1075         /* Make sure streaming is not already in progress for this type
1076            of filehandle (e.g. video, vbi) */
1077         rc = res_get(dev, vq->type);
1078         if (rc)
1079                 return rc;
1080
1081         if (v4l2->streaming_users == 0) {
1082                 /* First active streaming user, so allocate all the URBs */
1083
1084                 /* Allocate the USB bandwidth */
1085                 em28xx_set_alternate(dev);
1086
1087                 /* Needed, since GPIO might have disabled power of
1088                    some i2c device
1089                 */
1090                 em28xx_wake_i2c(dev);
1091
1092                 v4l2->capture_type = -1;
1093                 rc = em28xx_init_usb_xfer(dev, EM28XX_ANALOG_MODE,
1094                                           dev->analog_xfer_bulk,
1095                                           EM28XX_NUM_BUFS,
1096                                           dev->max_pkt_size,
1097                                           dev->packet_multiplier,
1098                                           em28xx_urb_data_copy);
1099                 if (rc < 0)
1100                         return rc;
1101
1102                 /*
1103                  * djh: it's not clear whether this code is still needed.  I'm
1104                  * leaving it in here for now entirely out of concern for
1105                  * backward compatibility (the old code did it)
1106                  */
1107
1108                 /* Ask tuner to go to analog or radio mode */
1109                 memset(&f, 0, sizeof(f));
1110                 f.frequency = v4l2->frequency;
1111                 owner = (struct v4l2_fh *)vq->owner;
1112                 if (owner && owner->vdev->vfl_type == VFL_TYPE_RADIO)
1113                         f.type = V4L2_TUNER_RADIO;
1114                 else
1115                         f.type = V4L2_TUNER_ANALOG_TV;
1116                 v4l2_device_call_all(&v4l2->v4l2_dev,
1117                                      0, tuner, s_frequency, &f);
1118
1119                 /* Enable video stream at TV decoder */
1120                 v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 1);
1121         }
1122
1123         v4l2->streaming_users++;
1124
1125         return rc;
1126 }
1127
1128 static void em28xx_stop_streaming(struct vb2_queue *vq)
1129 {
1130         struct em28xx *dev = vb2_get_drv_priv(vq);
1131         struct em28xx_v4l2 *v4l2 = dev->v4l2;
1132         struct em28xx_dmaqueue *vidq = &dev->vidq;
1133         unsigned long flags = 0;
1134
1135         em28xx_videodbg("%s\n", __func__);
1136
1137         res_free(dev, vq->type);
1138
1139         if (v4l2->streaming_users-- == 1) {
1140                 /* Disable video stream at TV decoder */
1141                 v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 0);
1142
1143                 /* Last active user, so shutdown all the URBS */
1144                 em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
1145         }
1146
1147         spin_lock_irqsave(&dev->slock, flags);
1148         if (dev->usb_ctl.vid_buf != NULL) {
1149                 vb2_buffer_done(&dev->usb_ctl.vid_buf->vb.vb2_buf,
1150                                 VB2_BUF_STATE_ERROR);
1151                 dev->usb_ctl.vid_buf = NULL;
1152         }
1153         while (!list_empty(&vidq->active)) {
1154                 struct em28xx_buffer *buf;
1155
1156                 buf = list_entry(vidq->active.next, struct em28xx_buffer, list);
1157                 list_del(&buf->list);
1158                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1159         }
1160         spin_unlock_irqrestore(&dev->slock, flags);
1161 }
1162
1163 void em28xx_stop_vbi_streaming(struct vb2_queue *vq)
1164 {
1165         struct em28xx *dev = vb2_get_drv_priv(vq);
1166         struct em28xx_v4l2 *v4l2 = dev->v4l2;
1167         struct em28xx_dmaqueue *vbiq = &dev->vbiq;
1168         unsigned long flags = 0;
1169
1170         em28xx_videodbg("%s\n", __func__);
1171
1172         res_free(dev, vq->type);
1173
1174         if (v4l2->streaming_users-- == 1) {
1175                 /* Disable video stream at TV decoder */
1176                 v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 0);
1177
1178                 /* Last active user, so shutdown all the URBS */
1179                 em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
1180         }
1181
1182         spin_lock_irqsave(&dev->slock, flags);
1183         if (dev->usb_ctl.vbi_buf != NULL) {
1184                 vb2_buffer_done(&dev->usb_ctl.vbi_buf->vb.vb2_buf,
1185                                 VB2_BUF_STATE_ERROR);
1186                 dev->usb_ctl.vbi_buf = NULL;
1187         }
1188         while (!list_empty(&vbiq->active)) {
1189                 struct em28xx_buffer *buf;
1190
1191                 buf = list_entry(vbiq->active.next, struct em28xx_buffer, list);
1192                 list_del(&buf->list);
1193                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1194         }
1195         spin_unlock_irqrestore(&dev->slock, flags);
1196 }
1197
1198 static void
1199 buffer_queue(struct vb2_buffer *vb)
1200 {
1201         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1202         struct em28xx *dev = vb2_get_drv_priv(vb->vb2_queue);
1203         struct em28xx_buffer *buf =
1204                 container_of(vbuf, struct em28xx_buffer, vb);
1205         struct em28xx_dmaqueue *vidq = &dev->vidq;
1206         unsigned long flags = 0;
1207
1208         em28xx_videodbg("%s\n", __func__);
1209         buf->mem = vb2_plane_vaddr(vb, 0);
1210         buf->length = vb2_plane_size(vb, 0);
1211
1212         spin_lock_irqsave(&dev->slock, flags);
1213         list_add_tail(&buf->list, &vidq->active);
1214         spin_unlock_irqrestore(&dev->slock, flags);
1215 }
1216
1217 static const struct vb2_ops em28xx_video_qops = {
1218         .queue_setup    = queue_setup,
1219         .buf_prepare    = buffer_prepare,
1220         .buf_queue      = buffer_queue,
1221         .start_streaming = em28xx_start_analog_streaming,
1222         .stop_streaming = em28xx_stop_streaming,
1223         .wait_prepare   = vb2_ops_wait_prepare,
1224         .wait_finish    = vb2_ops_wait_finish,
1225 };
1226
1227 static int em28xx_vb2_setup(struct em28xx *dev)
1228 {
1229         int rc;
1230         struct vb2_queue *q;
1231         struct em28xx_v4l2 *v4l2 = dev->v4l2;
1232
1233         /* Setup Videobuf2 for Video capture */
1234         q = &v4l2->vb_vidq;
1235         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1236         q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1237         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1238         q->drv_priv = dev;
1239         q->buf_struct_size = sizeof(struct em28xx_buffer);
1240         q->ops = &em28xx_video_qops;
1241         q->mem_ops = &vb2_vmalloc_memops;
1242
1243         rc = vb2_queue_init(q);
1244         if (rc < 0)
1245                 return rc;
1246
1247         /* Setup Videobuf2 for VBI capture */
1248         q = &v4l2->vb_vbiq;
1249         q->type = V4L2_BUF_TYPE_VBI_CAPTURE;
1250         q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR;
1251         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1252         q->drv_priv = dev;
1253         q->buf_struct_size = sizeof(struct em28xx_buffer);
1254         q->ops = &em28xx_vbi_qops;
1255         q->mem_ops = &vb2_vmalloc_memops;
1256
1257         rc = vb2_queue_init(q);
1258         if (rc < 0)
1259                 return rc;
1260
1261         return 0;
1262 }
1263
1264 /*********************  v4l2 interface  **************************************/
1265
1266 static void video_mux(struct em28xx *dev, int index)
1267 {
1268         struct v4l2_device *v4l2_dev = &dev->v4l2->v4l2_dev;
1269
1270         dev->ctl_input = index;
1271         dev->ctl_ainput = INPUT(index)->amux;
1272         dev->ctl_aoutput = INPUT(index)->aout;
1273
1274         if (!dev->ctl_aoutput)
1275                 dev->ctl_aoutput = EM28XX_AOUT_MASTER;
1276
1277         v4l2_device_call_all(v4l2_dev, 0, video, s_routing,
1278                              INPUT(index)->vmux, 0, 0);
1279
1280         if (dev->board.has_msp34xx) {
1281                 if (dev->i2s_speed) {
1282                         v4l2_device_call_all(v4l2_dev, 0, audio,
1283                                              s_i2s_clock_freq, dev->i2s_speed);
1284                 }
1285                 /* Note: this is msp3400 specific */
1286                 v4l2_device_call_all(v4l2_dev, 0, audio, s_routing,
1287                                      dev->ctl_ainput,
1288                                      MSP_OUTPUT(MSP_SC_IN_DSP_SCART1), 0);
1289         }
1290
1291         if (dev->board.adecoder != EM28XX_NOADECODER) {
1292                 v4l2_device_call_all(v4l2_dev, 0, audio, s_routing,
1293                                      dev->ctl_ainput, dev->ctl_aoutput, 0);
1294         }
1295
1296         em28xx_audio_analog_set(dev);
1297 }
1298
1299 static void em28xx_ctrl_notify(struct v4l2_ctrl *ctrl, void *priv)
1300 {
1301         struct em28xx *dev = priv;
1302
1303         /*
1304          * In the case of non-AC97 volume controls, we still need
1305          * to do some setups at em28xx, in order to mute/unmute
1306          * and to adjust audio volume. However, the value ranges
1307          * should be checked by the corresponding V4L subdriver.
1308          */
1309         switch (ctrl->id) {
1310         case V4L2_CID_AUDIO_MUTE:
1311                 dev->mute = ctrl->val;
1312                 em28xx_audio_analog_set(dev);
1313                 break;
1314         case V4L2_CID_AUDIO_VOLUME:
1315                 dev->volume = ctrl->val;
1316                 em28xx_audio_analog_set(dev);
1317                 break;
1318         }
1319 }
1320
1321 static int em28xx_s_ctrl(struct v4l2_ctrl *ctrl)
1322 {
1323         struct em28xx_v4l2 *v4l2 =
1324                   container_of(ctrl->handler, struct em28xx_v4l2, ctrl_handler);
1325         struct em28xx *dev = v4l2->dev;
1326         int ret = -EINVAL;
1327
1328         switch (ctrl->id) {
1329         case V4L2_CID_AUDIO_MUTE:
1330                 dev->mute = ctrl->val;
1331                 ret = em28xx_audio_analog_set(dev);
1332                 break;
1333         case V4L2_CID_AUDIO_VOLUME:
1334                 dev->volume = ctrl->val;
1335                 ret = em28xx_audio_analog_set(dev);
1336                 break;
1337         case V4L2_CID_CONTRAST:
1338                 ret = em28xx_write_reg(dev, EM28XX_R20_YGAIN, ctrl->val);
1339                 break;
1340         case V4L2_CID_BRIGHTNESS:
1341                 ret = em28xx_write_reg(dev, EM28XX_R21_YOFFSET, ctrl->val);
1342                 break;
1343         case V4L2_CID_SATURATION:
1344                 ret = em28xx_write_reg(dev, EM28XX_R22_UVGAIN, ctrl->val);
1345                 break;
1346         case V4L2_CID_BLUE_BALANCE:
1347                 ret = em28xx_write_reg(dev, EM28XX_R23_UOFFSET, ctrl->val);
1348                 break;
1349         case V4L2_CID_RED_BALANCE:
1350                 ret = em28xx_write_reg(dev, EM28XX_R24_VOFFSET, ctrl->val);
1351                 break;
1352         case V4L2_CID_SHARPNESS:
1353                 ret = em28xx_write_reg(dev, EM28XX_R25_SHARPNESS, ctrl->val);
1354                 break;
1355         }
1356
1357         return (ret < 0) ? ret : 0;
1358 }
1359
1360 static const struct v4l2_ctrl_ops em28xx_ctrl_ops = {
1361         .s_ctrl = em28xx_s_ctrl,
1362 };
1363
1364 static void size_to_scale(struct em28xx *dev,
1365                           unsigned int width, unsigned int height,
1366                         unsigned int *hscale, unsigned int *vscale)
1367 {
1368         unsigned int          maxw = norm_maxw(dev);
1369         unsigned int          maxh = norm_maxh(dev);
1370
1371         *hscale = (((unsigned long)maxw) << 12) / width - 4096L;
1372         if (*hscale > EM28XX_HVSCALE_MAX)
1373                 *hscale = EM28XX_HVSCALE_MAX;
1374
1375         *vscale = (((unsigned long)maxh) << 12) / height - 4096L;
1376         if (*vscale > EM28XX_HVSCALE_MAX)
1377                 *vscale = EM28XX_HVSCALE_MAX;
1378 }
1379
1380 static void scale_to_size(struct em28xx *dev,
1381                           unsigned int hscale, unsigned int vscale,
1382                           unsigned int *width, unsigned int *height)
1383 {
1384         unsigned int          maxw = norm_maxw(dev);
1385         unsigned int          maxh = norm_maxh(dev);
1386
1387         *width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
1388         *height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
1389
1390         /* Don't let width or height to be zero */
1391         if (*width < 1)
1392                 *width = 1;
1393         if (*height < 1)
1394                 *height = 1;
1395 }
1396
1397 /* ------------------------------------------------------------------
1398         IOCTL vidioc handling
1399    ------------------------------------------------------------------*/
1400
1401 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1402                                 struct v4l2_format *f)
1403 {
1404         struct em28xx         *dev = video_drvdata(file);
1405         struct em28xx_v4l2    *v4l2 = dev->v4l2;
1406
1407         f->fmt.pix.width = v4l2->width;
1408         f->fmt.pix.height = v4l2->height;
1409         f->fmt.pix.pixelformat = v4l2->format->fourcc;
1410         f->fmt.pix.bytesperline = (v4l2->width * v4l2->format->depth + 7) >> 3;
1411         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * v4l2->height;
1412         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1413
1414         /* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
1415         if (v4l2->progressive)
1416                 f->fmt.pix.field = V4L2_FIELD_NONE;
1417         else
1418                 f->fmt.pix.field = v4l2->interlaced_fieldmode ?
1419                            V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
1420         return 0;
1421 }
1422
1423 static struct em28xx_fmt *format_by_fourcc(unsigned int fourcc)
1424 {
1425         unsigned int i;
1426
1427         for (i = 0; i < ARRAY_SIZE(format); i++)
1428                 if (format[i].fourcc == fourcc)
1429                         return &format[i];
1430
1431         return NULL;
1432 }
1433
1434 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1435                                   struct v4l2_format *f)
1436 {
1437         struct em28xx         *dev   = video_drvdata(file);
1438         struct em28xx_v4l2    *v4l2  = dev->v4l2;
1439         unsigned int          width  = f->fmt.pix.width;
1440         unsigned int          height = f->fmt.pix.height;
1441         unsigned int          maxw   = norm_maxw(dev);
1442         unsigned int          maxh   = norm_maxh(dev);
1443         unsigned int          hscale, vscale;
1444         struct em28xx_fmt     *fmt;
1445
1446         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1447         if (!fmt) {
1448                 em28xx_videodbg("Fourcc format (%08x) invalid.\n",
1449                                 f->fmt.pix.pixelformat);
1450                 return -EINVAL;
1451         }
1452
1453         if (dev->board.is_em2800) {
1454                 /* the em2800 can only scale down to 50% */
1455                 height = height > (3 * maxh / 4) ? maxh : maxh / 2;
1456                 width = width > (3 * maxw / 4) ? maxw : maxw / 2;
1457                 /*
1458                  * MaxPacketSize for em2800 is too small to capture at full
1459                  * resolution use half of maxw as the scaler can only scale
1460                  * to 50%
1461                  */
1462                 if (width == maxw && height == maxh)
1463                         width /= 2;
1464         } else {
1465                 /* width must even because of the YUYV format
1466                    height must be even because of interlacing */
1467                 v4l_bound_align_image(&width, 48, maxw, 1, &height, 32, maxh,
1468                                       1, 0);
1469         }
1470         /* Avoid division by zero at size_to_scale */
1471         if (width < 1)
1472                 width = 1;
1473         if (height < 1)
1474                 height = 1;
1475
1476         size_to_scale(dev, width, height, &hscale, &vscale);
1477         scale_to_size(dev, hscale, vscale, &width, &height);
1478
1479         f->fmt.pix.width = width;
1480         f->fmt.pix.height = height;
1481         f->fmt.pix.pixelformat = fmt->fourcc;
1482         f->fmt.pix.bytesperline = (width * fmt->depth + 7) >> 3;
1483         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * height;
1484         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1485         if (v4l2->progressive)
1486                 f->fmt.pix.field = V4L2_FIELD_NONE;
1487         else
1488                 f->fmt.pix.field = v4l2->interlaced_fieldmode ?
1489                            V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
1490         f->fmt.pix.priv = 0;
1491
1492         return 0;
1493 }
1494
1495 static int em28xx_set_video_format(struct em28xx *dev, unsigned int fourcc,
1496                                    unsigned width, unsigned height)
1497 {
1498         struct em28xx_fmt     *fmt;
1499         struct em28xx_v4l2    *v4l2 = dev->v4l2;
1500
1501         fmt = format_by_fourcc(fourcc);
1502         if (!fmt)
1503                 return -EINVAL;
1504
1505         v4l2->format = fmt;
1506         v4l2->width  = width;
1507         v4l2->height = height;
1508
1509         /* set new image size */
1510         size_to_scale(dev, v4l2->width, v4l2->height,
1511                       &v4l2->hscale, &v4l2->vscale);
1512
1513         em28xx_resolution_set(dev);
1514
1515         return 0;
1516 }
1517
1518 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1519                                 struct v4l2_format *f)
1520 {
1521         struct em28xx *dev = video_drvdata(file);
1522         struct em28xx_v4l2 *v4l2 = dev->v4l2;
1523
1524         if (vb2_is_busy(&v4l2->vb_vidq))
1525                 return -EBUSY;
1526
1527         vidioc_try_fmt_vid_cap(file, priv, f);
1528
1529         return em28xx_set_video_format(dev, f->fmt.pix.pixelformat,
1530                                 f->fmt.pix.width, f->fmt.pix.height);
1531 }
1532
1533 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
1534 {
1535         struct em28xx *dev = video_drvdata(file);
1536
1537         *norm = dev->v4l2->norm;
1538
1539         return 0;
1540 }
1541
1542 static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *norm)
1543 {
1544         struct em28xx *dev = video_drvdata(file);
1545
1546         v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, video, querystd, norm);
1547
1548         return 0;
1549 }
1550
1551 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
1552 {
1553         struct em28xx      *dev  = video_drvdata(file);
1554         struct em28xx_v4l2 *v4l2 = dev->v4l2;
1555         struct v4l2_format f;
1556
1557         if (norm == v4l2->norm)
1558                 return 0;
1559
1560         if (v4l2->streaming_users > 0)
1561                 return -EBUSY;
1562
1563         v4l2->norm = norm;
1564
1565         /* Adjusts width/height, if needed */
1566         f.fmt.pix.width = 720;
1567         f.fmt.pix.height = (norm & V4L2_STD_525_60) ? 480 : 576;
1568         vidioc_try_fmt_vid_cap(file, priv, &f);
1569
1570         /* set new image size */
1571         v4l2->width = f.fmt.pix.width;
1572         v4l2->height = f.fmt.pix.height;
1573         size_to_scale(dev, v4l2->width, v4l2->height,
1574                       &v4l2->hscale, &v4l2->vscale);
1575
1576         em28xx_resolution_set(dev);
1577         v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_std, v4l2->norm);
1578
1579         return 0;
1580 }
1581
1582 static int vidioc_g_parm(struct file *file, void *priv,
1583                          struct v4l2_streamparm *p)
1584 {
1585         struct em28xx      *dev  = video_drvdata(file);
1586         struct em28xx_v4l2 *v4l2 = dev->v4l2;
1587         int rc = 0;
1588
1589         p->parm.capture.readbuffers = EM28XX_MIN_BUF;
1590         if (dev->board.is_webcam)
1591                 rc = v4l2_device_call_until_err(&v4l2->v4l2_dev, 0,
1592                                                 video, g_parm, p);
1593         else
1594                 v4l2_video_std_frame_period(v4l2->norm,
1595                                             &p->parm.capture.timeperframe);
1596
1597         return rc;
1598 }
1599
1600 static int vidioc_s_parm(struct file *file, void *priv,
1601                          struct v4l2_streamparm *p)
1602 {
1603         struct em28xx *dev = video_drvdata(file);
1604
1605         p->parm.capture.readbuffers = EM28XX_MIN_BUF;
1606         return v4l2_device_call_until_err(&dev->v4l2->v4l2_dev,
1607                                           0, video, s_parm, p);
1608 }
1609
1610 static int vidioc_enum_input(struct file *file, void *priv,
1611                              struct v4l2_input *i)
1612 {
1613         struct em28xx *dev = video_drvdata(file);
1614         unsigned int       n;
1615
1616         n = i->index;
1617         if (n >= MAX_EM28XX_INPUT)
1618                 return -EINVAL;
1619         if (0 == INPUT(n)->type)
1620                 return -EINVAL;
1621
1622         i->index = n;
1623         i->type = V4L2_INPUT_TYPE_CAMERA;
1624
1625         strcpy(i->name, iname[INPUT(n)->type]);
1626
1627         if ((EM28XX_VMUX_TELEVISION == INPUT(n)->type))
1628                 i->type = V4L2_INPUT_TYPE_TUNER;
1629
1630         i->std = dev->v4l2->vdev.tvnorms;
1631         /* webcams do not have the STD API */
1632         if (dev->board.is_webcam)
1633                 i->capabilities = 0;
1634
1635         return 0;
1636 }
1637
1638 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1639 {
1640         struct em28xx *dev = video_drvdata(file);
1641
1642         *i = dev->ctl_input;
1643
1644         return 0;
1645 }
1646
1647 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1648 {
1649         struct em28xx *dev = video_drvdata(file);
1650
1651         if (i >= MAX_EM28XX_INPUT)
1652                 return -EINVAL;
1653         if (0 == INPUT(i)->type)
1654                 return -EINVAL;
1655
1656         video_mux(dev, i);
1657         return 0;
1658 }
1659
1660 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1661 {
1662         struct em28xx *dev = video_drvdata(file);
1663
1664         switch (a->index) {
1665         case EM28XX_AMUX_VIDEO:
1666                 strcpy(a->name, "Television");
1667                 break;
1668         case EM28XX_AMUX_LINE_IN:
1669                 strcpy(a->name, "Line In");
1670                 break;
1671         case EM28XX_AMUX_VIDEO2:
1672                 strcpy(a->name, "Television alt");
1673                 break;
1674         case EM28XX_AMUX_PHONE:
1675                 strcpy(a->name, "Phone");
1676                 break;
1677         case EM28XX_AMUX_MIC:
1678                 strcpy(a->name, "Mic");
1679                 break;
1680         case EM28XX_AMUX_CD:
1681                 strcpy(a->name, "CD");
1682                 break;
1683         case EM28XX_AMUX_AUX:
1684                 strcpy(a->name, "Aux");
1685                 break;
1686         case EM28XX_AMUX_PCM_OUT:
1687                 strcpy(a->name, "PCM");
1688                 break;
1689         default:
1690                 return -EINVAL;
1691         }
1692
1693         a->index = dev->ctl_ainput;
1694         a->capability = V4L2_AUDCAP_STEREO;
1695
1696         return 0;
1697 }
1698
1699 static int vidioc_s_audio(struct file *file, void *priv, const struct v4l2_audio *a)
1700 {
1701         struct em28xx *dev = video_drvdata(file);
1702
1703         if (a->index >= MAX_EM28XX_INPUT)
1704                 return -EINVAL;
1705         if (0 == INPUT(a->index)->type)
1706                 return -EINVAL;
1707
1708         dev->ctl_ainput = INPUT(a->index)->amux;
1709         dev->ctl_aoutput = INPUT(a->index)->aout;
1710
1711         if (!dev->ctl_aoutput)
1712                 dev->ctl_aoutput = EM28XX_AOUT_MASTER;
1713
1714         return 0;
1715 }
1716
1717 static int vidioc_g_tuner(struct file *file, void *priv,
1718                           struct v4l2_tuner *t)
1719 {
1720         struct em28xx *dev = video_drvdata(file);
1721
1722         if (0 != t->index)
1723                 return -EINVAL;
1724
1725         strcpy(t->name, "Tuner");
1726
1727         v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, g_tuner, t);
1728         return 0;
1729 }
1730
1731 static int vidioc_s_tuner(struct file *file, void *priv,
1732                           const struct v4l2_tuner *t)
1733 {
1734         struct em28xx *dev = video_drvdata(file);
1735
1736         if (0 != t->index)
1737                 return -EINVAL;
1738
1739         v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, s_tuner, t);
1740         return 0;
1741 }
1742
1743 static int vidioc_g_frequency(struct file *file, void *priv,
1744                               struct v4l2_frequency *f)
1745 {
1746         struct em28xx         *dev = video_drvdata(file);
1747         struct em28xx_v4l2    *v4l2 = dev->v4l2;
1748
1749         if (0 != f->tuner)
1750                 return -EINVAL;
1751
1752         f->frequency = v4l2->frequency;
1753         return 0;
1754 }
1755
1756 static int vidioc_s_frequency(struct file *file, void *priv,
1757                               const struct v4l2_frequency *f)
1758 {
1759         struct v4l2_frequency  new_freq = *f;
1760         struct em28xx             *dev  = video_drvdata(file);
1761         struct em28xx_v4l2        *v4l2 = dev->v4l2;
1762
1763         if (0 != f->tuner)
1764                 return -EINVAL;
1765
1766         v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, s_frequency, f);
1767         v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, g_frequency, &new_freq);
1768         v4l2->frequency = new_freq.frequency;
1769
1770         return 0;
1771 }
1772
1773 #ifdef CONFIG_VIDEO_ADV_DEBUG
1774 static int vidioc_g_chip_info(struct file *file, void *priv,
1775                               struct v4l2_dbg_chip_info *chip)
1776 {
1777         struct em28xx *dev = video_drvdata(file);
1778
1779         if (chip->match.addr > 1)
1780                 return -EINVAL;
1781         if (chip->match.addr == 1)
1782                 strlcpy(chip->name, "ac97", sizeof(chip->name));
1783         else
1784                 strlcpy(chip->name,
1785                         dev->v4l2->v4l2_dev.name, sizeof(chip->name));
1786         return 0;
1787 }
1788
1789 static int em28xx_reg_len(int reg)
1790 {
1791         switch (reg) {
1792         case EM28XX_R40_AC97LSB:
1793         case EM28XX_R30_HSCALELOW:
1794         case EM28XX_R32_VSCALELOW:
1795                 return 2;
1796         default:
1797                 return 1;
1798         }
1799 }
1800
1801 static int vidioc_g_register(struct file *file, void *priv,
1802                              struct v4l2_dbg_register *reg)
1803 {
1804         struct em28xx *dev = video_drvdata(file);
1805         int ret;
1806
1807         if (reg->match.addr > 1)
1808                 return -EINVAL;
1809         if (reg->match.addr) {
1810                 ret = em28xx_read_ac97(dev, reg->reg);
1811                 if (ret < 0)
1812                         return ret;
1813
1814                 reg->val = ret;
1815                 reg->size = 1;
1816                 return 0;
1817         }
1818
1819         /* Match host */
1820         reg->size = em28xx_reg_len(reg->reg);
1821         if (reg->size == 1) {
1822                 ret = em28xx_read_reg(dev, reg->reg);
1823
1824                 if (ret < 0)
1825                         return ret;
1826
1827                 reg->val = ret;
1828         } else {
1829                 __le16 val = 0;
1830
1831                 ret = dev->em28xx_read_reg_req_len(dev, USB_REQ_GET_STATUS,
1832                                                    reg->reg, (char *)&val, 2);
1833                 if (ret < 0)
1834                         return ret;
1835
1836                 reg->val = le16_to_cpu(val);
1837         }
1838
1839         return 0;
1840 }
1841
1842 static int vidioc_s_register(struct file *file, void *priv,
1843                              const struct v4l2_dbg_register *reg)
1844 {
1845         struct em28xx *dev = video_drvdata(file);
1846         __le16 buf;
1847
1848         if (reg->match.addr > 1)
1849                 return -EINVAL;
1850         if (reg->match.addr)
1851                 return em28xx_write_ac97(dev, reg->reg, reg->val);
1852
1853         /* Match host */
1854         buf = cpu_to_le16(reg->val);
1855
1856         return em28xx_write_regs(dev, reg->reg, (char *)&buf,
1857                                em28xx_reg_len(reg->reg));
1858 }
1859 #endif
1860
1861 static int vidioc_querycap(struct file *file, void  *priv,
1862                            struct v4l2_capability *cap)
1863 {
1864         struct video_device   *vdev = video_devdata(file);
1865         struct em28xx         *dev  = video_drvdata(file);
1866         struct em28xx_v4l2    *v4l2 = dev->v4l2;
1867         struct usb_device *udev = interface_to_usbdev(dev->intf);
1868
1869         strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1870         strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1871         usb_make_path(udev, cap->bus_info, sizeof(cap->bus_info));
1872
1873         if (vdev->vfl_type == VFL_TYPE_GRABBER)
1874                 cap->device_caps = V4L2_CAP_READWRITE |
1875                         V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
1876         else if (vdev->vfl_type == VFL_TYPE_RADIO)
1877                 cap->device_caps = V4L2_CAP_RADIO;
1878         else
1879                 cap->device_caps = V4L2_CAP_READWRITE | V4L2_CAP_VBI_CAPTURE;
1880
1881         if (dev->int_audio_type != EM28XX_INT_AUDIO_NONE)
1882                 cap->device_caps |= V4L2_CAP_AUDIO;
1883
1884         if (dev->tuner_type != TUNER_ABSENT)
1885                 cap->device_caps |= V4L2_CAP_TUNER;
1886
1887         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS |
1888                 V4L2_CAP_READWRITE | V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
1889         if (video_is_registered(&v4l2->vbi_dev))
1890                 cap->capabilities |= V4L2_CAP_VBI_CAPTURE;
1891         if (video_is_registered(&v4l2->radio_dev))
1892                 cap->capabilities |= V4L2_CAP_RADIO;
1893         return 0;
1894 }
1895
1896 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1897                                    struct v4l2_fmtdesc *f)
1898 {
1899         if (unlikely(f->index >= ARRAY_SIZE(format)))
1900                 return -EINVAL;
1901
1902         strlcpy(f->description, format[f->index].name, sizeof(f->description));
1903         f->pixelformat = format[f->index].fourcc;
1904
1905         return 0;
1906 }
1907
1908 static int vidioc_enum_framesizes(struct file *file, void *priv,
1909                                   struct v4l2_frmsizeenum *fsize)
1910 {
1911         struct em28xx         *dev = video_drvdata(file);
1912         struct em28xx_fmt     *fmt;
1913         unsigned int          maxw = norm_maxw(dev);
1914         unsigned int          maxh = norm_maxh(dev);
1915
1916         fmt = format_by_fourcc(fsize->pixel_format);
1917         if (!fmt) {
1918                 em28xx_videodbg("Fourcc format (%08x) invalid.\n",
1919                                 fsize->pixel_format);
1920                 return -EINVAL;
1921         }
1922
1923         if (dev->board.is_em2800) {
1924                 if (fsize->index > 1)
1925                         return -EINVAL;
1926                 fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1927                 fsize->discrete.width = maxw / (1 + fsize->index);
1928                 fsize->discrete.height = maxh / (1 + fsize->index);
1929                 return 0;
1930         }
1931
1932         if (fsize->index != 0)
1933                 return -EINVAL;
1934
1935         /* Report a continuous range */
1936         fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
1937         scale_to_size(dev, EM28XX_HVSCALE_MAX, EM28XX_HVSCALE_MAX,
1938                       &fsize->stepwise.min_width, &fsize->stepwise.min_height);
1939         if (fsize->stepwise.min_width < 48)
1940                 fsize->stepwise.min_width = 48;
1941         if (fsize->stepwise.min_height < 38)
1942                 fsize->stepwise.min_height = 38;
1943         fsize->stepwise.max_width = maxw;
1944         fsize->stepwise.max_height = maxh;
1945         fsize->stepwise.step_width = 1;
1946         fsize->stepwise.step_height = 1;
1947         return 0;
1948 }
1949
1950 /* RAW VBI ioctls */
1951
1952 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
1953                                 struct v4l2_format *format)
1954 {
1955         struct em28xx         *dev  = video_drvdata(file);
1956         struct em28xx_v4l2    *v4l2 = dev->v4l2;
1957
1958         format->fmt.vbi.samples_per_line = v4l2->vbi_width;
1959         format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1960         format->fmt.vbi.offset = 0;
1961         format->fmt.vbi.flags = 0;
1962         format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
1963         format->fmt.vbi.count[0] = v4l2->vbi_height;
1964         format->fmt.vbi.count[1] = v4l2->vbi_height;
1965         memset(format->fmt.vbi.reserved, 0, sizeof(format->fmt.vbi.reserved));
1966
1967         /* Varies by video standard (NTSC, PAL, etc.) */
1968         if (v4l2->norm & V4L2_STD_525_60) {
1969                 /* NTSC */
1970                 format->fmt.vbi.start[0] = 10;
1971                 format->fmt.vbi.start[1] = 273;
1972         } else if (v4l2->norm & V4L2_STD_625_50) {
1973                 /* PAL */
1974                 format->fmt.vbi.start[0] = 6;
1975                 format->fmt.vbi.start[1] = 318;
1976         }
1977
1978         return 0;
1979 }
1980
1981 /* ----------------------------------------------------------- */
1982 /* RADIO ESPECIFIC IOCTLS                                      */
1983 /* ----------------------------------------------------------- */
1984
1985 static int radio_g_tuner(struct file *file, void *priv,
1986                          struct v4l2_tuner *t)
1987 {
1988         struct em28xx *dev = video_drvdata(file);
1989
1990         if (unlikely(t->index > 0))
1991                 return -EINVAL;
1992
1993         strcpy(t->name, "Radio");
1994
1995         v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, g_tuner, t);
1996
1997         return 0;
1998 }
1999
2000 static int radio_s_tuner(struct file *file, void *priv,
2001                          const struct v4l2_tuner *t)
2002 {
2003         struct em28xx *dev = video_drvdata(file);
2004
2005         if (0 != t->index)
2006                 return -EINVAL;
2007
2008         v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, s_tuner, t);
2009
2010         return 0;
2011 }
2012
2013 /*
2014  * em28xx_free_v4l2() - Free struct em28xx_v4l2
2015  *
2016  * @ref: struct kref for struct em28xx_v4l2
2017  *
2018  * Called when all users of struct em28xx_v4l2 are gone
2019  */
2020 static void em28xx_free_v4l2(struct kref *ref)
2021 {
2022         struct em28xx_v4l2 *v4l2 = container_of(ref, struct em28xx_v4l2, ref);
2023
2024         v4l2->dev->v4l2 = NULL;
2025         kfree(v4l2);
2026 }
2027
2028 /*
2029  * em28xx_v4l2_open()
2030  * inits the device and starts isoc transfer
2031  */
2032 static int em28xx_v4l2_open(struct file *filp)
2033 {
2034         struct video_device *vdev = video_devdata(filp);
2035         struct em28xx *dev = video_drvdata(filp);
2036         struct em28xx_v4l2 *v4l2 = dev->v4l2;
2037         enum v4l2_buf_type fh_type = 0;
2038         int ret;
2039
2040         switch (vdev->vfl_type) {
2041         case VFL_TYPE_GRABBER:
2042                 fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2043                 break;
2044         case VFL_TYPE_VBI:
2045                 fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
2046                 break;
2047         case VFL_TYPE_RADIO:
2048                 break;
2049         default:
2050                 return -EINVAL;
2051         }
2052
2053         em28xx_videodbg("open dev=%s type=%s users=%d\n",
2054                         video_device_node_name(vdev), v4l2_type_names[fh_type],
2055                         v4l2->users);
2056
2057         if (mutex_lock_interruptible(&dev->lock))
2058                 return -ERESTARTSYS;
2059
2060         ret = v4l2_fh_open(filp);
2061         if (ret) {
2062                 dev_err(&dev->intf->dev,
2063                         "%s: v4l2_fh_open() returned error %d\n",
2064                        __func__, ret);
2065                 mutex_unlock(&dev->lock);
2066                 return ret;
2067         }
2068
2069         if (v4l2->users == 0) {
2070                 em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
2071
2072                 if (vdev->vfl_type != VFL_TYPE_RADIO)
2073                         em28xx_resolution_set(dev);
2074
2075                 /*
2076                  * Needed, since GPIO might have disabled power
2077                  * of some i2c devices
2078                  */
2079                 em28xx_wake_i2c(dev);
2080         }
2081
2082         if (vdev->vfl_type == VFL_TYPE_RADIO) {
2083                 em28xx_videodbg("video_open: setting radio device\n");
2084                 v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, s_radio);
2085         }
2086
2087         kref_get(&dev->ref);
2088         kref_get(&v4l2->ref);
2089         v4l2->users++;
2090
2091         mutex_unlock(&dev->lock);
2092
2093         return 0;
2094 }
2095
2096 /*
2097  * em28xx_v4l2_fini()
2098  * unregisters the v4l2,i2c and usb devices
2099  * called when the device gets disconected or at module unload
2100 */
2101 static int em28xx_v4l2_fini(struct em28xx *dev)
2102 {
2103         struct em28xx_v4l2 *v4l2 = dev->v4l2;
2104
2105         if (dev->is_audio_only) {
2106                 /* Shouldn't initialize IR for this interface */
2107                 return 0;
2108         }
2109
2110         if (!dev->has_video) {
2111                 /* This device does not support the v4l2 extension */
2112                 return 0;
2113         }
2114
2115         if (v4l2 == NULL)
2116                 return 0;
2117
2118         dev_info(&dev->intf->dev, "Closing video extension\n");
2119
2120         mutex_lock(&dev->lock);
2121
2122         v4l2_device_disconnect(&v4l2->v4l2_dev);
2123
2124         em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
2125
2126         em28xx_v4l2_media_release(dev);
2127
2128         if (video_is_registered(&v4l2->radio_dev)) {
2129                 dev_info(&dev->intf->dev, "V4L2 device %s deregistered\n",
2130                         video_device_node_name(&v4l2->radio_dev));
2131                 video_unregister_device(&v4l2->radio_dev);
2132         }
2133         if (video_is_registered(&v4l2->vbi_dev)) {
2134                 dev_info(&dev->intf->dev, "V4L2 device %s deregistered\n",
2135                         video_device_node_name(&v4l2->vbi_dev));
2136                 video_unregister_device(&v4l2->vbi_dev);
2137         }
2138         if (video_is_registered(&v4l2->vdev)) {
2139                 dev_info(&dev->intf->dev, "V4L2 device %s deregistered\n",
2140                         video_device_node_name(&v4l2->vdev));
2141                 video_unregister_device(&v4l2->vdev);
2142         }
2143
2144         v4l2_ctrl_handler_free(&v4l2->ctrl_handler);
2145         v4l2_device_unregister(&v4l2->v4l2_dev);
2146
2147         kref_put(&v4l2->ref, em28xx_free_v4l2);
2148
2149         mutex_unlock(&dev->lock);
2150
2151         kref_put(&dev->ref, em28xx_free_device);
2152
2153         return 0;
2154 }
2155
2156 static int em28xx_v4l2_suspend(struct em28xx *dev)
2157 {
2158         if (dev->is_audio_only)
2159                 return 0;
2160
2161         if (!dev->has_video)
2162                 return 0;
2163
2164         dev_info(&dev->intf->dev, "Suspending video extension\n");
2165         em28xx_stop_urbs(dev);
2166         return 0;
2167 }
2168
2169 static int em28xx_v4l2_resume(struct em28xx *dev)
2170 {
2171         if (dev->is_audio_only)
2172                 return 0;
2173
2174         if (!dev->has_video)
2175                 return 0;
2176
2177         dev_info(&dev->intf->dev, "Resuming video extension\n");
2178         /* what do we do here */
2179         return 0;
2180 }
2181
2182 /*
2183  * em28xx_v4l2_close()
2184  * stops streaming and deallocates all resources allocated by the v4l2
2185  * calls and ioctls
2186  */
2187 static int em28xx_v4l2_close(struct file *filp)
2188 {
2189         struct em28xx         *dev  = video_drvdata(filp);
2190         struct em28xx_v4l2    *v4l2 = dev->v4l2;
2191         struct usb_device *udev = interface_to_usbdev(dev->intf);
2192         int              errCode;
2193
2194         em28xx_videodbg("users=%d\n", v4l2->users);
2195
2196         vb2_fop_release(filp);
2197         mutex_lock(&dev->lock);
2198
2199         if (v4l2->users == 1) {
2200                 /* No sense to try to write to the device */
2201                 if (dev->disconnected)
2202                         goto exit;
2203
2204                 /* Save some power by putting tuner to sleep */
2205                 v4l2_device_call_all(&v4l2->v4l2_dev, 0, core, s_power, 0);
2206
2207                 /* do this before setting alternate! */
2208                 em28xx_set_mode(dev, EM28XX_SUSPEND);
2209
2210                 /* set alternate 0 */
2211                 dev->alt = 0;
2212                 em28xx_videodbg("setting alternate 0\n");
2213                 errCode = usb_set_interface(udev, 0, 0);
2214                 if (errCode < 0) {
2215                         dev_err(&dev->intf->dev,
2216                                 "cannot change alternate number to 0 (error=%i)\n",
2217                                 errCode);
2218                 }
2219         }
2220
2221 exit:
2222         v4l2->users--;
2223         kref_put(&v4l2->ref, em28xx_free_v4l2);
2224         mutex_unlock(&dev->lock);
2225         kref_put(&dev->ref, em28xx_free_device);
2226
2227         return 0;
2228 }
2229
2230 static const struct v4l2_file_operations em28xx_v4l_fops = {
2231         .owner         = THIS_MODULE,
2232         .open          = em28xx_v4l2_open,
2233         .release       = em28xx_v4l2_close,
2234         .read          = vb2_fop_read,
2235         .poll          = vb2_fop_poll,
2236         .mmap          = vb2_fop_mmap,
2237         .unlocked_ioctl = video_ioctl2,
2238 };
2239
2240 static const struct v4l2_ioctl_ops video_ioctl_ops = {
2241         .vidioc_querycap            = vidioc_querycap,
2242         .vidioc_enum_fmt_vid_cap    = vidioc_enum_fmt_vid_cap,
2243         .vidioc_g_fmt_vid_cap       = vidioc_g_fmt_vid_cap,
2244         .vidioc_try_fmt_vid_cap     = vidioc_try_fmt_vid_cap,
2245         .vidioc_s_fmt_vid_cap       = vidioc_s_fmt_vid_cap,
2246         .vidioc_g_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
2247         .vidioc_try_fmt_vbi_cap     = vidioc_g_fmt_vbi_cap,
2248         .vidioc_s_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
2249         .vidioc_enum_framesizes     = vidioc_enum_framesizes,
2250         .vidioc_g_audio             = vidioc_g_audio,
2251         .vidioc_s_audio             = vidioc_s_audio,
2252
2253         .vidioc_reqbufs             = vb2_ioctl_reqbufs,
2254         .vidioc_create_bufs         = vb2_ioctl_create_bufs,
2255         .vidioc_prepare_buf         = vb2_ioctl_prepare_buf,
2256         .vidioc_querybuf            = vb2_ioctl_querybuf,
2257         .vidioc_qbuf                = vb2_ioctl_qbuf,
2258         .vidioc_dqbuf               = vb2_ioctl_dqbuf,
2259
2260         .vidioc_g_std               = vidioc_g_std,
2261         .vidioc_querystd            = vidioc_querystd,
2262         .vidioc_s_std               = vidioc_s_std,
2263         .vidioc_g_parm              = vidioc_g_parm,
2264         .vidioc_s_parm              = vidioc_s_parm,
2265         .vidioc_enum_input          = vidioc_enum_input,
2266         .vidioc_g_input             = vidioc_g_input,
2267         .vidioc_s_input             = vidioc_s_input,
2268         .vidioc_streamon            = vb2_ioctl_streamon,
2269         .vidioc_streamoff           = vb2_ioctl_streamoff,
2270         .vidioc_g_tuner             = vidioc_g_tuner,
2271         .vidioc_s_tuner             = vidioc_s_tuner,
2272         .vidioc_g_frequency         = vidioc_g_frequency,
2273         .vidioc_s_frequency         = vidioc_s_frequency,
2274         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2275         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2276 #ifdef CONFIG_VIDEO_ADV_DEBUG
2277         .vidioc_g_chip_info         = vidioc_g_chip_info,
2278         .vidioc_g_register          = vidioc_g_register,
2279         .vidioc_s_register          = vidioc_s_register,
2280 #endif
2281 };
2282
2283 static const struct video_device em28xx_video_template = {
2284         .fops           = &em28xx_v4l_fops,
2285         .ioctl_ops      = &video_ioctl_ops,
2286         .release        = video_device_release_empty,
2287         .tvnorms        = V4L2_STD_ALL,
2288 };
2289
2290 static const struct v4l2_file_operations radio_fops = {
2291         .owner         = THIS_MODULE,
2292         .open          = em28xx_v4l2_open,
2293         .release       = em28xx_v4l2_close,
2294         .unlocked_ioctl = video_ioctl2,
2295 };
2296
2297 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2298         .vidioc_querycap      = vidioc_querycap,
2299         .vidioc_g_tuner       = radio_g_tuner,
2300         .vidioc_s_tuner       = radio_s_tuner,
2301         .vidioc_g_frequency   = vidioc_g_frequency,
2302         .vidioc_s_frequency   = vidioc_s_frequency,
2303         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2304         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2305 #ifdef CONFIG_VIDEO_ADV_DEBUG
2306         .vidioc_g_chip_info   = vidioc_g_chip_info,
2307         .vidioc_g_register    = vidioc_g_register,
2308         .vidioc_s_register    = vidioc_s_register,
2309 #endif
2310 };
2311
2312 static struct video_device em28xx_radio_template = {
2313         .fops           = &radio_fops,
2314         .ioctl_ops      = &radio_ioctl_ops,
2315         .release        = video_device_release_empty,
2316 };
2317
2318 /* I2C possible address to saa7115, tvp5150, msp3400, tvaudio */
2319 static unsigned short saa711x_addrs[] = {
2320         0x4a >> 1, 0x48 >> 1,   /* SAA7111, SAA7111A and SAA7113 */
2321         0x42 >> 1, 0x40 >> 1,   /* SAA7114, SAA7115 and SAA7118 */
2322         I2C_CLIENT_END };
2323
2324 static unsigned short tvp5150_addrs[] = {
2325         0xb8 >> 1,
2326         0xba >> 1,
2327         I2C_CLIENT_END
2328 };
2329
2330 static unsigned short msp3400_addrs[] = {
2331         0x80 >> 1,
2332         0x88 >> 1,
2333         I2C_CLIENT_END
2334 };
2335
2336 /******************************** usb interface ******************************/
2337
2338 static void em28xx_vdev_init(struct em28xx *dev,
2339                              struct video_device *vfd,
2340                              const struct video_device *template,
2341                              const char *type_name)
2342 {
2343         *vfd            = *template;
2344         vfd->v4l2_dev   = &dev->v4l2->v4l2_dev;
2345         vfd->lock       = &dev->lock;
2346         if (dev->board.is_webcam)
2347                 vfd->tvnorms = 0;
2348
2349         snprintf(vfd->name, sizeof(vfd->name), "%s %s",
2350                  dev_name(&dev->intf->dev), type_name);
2351
2352         video_set_drvdata(vfd, dev);
2353 }
2354
2355 static void em28xx_tuner_setup(struct em28xx *dev, unsigned short tuner_addr)
2356 {
2357         struct em28xx_v4l2      *v4l2 = dev->v4l2;
2358         struct v4l2_device      *v4l2_dev = &v4l2->v4l2_dev;
2359         struct tuner_setup      tun_setup;
2360         struct v4l2_frequency   f;
2361
2362         memset(&tun_setup, 0, sizeof(tun_setup));
2363
2364         tun_setup.mode_mask = T_ANALOG_TV | T_RADIO;
2365         tun_setup.tuner_callback = em28xx_tuner_callback;
2366
2367         if (dev->board.radio.type) {
2368                 tun_setup.type = dev->board.radio.type;
2369                 tun_setup.addr = dev->board.radio_addr;
2370
2371                 v4l2_device_call_all(v4l2_dev,
2372                                      0, tuner, s_type_addr, &tun_setup);
2373         }
2374
2375         if ((dev->tuner_type != TUNER_ABSENT) && (dev->tuner_type)) {
2376                 tun_setup.type   = dev->tuner_type;
2377                 tun_setup.addr   = tuner_addr;
2378
2379                 v4l2_device_call_all(v4l2_dev,
2380                                      0, tuner, s_type_addr, &tun_setup);
2381         }
2382
2383         if (dev->board.tda9887_conf) {
2384                 struct v4l2_priv_tun_config tda9887_cfg;
2385
2386                 tda9887_cfg.tuner = TUNER_TDA9887;
2387                 tda9887_cfg.priv = &dev->board.tda9887_conf;
2388
2389                 v4l2_device_call_all(v4l2_dev,
2390                                      0, tuner, s_config, &tda9887_cfg);
2391         }
2392
2393         if (dev->tuner_type == TUNER_XC2028) {
2394                 struct v4l2_priv_tun_config  xc2028_cfg;
2395                 struct xc2028_ctrl           ctl;
2396
2397                 memset(&xc2028_cfg, 0, sizeof(xc2028_cfg));
2398                 memset(&ctl, 0, sizeof(ctl));
2399
2400                 em28xx_setup_xc3028(dev, &ctl);
2401
2402                 xc2028_cfg.tuner = TUNER_XC2028;
2403                 xc2028_cfg.priv  = &ctl;
2404
2405                 v4l2_device_call_all(v4l2_dev, 0, tuner, s_config, &xc2028_cfg);
2406         }
2407
2408         /* configure tuner */
2409         f.tuner = 0;
2410         f.type = V4L2_TUNER_ANALOG_TV;
2411         f.frequency = 9076;     /* just a magic number */
2412         v4l2->frequency = f.frequency;
2413         v4l2_device_call_all(v4l2_dev, 0, tuner, s_frequency, &f);
2414 }
2415
2416 static int em28xx_v4l2_init(struct em28xx *dev)
2417 {
2418         u8 val;
2419         int ret;
2420         unsigned int maxw;
2421         struct v4l2_ctrl_handler *hdl;
2422         struct em28xx_v4l2 *v4l2;
2423
2424         if (dev->is_audio_only) {
2425                 /* Shouldn't initialize IR for this interface */
2426                 return 0;
2427         }
2428
2429         if (!dev->has_video) {
2430                 /* This device does not support the v4l2 extension */
2431                 return 0;
2432         }
2433
2434         dev_info(&dev->intf->dev, "Registering V4L2 extension\n");
2435
2436         mutex_lock(&dev->lock);
2437
2438         v4l2 = kzalloc(sizeof(struct em28xx_v4l2), GFP_KERNEL);
2439         if (!v4l2) {
2440                 mutex_unlock(&dev->lock);
2441                 return -ENOMEM;
2442         }
2443         kref_init(&v4l2->ref);
2444         v4l2->dev = dev;
2445         dev->v4l2 = v4l2;
2446
2447 #ifdef CONFIG_MEDIA_CONTROLLER
2448         v4l2->v4l2_dev.mdev = dev->media_dev;
2449 #endif
2450         ret = v4l2_device_register(&dev->intf->dev, &v4l2->v4l2_dev);
2451         if (ret < 0) {
2452                 dev_err(&dev->intf->dev,
2453                         "Call to v4l2_device_register() failed!\n");
2454                 goto err;
2455         }
2456
2457         hdl = &v4l2->ctrl_handler;
2458         v4l2_ctrl_handler_init(hdl, 8);
2459         v4l2->v4l2_dev.ctrl_handler = hdl;
2460
2461         if (dev->board.is_webcam)
2462                 v4l2->progressive = true;
2463
2464         /*
2465          * Default format, used for tvp5150 or saa711x output formats
2466          */
2467         v4l2->vinmode = EM28XX_VINMODE_YUV422_CbYCrY;
2468         v4l2->vinctl  = EM28XX_VINCTRL_INTERLACED |
2469                         EM28XX_VINCTRL_CCIR656_ENABLE;
2470
2471         /* request some modules */
2472
2473         if (dev->board.has_msp34xx)
2474                 v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2475                                     &dev->i2c_adap[dev->def_i2c_bus],
2476                                     "msp3400", 0, msp3400_addrs);
2477
2478         if (dev->board.decoder == EM28XX_SAA711X)
2479                 v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2480                                     &dev->i2c_adap[dev->def_i2c_bus],
2481                                     "saa7115_auto", 0, saa711x_addrs);
2482
2483         if (dev->board.decoder == EM28XX_TVP5150)
2484                 v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2485                                     &dev->i2c_adap[dev->def_i2c_bus],
2486                                     "tvp5150", 0, tvp5150_addrs);
2487
2488         if (dev->board.adecoder == EM28XX_TVAUDIO)
2489                 v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2490                                     &dev->i2c_adap[dev->def_i2c_bus],
2491                                     "tvaudio", dev->board.tvaudio_addr, NULL);
2492
2493         /* Initialize tuner and camera */
2494
2495         if (dev->board.tuner_type != TUNER_ABSENT) {
2496                 unsigned short tuner_addr = dev->board.tuner_addr;
2497                 int has_demod = (dev->board.tda9887_conf & TDA9887_PRESENT);
2498
2499                 if (dev->board.radio.type)
2500                         v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2501                                             &dev->i2c_adap[dev->def_i2c_bus],
2502                                             "tuner", dev->board.radio_addr,
2503                                             NULL);
2504
2505                 if (has_demod)
2506                         v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2507                                             &dev->i2c_adap[dev->def_i2c_bus],
2508                                             "tuner", 0,
2509                                             v4l2_i2c_tuner_addrs(ADDRS_DEMOD));
2510                 if (tuner_addr == 0) {
2511                         enum v4l2_i2c_tuner_type type =
2512                                 has_demod ? ADDRS_TV_WITH_DEMOD : ADDRS_TV;
2513                         struct v4l2_subdev *sd;
2514
2515                         sd = v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2516                                                  &dev->i2c_adap[dev->def_i2c_bus],
2517                                                  "tuner", 0,
2518                                                  v4l2_i2c_tuner_addrs(type));
2519
2520                         if (sd)
2521                                 tuner_addr = v4l2_i2c_subdev_addr(sd);
2522                 } else {
2523                         v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2524                                             &dev->i2c_adap[dev->def_i2c_bus],
2525                                             "tuner", tuner_addr, NULL);
2526                 }
2527
2528                 em28xx_tuner_setup(dev, tuner_addr);
2529         }
2530
2531         if (dev->em28xx_sensor != EM28XX_NOSENSOR)
2532                 em28xx_init_camera(dev);
2533
2534         /* Configure audio */
2535         ret = em28xx_audio_setup(dev);
2536         if (ret < 0) {
2537                 dev_err(&dev->intf->dev,
2538                         "%s: Error while setting audio - error [%d]!\n",
2539                         __func__, ret);
2540                 goto unregister_dev;
2541         }
2542         if (dev->audio_mode.ac97 != EM28XX_NO_AC97) {
2543                 v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2544                                   V4L2_CID_AUDIO_MUTE, 0, 1, 1, 1);
2545                 v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2546                                   V4L2_CID_AUDIO_VOLUME, 0, 0x1f, 1, 0x1f);
2547         } else {
2548                 /* install the em28xx notify callback */
2549                 v4l2_ctrl_notify(v4l2_ctrl_find(hdl, V4L2_CID_AUDIO_MUTE),
2550                                  em28xx_ctrl_notify, dev);
2551                 v4l2_ctrl_notify(v4l2_ctrl_find(hdl, V4L2_CID_AUDIO_VOLUME),
2552                                  em28xx_ctrl_notify, dev);
2553         }
2554
2555         /* wake i2c devices */
2556         em28xx_wake_i2c(dev);
2557
2558         /* init video dma queues */
2559         INIT_LIST_HEAD(&dev->vidq.active);
2560         INIT_LIST_HEAD(&dev->vbiq.active);
2561
2562         if (dev->board.has_msp34xx) {
2563                 /* Send a reset to other chips via gpio */
2564                 ret = em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xf7);
2565                 if (ret < 0) {
2566                         dev_err(&dev->intf->dev,
2567                                 "%s: em28xx_write_reg - msp34xx(1) failed! error [%d]\n",
2568                                 __func__, ret);
2569                         goto unregister_dev;
2570                 }
2571                 msleep(3);
2572
2573                 ret = em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xff);
2574                 if (ret < 0) {
2575                         dev_err(&dev->intf->dev,
2576                                 "%s: em28xx_write_reg - msp34xx(2) failed! error [%d]\n",
2577                                 __func__, ret);
2578                         goto unregister_dev;
2579                 }
2580                 msleep(3);
2581         }
2582
2583         /* set default norm */
2584         v4l2->norm = V4L2_STD_PAL;
2585         v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_std, v4l2->norm);
2586         v4l2->interlaced_fieldmode = EM28XX_INTERLACED_DEFAULT;
2587
2588         /* Analog specific initialization */
2589         v4l2->format = &format[0];
2590
2591         maxw = norm_maxw(dev);
2592         /* MaxPacketSize for em2800 is too small to capture at full resolution
2593          * use half of maxw as the scaler can only scale to 50% */
2594         if (dev->board.is_em2800)
2595                 maxw /= 2;
2596
2597         em28xx_set_video_format(dev, format[0].fourcc,
2598                                 maxw, norm_maxh(dev));
2599
2600         video_mux(dev, 0);
2601
2602         /* Audio defaults */
2603         dev->mute = 1;
2604         dev->volume = 0x1f;
2605
2606 /*      em28xx_write_reg(dev, EM28XX_R0E_AUDIOSRC, 0xc0); audio register */
2607         val = (u8)em28xx_read_reg(dev, EM28XX_R0F_XCLK);
2608         em28xx_write_reg(dev, EM28XX_R0F_XCLK,
2609                          (EM28XX_XCLK_AUDIO_UNMUTE | val));
2610
2611         em28xx_set_outfmt(dev);
2612
2613         /* Add image controls */
2614         /* NOTE: at this point, the subdevices are already registered, so bridge
2615          * controls are only added/enabled when no subdevice provides them */
2616         if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_CONTRAST))
2617                 v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2618                                   V4L2_CID_CONTRAST,
2619                                   0, 0x1f, 1, CONTRAST_DEFAULT);
2620         if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_BRIGHTNESS))
2621                 v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2622                                   V4L2_CID_BRIGHTNESS,
2623                                   -0x80, 0x7f, 1, BRIGHTNESS_DEFAULT);
2624         if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_SATURATION))
2625                 v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2626                                   V4L2_CID_SATURATION,
2627                                   0, 0x1f, 1, SATURATION_DEFAULT);
2628         if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_BLUE_BALANCE))
2629                 v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2630                                   V4L2_CID_BLUE_BALANCE,
2631                                   -0x30, 0x30, 1, BLUE_BALANCE_DEFAULT);
2632         if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_RED_BALANCE))
2633                 v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2634                                   V4L2_CID_RED_BALANCE,
2635                                   -0x30, 0x30, 1, RED_BALANCE_DEFAULT);
2636         if (NULL == v4l2_ctrl_find(hdl, V4L2_CID_SHARPNESS))
2637                 v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2638                                   V4L2_CID_SHARPNESS,
2639                                   0, 0x0f, 1, SHARPNESS_DEFAULT);
2640
2641         /* Reset image controls */
2642         em28xx_colorlevels_set_default(dev);
2643         v4l2_ctrl_handler_setup(hdl);
2644         ret = hdl->error;
2645         if (ret)
2646                 goto unregister_dev;
2647
2648         /* allocate and fill video video_device struct */
2649         em28xx_vdev_init(dev, &v4l2->vdev, &em28xx_video_template, "video");
2650         mutex_init(&v4l2->vb_queue_lock);
2651         mutex_init(&v4l2->vb_vbi_queue_lock);
2652         v4l2->vdev.queue = &v4l2->vb_vidq;
2653         v4l2->vdev.queue->lock = &v4l2->vb_queue_lock;
2654
2655         /* disable inapplicable ioctls */
2656         if (dev->board.is_webcam) {
2657                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_QUERYSTD);
2658                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_STD);
2659                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_STD);
2660         } else {
2661                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_PARM);
2662         }
2663         if (dev->tuner_type == TUNER_ABSENT) {
2664                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_TUNER);
2665                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_TUNER);
2666                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_FREQUENCY);
2667                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_FREQUENCY);
2668         }
2669         if (dev->int_audio_type == EM28XX_INT_AUDIO_NONE) {
2670                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_AUDIO);
2671                 v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_AUDIO);
2672         }
2673
2674         /* register v4l2 video video_device */
2675         ret = video_register_device(&v4l2->vdev, VFL_TYPE_GRABBER,
2676                                     video_nr[dev->devno]);
2677         if (ret) {
2678                 dev_err(&dev->intf->dev,
2679                         "unable to register video device (error=%i).\n", ret);
2680                 goto unregister_dev;
2681         }
2682
2683         /* Allocate and fill vbi video_device struct */
2684         if (em28xx_vbi_supported(dev) == 1) {
2685                 em28xx_vdev_init(dev, &v4l2->vbi_dev, &em28xx_video_template,
2686                                 "vbi");
2687
2688                 v4l2->vbi_dev.queue = &v4l2->vb_vbiq;
2689                 v4l2->vbi_dev.queue->lock = &v4l2->vb_vbi_queue_lock;
2690
2691                 /* disable inapplicable ioctls */
2692                 v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_PARM);
2693                 if (dev->tuner_type == TUNER_ABSENT) {
2694                         v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_TUNER);
2695                         v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_TUNER);
2696                         v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_FREQUENCY);
2697                         v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_FREQUENCY);
2698                 }
2699                 if (dev->int_audio_type == EM28XX_INT_AUDIO_NONE) {
2700                         v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_AUDIO);
2701                         v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_AUDIO);
2702                 }
2703
2704                 /* register v4l2 vbi video_device */
2705                 ret = video_register_device(&v4l2->vbi_dev, VFL_TYPE_VBI,
2706                                             vbi_nr[dev->devno]);
2707                 if (ret < 0) {
2708                         dev_err(&dev->intf->dev,
2709                                 "unable to register vbi device\n");
2710                         goto unregister_dev;
2711                 }
2712         }
2713
2714         if (em28xx_boards[dev->model].radio.type == EM28XX_RADIO) {
2715                 em28xx_vdev_init(dev, &v4l2->radio_dev, &em28xx_radio_template,
2716                                    "radio");
2717                 ret = video_register_device(&v4l2->radio_dev, VFL_TYPE_RADIO,
2718                                             radio_nr[dev->devno]);
2719                 if (ret < 0) {
2720                         dev_err(&dev->intf->dev,
2721                                 "can't register radio device\n");
2722                         goto unregister_dev;
2723                 }
2724                 dev_info(&dev->intf->dev,
2725                          "Registered radio device as %s\n",
2726                          video_device_node_name(&v4l2->radio_dev));
2727         }
2728
2729         /* Init entities at the Media Controller */
2730         em28xx_v4l2_create_entities(dev);
2731
2732 #ifdef CONFIG_MEDIA_CONTROLLER
2733         ret = v4l2_mc_create_media_graph(dev->media_dev);
2734         if (ret) {
2735                 dev_err(&dev->intf->dev,
2736                         "failed to create media graph\n");
2737                 em28xx_v4l2_media_release(dev);
2738                 goto unregister_dev;
2739         }
2740 #endif
2741
2742         dev_info(&dev->intf->dev,
2743                  "V4L2 video device registered as %s\n",
2744                  video_device_node_name(&v4l2->vdev));
2745
2746         if (video_is_registered(&v4l2->vbi_dev))
2747                 dev_info(&dev->intf->dev,
2748                          "V4L2 VBI device registered as %s\n",
2749                          video_device_node_name(&v4l2->vbi_dev));
2750
2751         /* Save some power by putting tuner to sleep */
2752         v4l2_device_call_all(&v4l2->v4l2_dev, 0, core, s_power, 0);
2753
2754         /* initialize videobuf2 stuff */
2755         em28xx_vb2_setup(dev);
2756
2757         dev_info(&dev->intf->dev,
2758                  "V4L2 extension successfully initialized\n");
2759
2760         kref_get(&dev->ref);
2761
2762         mutex_unlock(&dev->lock);
2763         return 0;
2764
2765 unregister_dev:
2766         if (video_is_registered(&v4l2->radio_dev)) {
2767                 dev_info(&dev->intf->dev,
2768                          "V4L2 device %s deregistered\n",
2769                          video_device_node_name(&v4l2->radio_dev));
2770                 video_unregister_device(&v4l2->radio_dev);
2771         }
2772         if (video_is_registered(&v4l2->vbi_dev)) {
2773                 dev_info(&dev->intf->dev,
2774                          "V4L2 device %s deregistered\n",
2775                          video_device_node_name(&v4l2->vbi_dev));
2776                 video_unregister_device(&v4l2->vbi_dev);
2777         }
2778         if (video_is_registered(&v4l2->vdev)) {
2779                 dev_info(&dev->intf->dev,
2780                          "V4L2 device %s deregistered\n",
2781                          video_device_node_name(&v4l2->vdev));
2782                 video_unregister_device(&v4l2->vdev);
2783         }
2784
2785         v4l2_ctrl_handler_free(&v4l2->ctrl_handler);
2786         v4l2_device_unregister(&v4l2->v4l2_dev);
2787 err:
2788         dev->v4l2 = NULL;
2789         kref_put(&v4l2->ref, em28xx_free_v4l2);
2790         mutex_unlock(&dev->lock);
2791         return ret;
2792 }
2793
2794 static struct em28xx_ops v4l2_ops = {
2795         .id   = EM28XX_V4L2,
2796         .name = "Em28xx v4l2 Extension",
2797         .init = em28xx_v4l2_init,
2798         .fini = em28xx_v4l2_fini,
2799         .suspend = em28xx_v4l2_suspend,
2800         .resume = em28xx_v4l2_resume,
2801 };
2802
2803 static int __init em28xx_video_register(void)
2804 {
2805         return em28xx_register_extension(&v4l2_ops);
2806 }
2807
2808 static void __exit em28xx_video_unregister(void)
2809 {
2810         em28xx_unregister_extension(&v4l2_ops);
2811 }
2812
2813 module_init(em28xx_video_register);
2814 module_exit(em28xx_video_unregister);