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