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