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