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