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