Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0+
0002 //
0003 // em28xx-video.c - driver for Empia EM2800/EM2820/2840 USB
0004 //          video capture devices
0005 //
0006 // Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
0007 //            Markus Rechberger <mrechberger@gmail.com>
0008 //            Mauro Carvalho Chehab <mchehab@kernel.org>
0009 //            Sascha Sommer <saschasommer@freenet.de>
0010 // Copyright (C) 2012 Frank Schäfer <fschaefer.oss@googlemail.com>
0011 //
0012 //  Some parts based on SN9C10x PC Camera Controllers GPL driver made
0013 //      by Luca Risolia <luca.risolia@studio.unibo.it>
0014 
0015 #include "em28xx.h"
0016 
0017 #include <linux/init.h>
0018 #include <linux/list.h>
0019 #include <linux/module.h>
0020 #include <linux/kernel.h>
0021 #include <linux/bitmap.h>
0022 #include <linux/usb.h>
0023 #include <linux/i2c.h>
0024 #include <linux/mm.h>
0025 #include <linux/mutex.h>
0026 #include <linux/slab.h>
0027 
0028 #include "em28xx-v4l.h"
0029 #include <media/v4l2-common.h>
0030 #include <media/v4l2-ioctl.h>
0031 #include <media/v4l2-event.h>
0032 #include <media/drv-intf/msp3400.h>
0033 #include <media/tuner.h>
0034 
0035 #define DRIVER_AUTHOR "Ludovico Cavedon <cavedon@sssup.it>, " \
0036               "Markus Rechberger <mrechberger@gmail.com>, " \
0037               "Mauro Carvalho Chehab <mchehab@kernel.org>, " \
0038               "Sascha Sommer <saschasommer@freenet.de>"
0039 
0040 static unsigned int isoc_debug;
0041 module_param(isoc_debug, int, 0644);
0042 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
0043 
0044 static unsigned int disable_vbi;
0045 module_param(disable_vbi, int, 0644);
0046 MODULE_PARM_DESC(disable_vbi, "disable vbi support");
0047 
0048 static int alt;
0049 module_param(alt, int, 0644);
0050 MODULE_PARM_DESC(alt, "alternate setting to use for video endpoint");
0051 
0052 #define em28xx_videodbg(fmt, arg...) do {               \
0053     if (video_debug)                        \
0054         dev_printk(KERN_DEBUG, &dev->intf->dev,         \
0055                "video: %s: " fmt, __func__, ## arg);    \
0056 } while (0)
0057 
0058 #define em28xx_isocdbg(fmt, arg...) do {\
0059     if (isoc_debug) \
0060         dev_printk(KERN_DEBUG, &dev->intf->dev,         \
0061                "isoc: %s: " fmt, __func__, ## arg);     \
0062 } while (0)
0063 
0064 MODULE_AUTHOR(DRIVER_AUTHOR);
0065 MODULE_DESCRIPTION(DRIVER_DESC " - v4l2 interface");
0066 MODULE_LICENSE("GPL v2");
0067 MODULE_VERSION(EM28XX_VERSION);
0068 
0069 #define EM25XX_FRMDATAHDR_BYTE1         0x02
0070 #define EM25XX_FRMDATAHDR_BYTE2_STILL_IMAGE 0x20
0071 #define EM25XX_FRMDATAHDR_BYTE2_FRAME_END   0x02
0072 #define EM25XX_FRMDATAHDR_BYTE2_FRAME_ID    0x01
0073 #define EM25XX_FRMDATAHDR_BYTE2_MASK    (EM25XX_FRMDATAHDR_BYTE2_STILL_IMAGE | \
0074                      EM25XX_FRMDATAHDR_BYTE2_FRAME_END |   \
0075                      EM25XX_FRMDATAHDR_BYTE2_FRAME_ID)
0076 
0077 static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
0078 static unsigned int vbi_nr[]   = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
0079 static unsigned int radio_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
0080 
0081 module_param_array(video_nr, int, NULL, 0444);
0082 module_param_array(vbi_nr, int, NULL, 0444);
0083 module_param_array(radio_nr, int, NULL, 0444);
0084 MODULE_PARM_DESC(video_nr, "video device numbers");
0085 MODULE_PARM_DESC(vbi_nr,   "vbi device numbers");
0086 MODULE_PARM_DESC(radio_nr, "radio device numbers");
0087 
0088 static unsigned int video_debug;
0089 module_param(video_debug, int, 0644);
0090 MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
0091 
0092 /* supported video standards */
0093 static struct em28xx_fmt format[] = {
0094     {
0095         .fourcc   = V4L2_PIX_FMT_YUYV,
0096         .depth    = 16,
0097         .reg      = EM28XX_OUTFMT_YUV422_Y0UY1V,
0098     }, {
0099         .fourcc   = V4L2_PIX_FMT_RGB565,
0100         .depth    = 16,
0101         .reg      = EM28XX_OUTFMT_RGB_16_656,
0102     }, {
0103         .fourcc   = V4L2_PIX_FMT_SRGGB8,
0104         .depth    = 8,
0105         .reg      = EM28XX_OUTFMT_RGB_8_RGRG,
0106     }, {
0107         .fourcc   = V4L2_PIX_FMT_SBGGR8,
0108         .depth    = 8,
0109         .reg      = EM28XX_OUTFMT_RGB_8_BGBG,
0110     }, {
0111         .fourcc   = V4L2_PIX_FMT_SGRBG8,
0112         .depth    = 8,
0113         .reg      = EM28XX_OUTFMT_RGB_8_GRGR,
0114     }, {
0115         .fourcc   = V4L2_PIX_FMT_SGBRG8,
0116         .depth    = 8,
0117         .reg      = EM28XX_OUTFMT_RGB_8_GBGB,
0118     }, {
0119         .fourcc   = V4L2_PIX_FMT_YUV411P,
0120         .depth    = 12,
0121         .reg      = EM28XX_OUTFMT_YUV411,
0122     },
0123 };
0124 
0125 /*FIXME: maxw should be dependent of alt mode */
0126 static inline unsigned int norm_maxw(struct em28xx *dev)
0127 {
0128     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0129 
0130     if (dev->is_webcam)
0131         return v4l2->sensor_xres;
0132 
0133     if (dev->board.max_range_640_480)
0134         return 640;
0135 
0136     return 720;
0137 }
0138 
0139 static inline unsigned int norm_maxh(struct em28xx *dev)
0140 {
0141     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0142 
0143     if (dev->is_webcam)
0144         return v4l2->sensor_yres;
0145 
0146     if (dev->board.max_range_640_480)
0147         return 480;
0148 
0149     return (v4l2->norm & V4L2_STD_625_50) ? 576 : 480;
0150 }
0151 
0152 static int em28xx_vbi_supported(struct em28xx *dev)
0153 {
0154     /* Modprobe option to manually disable */
0155     if (disable_vbi == 1)
0156         return 0;
0157 
0158     if (dev->is_webcam)
0159         return 0;
0160 
0161     /* FIXME: check subdevices for VBI support */
0162 
0163     if (dev->chip_id == CHIP_ID_EM2860 ||
0164         dev->chip_id == CHIP_ID_EM2883)
0165         return 1;
0166 
0167     /* Version of em28xx that does not support VBI */
0168     return 0;
0169 }
0170 
0171 /*
0172  * em28xx_wake_i2c()
0173  * configure i2c attached devices
0174  */
0175 static void em28xx_wake_i2c(struct em28xx *dev)
0176 {
0177     struct v4l2_device *v4l2_dev = &dev->v4l2->v4l2_dev;
0178 
0179     v4l2_device_call_all(v4l2_dev, 0, core,  reset, 0);
0180     v4l2_device_call_all(v4l2_dev, 0, video, s_routing,
0181                  INPUT(dev->ctl_input)->vmux, 0, 0);
0182 }
0183 
0184 static int em28xx_colorlevels_set_default(struct em28xx *dev)
0185 {
0186     em28xx_write_reg(dev, EM28XX_R20_YGAIN, CONTRAST_DEFAULT);
0187     em28xx_write_reg(dev, EM28XX_R21_YOFFSET, BRIGHTNESS_DEFAULT);
0188     em28xx_write_reg(dev, EM28XX_R22_UVGAIN, SATURATION_DEFAULT);
0189     em28xx_write_reg(dev, EM28XX_R23_UOFFSET, BLUE_BALANCE_DEFAULT);
0190     em28xx_write_reg(dev, EM28XX_R24_VOFFSET, RED_BALANCE_DEFAULT);
0191     em28xx_write_reg(dev, EM28XX_R25_SHARPNESS, SHARPNESS_DEFAULT);
0192 
0193     em28xx_write_reg(dev, EM28XX_R14_GAMMA, 0x20);
0194     em28xx_write_reg(dev, EM28XX_R15_RGAIN, 0x20);
0195     em28xx_write_reg(dev, EM28XX_R16_GGAIN, 0x20);
0196     em28xx_write_reg(dev, EM28XX_R17_BGAIN, 0x20);
0197     em28xx_write_reg(dev, EM28XX_R18_ROFFSET, 0x00);
0198     em28xx_write_reg(dev, EM28XX_R19_GOFFSET, 0x00);
0199     return em28xx_write_reg(dev, EM28XX_R1A_BOFFSET, 0x00);
0200 }
0201 
0202 static int em28xx_set_outfmt(struct em28xx *dev)
0203 {
0204     int ret;
0205     u8 fmt, vinctrl;
0206     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0207 
0208     fmt = v4l2->format->reg;
0209     if (!dev->is_em25xx)
0210         fmt |= 0x20;
0211     /*
0212      * NOTE: it's not clear if this is really needed !
0213      * The datasheets say bit 5 is a reserved bit and devices seem to work
0214      * fine without it. But the Windows driver sets it for em2710/50+em28xx
0215      * devices and we've always been setting it, too.
0216      *
0217      * em2765 (em25xx, em276x/7x/8x) devices do NOT work with this bit set,
0218      * it's likely used for an additional (compressed ?) format there.
0219      */
0220     ret = em28xx_write_reg(dev, EM28XX_R27_OUTFMT, fmt);
0221     if (ret < 0)
0222         return ret;
0223 
0224     ret = em28xx_write_reg(dev, EM28XX_R10_VINMODE, v4l2->vinmode);
0225     if (ret < 0)
0226         return ret;
0227 
0228     vinctrl = v4l2->vinctl;
0229     if (em28xx_vbi_supported(dev) == 1) {
0230         vinctrl |= EM28XX_VINCTRL_VBI_RAW;
0231         em28xx_write_reg(dev, EM28XX_R34_VBI_START_H, 0x00);
0232         em28xx_write_reg(dev, EM28XX_R36_VBI_WIDTH,
0233                  v4l2->vbi_width / 4);
0234         em28xx_write_reg(dev, EM28XX_R37_VBI_HEIGHT, v4l2->vbi_height);
0235         if (v4l2->norm & V4L2_STD_525_60) {
0236             /* NTSC */
0237             em28xx_write_reg(dev, EM28XX_R35_VBI_START_V, 0x09);
0238         } else if (v4l2->norm & V4L2_STD_625_50) {
0239             /* PAL */
0240             em28xx_write_reg(dev, EM28XX_R35_VBI_START_V, 0x07);
0241         }
0242     }
0243 
0244     return em28xx_write_reg(dev, EM28XX_R11_VINCTRL, vinctrl);
0245 }
0246 
0247 static int em28xx_accumulator_set(struct em28xx *dev, u8 xmin, u8 xmax,
0248                   u8 ymin, u8 ymax)
0249 {
0250     em28xx_videodbg("em28xx Scale: (%d,%d)-(%d,%d)\n",
0251             xmin, ymin, xmax, ymax);
0252 
0253     em28xx_write_regs(dev, EM28XX_R28_XMIN, &xmin, 1);
0254     em28xx_write_regs(dev, EM28XX_R29_XMAX, &xmax, 1);
0255     em28xx_write_regs(dev, EM28XX_R2A_YMIN, &ymin, 1);
0256     return em28xx_write_regs(dev, EM28XX_R2B_YMAX, &ymax, 1);
0257 }
0258 
0259 static void em28xx_capture_area_set(struct em28xx *dev, u8 hstart, u8 vstart,
0260                     u16 width, u16 height)
0261 {
0262     u8 cwidth = width >> 2;
0263     u8 cheight = height >> 2;
0264     u8 overflow = (height >> 9 & 0x02) | (width >> 10 & 0x01);
0265     /* NOTE: size limit: 2047x1023 = 2MPix */
0266 
0267     em28xx_videodbg("capture area set to (%d,%d): %dx%d\n",
0268             hstart, vstart,
0269                ((overflow & 2) << 9 | cwidth << 2),
0270                ((overflow & 1) << 10 | cheight << 2));
0271 
0272     em28xx_write_regs(dev, EM28XX_R1C_HSTART, &hstart, 1);
0273     em28xx_write_regs(dev, EM28XX_R1D_VSTART, &vstart, 1);
0274     em28xx_write_regs(dev, EM28XX_R1E_CWIDTH, &cwidth, 1);
0275     em28xx_write_regs(dev, EM28XX_R1F_CHEIGHT, &cheight, 1);
0276     em28xx_write_regs(dev, EM28XX_R1B_OFLOW, &overflow, 1);
0277 
0278     /* FIXME: function/meaning of these registers ? */
0279     /* FIXME: align width+height to multiples of 4 ?! */
0280     if (dev->is_em25xx) {
0281         em28xx_write_reg(dev, 0x34, width >> 4);
0282         em28xx_write_reg(dev, 0x35, height >> 4);
0283     }
0284 }
0285 
0286 static int em28xx_scaler_set(struct em28xx *dev, u16 h, u16 v)
0287 {
0288     u8 mode = 0x00;
0289     /* the em2800 scaler only supports scaling down to 50% */
0290 
0291     if (dev->board.is_em2800) {
0292         mode = (v ? 0x20 : 0x00) | (h ? 0x10 : 0x00);
0293     } else {
0294         u8 buf[2];
0295 
0296         buf[0] = h;
0297         buf[1] = h >> 8;
0298         em28xx_write_regs(dev, EM28XX_R30_HSCALELOW, (char *)buf, 2);
0299 
0300         buf[0] = v;
0301         buf[1] = v >> 8;
0302         em28xx_write_regs(dev, EM28XX_R32_VSCALELOW, (char *)buf, 2);
0303         /*
0304          * it seems that both H and V scalers must be active
0305          * to work correctly
0306          */
0307         mode = (h || v) ? 0x30 : 0x00;
0308     }
0309     return em28xx_write_reg(dev, EM28XX_R26_COMPR, mode);
0310 }
0311 
0312 /* FIXME: this only function read values from dev */
0313 static int em28xx_resolution_set(struct em28xx *dev)
0314 {
0315     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0316     int width = norm_maxw(dev);
0317     int height = norm_maxh(dev);
0318 
0319     /* Properly setup VBI */
0320     v4l2->vbi_width = 720;
0321     if (v4l2->norm & V4L2_STD_525_60)
0322         v4l2->vbi_height = 12;
0323     else
0324         v4l2->vbi_height = 18;
0325 
0326     em28xx_set_outfmt(dev);
0327 
0328     em28xx_accumulator_set(dev, 1, (width - 4) >> 2, 1, (height - 4) >> 2);
0329 
0330     /*
0331      * If we don't set the start position to 2 in VBI mode, we end up
0332      * with line 20/21 being YUYV encoded instead of being in 8-bit
0333      * greyscale.  The core of the issue is that line 21 (and line 23 for
0334      * PAL WSS) are inside of active video region, and as a result they
0335      * get the pixelformatting associated with that area.  So by cropping
0336      * it out, we end up with the same format as the rest of the VBI
0337      * region
0338      */
0339     if (em28xx_vbi_supported(dev) == 1)
0340         em28xx_capture_area_set(dev, 0, 2, width, height);
0341     else
0342         em28xx_capture_area_set(dev, 0, 0, width, height);
0343 
0344     return em28xx_scaler_set(dev, v4l2->hscale, v4l2->vscale);
0345 }
0346 
0347 /* Set USB alternate setting for analog video */
0348 static int em28xx_set_alternate(struct em28xx *dev)
0349 {
0350     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0351     struct usb_device *udev = interface_to_usbdev(dev->intf);
0352     int err;
0353     int i;
0354     unsigned int min_pkt_size = v4l2->width * 2 + 4;
0355 
0356     /*
0357      * NOTE: for isoc transfers, only alt settings > 0 are allowed
0358      * bulk transfers seem to work only with alt=0 !
0359      */
0360     dev->alt = 0;
0361     if (alt > 0 && alt < dev->num_alt) {
0362         em28xx_videodbg("alternate forced to %d\n", dev->alt);
0363         dev->alt = alt;
0364         goto set_alt;
0365     }
0366     if (dev->analog_xfer_bulk)
0367         goto set_alt;
0368 
0369     /*
0370      * When image size is bigger than a certain value,
0371      * the frame size should be increased, otherwise, only
0372      * green screen will be received.
0373      */
0374     if (v4l2->width * 2 * v4l2->height > 720 * 240 * 2)
0375         min_pkt_size *= 2;
0376 
0377     for (i = 0; i < dev->num_alt; i++) {
0378         /* stop when the selected alt setting offers enough bandwidth */
0379         if (dev->alt_max_pkt_size_isoc[i] >= min_pkt_size) {
0380             dev->alt = i;
0381             break;
0382         /*
0383          * otherwise make sure that we end up with the maximum
0384          * bandwidth because the min_pkt_size equation might be wrong.
0385          *
0386          */
0387         } else if (dev->alt_max_pkt_size_isoc[i] >
0388                dev->alt_max_pkt_size_isoc[dev->alt])
0389             dev->alt = i;
0390     }
0391 
0392 set_alt:
0393     /*
0394      * NOTE: for bulk transfers, we need to call usb_set_interface()
0395      * even if the previous settings were the same. Otherwise streaming
0396      * fails with all urbs having status = -EOVERFLOW !
0397      */
0398     if (dev->analog_xfer_bulk) {
0399         dev->max_pkt_size = 512; /* USB 2.0 spec */
0400         dev->packet_multiplier = EM28XX_BULK_PACKET_MULTIPLIER;
0401     } else { /* isoc */
0402         em28xx_videodbg("minimum isoc packet size: %u (alt=%d)\n",
0403                 min_pkt_size, dev->alt);
0404         dev->max_pkt_size =
0405                   dev->alt_max_pkt_size_isoc[dev->alt];
0406         dev->packet_multiplier = EM28XX_NUM_ISOC_PACKETS;
0407     }
0408     em28xx_videodbg("setting alternate %d with wMaxPacketSize=%u\n",
0409             dev->alt, dev->max_pkt_size);
0410     err = usb_set_interface(udev, dev->ifnum, dev->alt);
0411     if (err < 0) {
0412         dev_err(&dev->intf->dev,
0413             "cannot change alternate number to %d (error=%i)\n",
0414             dev->alt, err);
0415         return err;
0416     }
0417     return 0;
0418 }
0419 
0420 /*
0421  * DMA and thread functions
0422  */
0423 
0424 /*
0425  * Finish the current buffer
0426  */
0427 static inline void finish_buffer(struct em28xx *dev,
0428                  struct em28xx_buffer *buf)
0429 {
0430     em28xx_isocdbg("[%p/%d] wakeup\n", buf, buf->top_field);
0431 
0432     buf->vb.sequence = dev->v4l2->field_count++;
0433     if (dev->v4l2->progressive)
0434         buf->vb.field = V4L2_FIELD_NONE;
0435     else
0436         buf->vb.field = V4L2_FIELD_INTERLACED;
0437     buf->vb.vb2_buf.timestamp = ktime_get_ns();
0438 
0439     vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_DONE);
0440 }
0441 
0442 /*
0443  * Copy picture data from USB buffer to videobuf buffer
0444  */
0445 static void em28xx_copy_video(struct em28xx *dev,
0446                   struct em28xx_buffer *buf,
0447                   unsigned char *usb_buf,
0448                   unsigned long len)
0449 {
0450     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0451     void *fieldstart, *startwrite, *startread;
0452     int  linesdone, currlinedone, offset, lencopy, remain;
0453     int bytesperline = v4l2->width << 1;
0454 
0455     if (buf->pos + len > buf->length)
0456         len = buf->length - buf->pos;
0457 
0458     startread = usb_buf;
0459     remain = len;
0460 
0461     if (v4l2->progressive || buf->top_field)
0462         fieldstart = buf->vb_buf;
0463     else /* interlaced mode, even nr. of lines */
0464         fieldstart = buf->vb_buf + bytesperline;
0465 
0466     linesdone = buf->pos / bytesperline;
0467     currlinedone = buf->pos % bytesperline;
0468 
0469     if (v4l2->progressive)
0470         offset = linesdone * bytesperline + currlinedone;
0471     else
0472         offset = linesdone * bytesperline * 2 + currlinedone;
0473 
0474     startwrite = fieldstart + offset;
0475     lencopy = bytesperline - currlinedone;
0476     lencopy = lencopy > remain ? remain : lencopy;
0477 
0478     if ((char *)startwrite + lencopy > (char *)buf->vb_buf + buf->length) {
0479         em28xx_isocdbg("Overflow of %zu bytes past buffer end (1)\n",
0480                    ((char *)startwrite + lencopy) -
0481                   ((char *)buf->vb_buf + buf->length));
0482         remain = (char *)buf->vb_buf + buf->length -
0483              (char *)startwrite;
0484         lencopy = remain;
0485     }
0486     if (lencopy <= 0)
0487         return;
0488     memcpy(startwrite, startread, lencopy);
0489 
0490     remain -= lencopy;
0491 
0492     while (remain > 0) {
0493         if (v4l2->progressive)
0494             startwrite += lencopy;
0495         else
0496             startwrite += lencopy + bytesperline;
0497         startread += lencopy;
0498         if (bytesperline > remain)
0499             lencopy = remain;
0500         else
0501             lencopy = bytesperline;
0502 
0503         if ((char *)startwrite + lencopy > (char *)buf->vb_buf +
0504             buf->length) {
0505             em28xx_isocdbg("Overflow of %zu bytes past buffer end(2)\n",
0506                        ((char *)startwrite + lencopy) -
0507                        ((char *)buf->vb_buf + buf->length));
0508             remain = (char *)buf->vb_buf + buf->length -
0509                  (char *)startwrite;
0510             lencopy = remain;
0511         }
0512         if (lencopy <= 0)
0513             break;
0514 
0515         memcpy(startwrite, startread, lencopy);
0516 
0517         remain -= lencopy;
0518     }
0519 
0520     buf->pos += len;
0521 }
0522 
0523 /*
0524  * Copy VBI data from USB buffer to videobuf buffer
0525  */
0526 static void em28xx_copy_vbi(struct em28xx *dev,
0527                 struct em28xx_buffer *buf,
0528                 unsigned char *usb_buf,
0529                 unsigned long len)
0530 {
0531     unsigned int offset;
0532 
0533     if (buf->pos + len > buf->length)
0534         len = buf->length - buf->pos;
0535 
0536     offset = buf->pos;
0537     /* Make sure the bottom field populates the second half of the frame */
0538     if (buf->top_field == 0)
0539         offset += dev->v4l2->vbi_width * dev->v4l2->vbi_height;
0540 
0541     memcpy(buf->vb_buf + offset, usb_buf, len);
0542     buf->pos += len;
0543 }
0544 
0545 static inline void print_err_status(struct em28xx *dev,
0546                     int packet, int status)
0547 {
0548     char *errmsg = "Unknown";
0549 
0550     switch (status) {
0551     case -ENOENT:
0552         errmsg = "unlinked synchronously";
0553         break;
0554     case -ECONNRESET:
0555         errmsg = "unlinked asynchronously";
0556         break;
0557     case -ENOSR:
0558         errmsg = "Buffer error (overrun)";
0559         break;
0560     case -EPIPE:
0561         errmsg = "Stalled (device not responding)";
0562         break;
0563     case -EOVERFLOW:
0564         errmsg = "Babble (bad cable?)";
0565         break;
0566     case -EPROTO:
0567         errmsg = "Bit-stuff error (bad cable?)";
0568         break;
0569     case -EILSEQ:
0570         errmsg = "CRC/Timeout (could be anything)";
0571         break;
0572     case -ETIME:
0573         errmsg = "Device does not respond";
0574         break;
0575     }
0576     if (packet < 0) {
0577         em28xx_isocdbg("URB status %d [%s].\n", status, errmsg);
0578     } else {
0579         em28xx_isocdbg("URB packet %d, status %d [%s].\n",
0580                    packet, status, errmsg);
0581     }
0582 }
0583 
0584 /*
0585  * get the next available buffer from dma queue
0586  */
0587 static inline struct em28xx_buffer *get_next_buf(struct em28xx *dev,
0588                          struct em28xx_dmaqueue *dma_q)
0589 {
0590     struct em28xx_buffer *buf;
0591 
0592     if (list_empty(&dma_q->active)) {
0593         em28xx_isocdbg("No active queue to serve\n");
0594         return NULL;
0595     }
0596 
0597     /* Get the next buffer */
0598     buf = list_entry(dma_q->active.next, struct em28xx_buffer, list);
0599     /* Cleans up buffer - Useful for testing for frame/URB loss */
0600     list_del(&buf->list);
0601     buf->pos = 0;
0602     buf->vb_buf = buf->mem;
0603 
0604     return buf;
0605 }
0606 
0607 /*
0608  * Finish the current buffer if completed and prepare for the next field
0609  */
0610 static struct em28xx_buffer *
0611 finish_field_prepare_next(struct em28xx *dev,
0612               struct em28xx_buffer *buf,
0613               struct em28xx_dmaqueue *dma_q)
0614 {
0615     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0616 
0617     if (v4l2->progressive || v4l2->top_field) { /* Brand new frame */
0618         if (buf)
0619             finish_buffer(dev, buf);
0620         buf = get_next_buf(dev, dma_q);
0621     }
0622     if (buf) {
0623         buf->top_field = v4l2->top_field;
0624         buf->pos = 0;
0625     }
0626 
0627     return buf;
0628 }
0629 
0630 /*
0631  * Process data packet according to the em2710/em2750/em28xx frame data format
0632  */
0633 static inline void process_frame_data_em28xx(struct em28xx *dev,
0634                          unsigned char *data_pkt,
0635                          unsigned int  data_len)
0636 {
0637     struct em28xx_v4l2      *v4l2 = dev->v4l2;
0638     struct em28xx_buffer    *buf = dev->usb_ctl.vid_buf;
0639     struct em28xx_buffer    *vbi_buf = dev->usb_ctl.vbi_buf;
0640     struct em28xx_dmaqueue  *dma_q = &dev->vidq;
0641     struct em28xx_dmaqueue  *vbi_dma_q = &dev->vbiq;
0642 
0643     /*
0644      * capture type 0 = vbi start
0645      * capture type 1 = vbi in progress
0646      * capture type 2 = video start
0647      * capture type 3 = video in progress
0648      */
0649     if (data_len >= 4) {
0650         /*
0651          * NOTE: Headers are always 4 bytes and
0652          * never split across packets
0653          */
0654         if (data_pkt[0] == 0x88 && data_pkt[1] == 0x88 &&
0655             data_pkt[2] == 0x88 && data_pkt[3] == 0x88) {
0656             /* Continuation */
0657             data_pkt += 4;
0658             data_len -= 4;
0659         } else if (data_pkt[0] == 0x33 && data_pkt[1] == 0x95) {
0660             /* Field start (VBI mode) */
0661             v4l2->capture_type = 0;
0662             v4l2->vbi_read = 0;
0663             em28xx_isocdbg("VBI START HEADER !!!\n");
0664             v4l2->top_field = !(data_pkt[2] & 1);
0665             data_pkt += 4;
0666             data_len -= 4;
0667         } else if (data_pkt[0] == 0x22 && data_pkt[1] == 0x5a) {
0668             /* Field start (VBI disabled) */
0669             v4l2->capture_type = 2;
0670             em28xx_isocdbg("VIDEO START HEADER !!!\n");
0671             v4l2->top_field = !(data_pkt[2] & 1);
0672             data_pkt += 4;
0673             data_len -= 4;
0674         }
0675     }
0676     /*
0677      * NOTE: With bulk transfers, intermediate data packets
0678      * have no continuation header
0679      */
0680 
0681     if (v4l2->capture_type == 0) {
0682         vbi_buf = finish_field_prepare_next(dev, vbi_buf, vbi_dma_q);
0683         dev->usb_ctl.vbi_buf = vbi_buf;
0684         v4l2->capture_type = 1;
0685     }
0686 
0687     if (v4l2->capture_type == 1) {
0688         int vbi_size = v4l2->vbi_width * v4l2->vbi_height;
0689         int vbi_data_len = ((v4l2->vbi_read + data_len) > vbi_size) ?
0690                    (vbi_size - v4l2->vbi_read) : data_len;
0691 
0692         /* Copy VBI data */
0693         if (vbi_buf)
0694             em28xx_copy_vbi(dev, vbi_buf, data_pkt, vbi_data_len);
0695         v4l2->vbi_read += vbi_data_len;
0696 
0697         if (vbi_data_len < data_len) {
0698             /* Continue with copying video data */
0699             v4l2->capture_type = 2;
0700             data_pkt += vbi_data_len;
0701             data_len -= vbi_data_len;
0702         }
0703     }
0704 
0705     if (v4l2->capture_type == 2) {
0706         buf = finish_field_prepare_next(dev, buf, dma_q);
0707         dev->usb_ctl.vid_buf = buf;
0708         v4l2->capture_type = 3;
0709     }
0710 
0711     if (v4l2->capture_type == 3 && buf && data_len > 0)
0712         em28xx_copy_video(dev, buf, data_pkt, data_len);
0713 }
0714 
0715 /*
0716  * Process data packet according to the em25xx/em276x/7x/8x frame data format
0717  */
0718 static inline void process_frame_data_em25xx(struct em28xx *dev,
0719                          unsigned char *data_pkt,
0720                          unsigned int  data_len)
0721 {
0722     struct em28xx_buffer    *buf = dev->usb_ctl.vid_buf;
0723     struct em28xx_dmaqueue  *dmaq = &dev->vidq;
0724     struct em28xx_v4l2      *v4l2 = dev->v4l2;
0725     bool frame_end = false;
0726 
0727     /* Check for header */
0728     /*
0729      * NOTE: at least with bulk transfers, only the first packet
0730      * has a header and has always set the FRAME_END bit
0731      */
0732     if (data_len >= 2) {    /* em25xx header is only 2 bytes long */
0733         if ((data_pkt[0] == EM25XX_FRMDATAHDR_BYTE1) &&
0734             ((data_pkt[1] & ~EM25XX_FRMDATAHDR_BYTE2_MASK) == 0x00)) {
0735             v4l2->top_field = !(data_pkt[1] &
0736                        EM25XX_FRMDATAHDR_BYTE2_FRAME_ID);
0737             frame_end = data_pkt[1] &
0738                     EM25XX_FRMDATAHDR_BYTE2_FRAME_END;
0739             data_pkt += 2;
0740             data_len -= 2;
0741         }
0742 
0743         /* Finish field and prepare next (BULK only) */
0744         if (dev->analog_xfer_bulk && frame_end) {
0745             buf = finish_field_prepare_next(dev, buf, dmaq);
0746             dev->usb_ctl.vid_buf = buf;
0747         }
0748         /*
0749          * NOTE: in ISOC mode when a new frame starts and buf==NULL,
0750          * we COULD already prepare a buffer here to avoid skipping the
0751          * first frame.
0752          */
0753     }
0754 
0755     /* Copy data */
0756     if (buf && data_len > 0)
0757         em28xx_copy_video(dev, buf, data_pkt, data_len);
0758 
0759     /* Finish frame (ISOC only) => avoids lag of 1 frame */
0760     if (!dev->analog_xfer_bulk && frame_end) {
0761         buf = finish_field_prepare_next(dev, buf, dmaq);
0762         dev->usb_ctl.vid_buf = buf;
0763     }
0764 
0765     /*
0766      * NOTES:
0767      *
0768      * 1) Tested with USB bulk transfers only !
0769      * The wording in the datasheet suggests that isoc might work different.
0770      * The current code assumes that with isoc transfers each packet has a
0771      * header like with the other em28xx devices.
0772      *
0773      * 2) Support for interlaced mode is pure theory. It has not been
0774      * tested and it is unknown if these devices actually support it.
0775      */
0776 }
0777 
0778 /* Processes and copies the URB data content (video and VBI data) */
0779 static inline int em28xx_urb_data_copy(struct em28xx *dev, struct urb *urb)
0780 {
0781     int xfer_bulk, num_packets, i;
0782     unsigned char *usb_data_pkt;
0783     unsigned int usb_data_len;
0784 
0785     if (!dev)
0786         return 0;
0787 
0788     if (dev->disconnected)
0789         return 0;
0790 
0791     if (urb->status < 0)
0792         print_err_status(dev, -1, urb->status);
0793 
0794     xfer_bulk = usb_pipebulk(urb->pipe);
0795 
0796     if (xfer_bulk) /* bulk */
0797         num_packets = 1;
0798     else /* isoc */
0799         num_packets = urb->number_of_packets;
0800 
0801     for (i = 0; i < num_packets; i++) {
0802         if (xfer_bulk) { /* bulk */
0803             usb_data_len = urb->actual_length;
0804 
0805             usb_data_pkt = urb->transfer_buffer;
0806         } else { /* isoc */
0807             if (urb->iso_frame_desc[i].status < 0) {
0808                 print_err_status(dev, i,
0809                          urb->iso_frame_desc[i].status);
0810                 if (urb->iso_frame_desc[i].status != -EPROTO)
0811                     continue;
0812             }
0813 
0814             usb_data_len = urb->iso_frame_desc[i].actual_length;
0815             if (usb_data_len > dev->max_pkt_size) {
0816                 em28xx_isocdbg("packet bigger than packet size");
0817                 continue;
0818             }
0819 
0820             usb_data_pkt = urb->transfer_buffer +
0821                        urb->iso_frame_desc[i].offset;
0822         }
0823 
0824         if (usb_data_len == 0) {
0825             /* NOTE: happens very often with isoc transfers */
0826             /* em28xx_usbdbg("packet %d is empty",i); - spammy */
0827             continue;
0828         }
0829 
0830         if (dev->is_em25xx)
0831             process_frame_data_em25xx(dev,
0832                           usb_data_pkt, usb_data_len);
0833         else
0834             process_frame_data_em28xx(dev,
0835                           usb_data_pkt, usb_data_len);
0836     }
0837     return 1;
0838 }
0839 
0840 static int get_resource(enum v4l2_buf_type f_type)
0841 {
0842     switch (f_type) {
0843     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
0844         return EM28XX_RESOURCE_VIDEO;
0845     case V4L2_BUF_TYPE_VBI_CAPTURE:
0846         return EM28XX_RESOURCE_VBI;
0847     default:
0848         WARN_ON(1);
0849         return -1; /* Indicate that device is busy */
0850     }
0851 }
0852 
0853 /* Usage lock check functions */
0854 static int res_get(struct em28xx *dev, enum v4l2_buf_type f_type)
0855 {
0856     int res_type = get_resource(f_type);
0857 
0858     /* is it free? */
0859     if (dev->resources & res_type) {
0860         /* no, someone else uses it */
0861         return -EBUSY;
0862     }
0863 
0864     /* it's free, grab it */
0865     dev->resources |= res_type;
0866     em28xx_videodbg("res: get %d\n", res_type);
0867     return 0;
0868 }
0869 
0870 static void res_free(struct em28xx *dev, enum v4l2_buf_type f_type)
0871 {
0872     int res_type = get_resource(f_type);
0873 
0874     dev->resources &= ~res_type;
0875     em28xx_videodbg("res: put %d\n", res_type);
0876 }
0877 
0878 static void em28xx_v4l2_media_release(struct em28xx *dev)
0879 {
0880 #ifdef CONFIG_MEDIA_CONTROLLER
0881     int i;
0882 
0883     for (i = 0; i < MAX_EM28XX_INPUT; i++) {
0884         if (!INPUT(i)->type)
0885             return;
0886         media_device_unregister_entity(&dev->input_ent[i]);
0887     }
0888 #endif
0889 }
0890 
0891 /*
0892  * Media Controller helper functions
0893  */
0894 
0895 static int em28xx_enable_analog_tuner(struct em28xx *dev)
0896 {
0897 #ifdef CONFIG_MEDIA_CONTROLLER
0898     struct media_device *mdev = dev->media_dev;
0899     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0900     struct media_entity *source;
0901     struct media_link *link, *found_link = NULL;
0902     int ret, active_links = 0;
0903 
0904     if (!mdev || !v4l2->decoder)
0905         return 0;
0906 
0907     /*
0908      * This will find the tuner that is connected into the decoder.
0909      * Technically, this is not 100% correct, as the device may be
0910      * using an analog input instead of the tuner. However, as we can't
0911      * do DVB streaming while the DMA engine is being used for V4L2,
0912      * this should be enough for the actual needs.
0913      */
0914     list_for_each_entry(link, &v4l2->decoder->links, list) {
0915         if (link->sink->entity == v4l2->decoder) {
0916             found_link = link;
0917             if (link->flags & MEDIA_LNK_FL_ENABLED)
0918                 active_links++;
0919             break;
0920         }
0921     }
0922 
0923     if (active_links == 1 || !found_link)
0924         return 0;
0925 
0926     source = found_link->source->entity;
0927     list_for_each_entry(link, &source->links, list) {
0928         struct media_entity *sink;
0929         int flags = 0;
0930 
0931         sink = link->sink->entity;
0932 
0933         if (sink == v4l2->decoder)
0934             flags = MEDIA_LNK_FL_ENABLED;
0935 
0936         ret = media_entity_setup_link(link, flags);
0937         if (ret) {
0938             dev_err(&dev->intf->dev,
0939                 "Couldn't change link %s->%s to %s. Error %d\n",
0940                 source->name, sink->name,
0941                 flags ? "enabled" : "disabled",
0942                 ret);
0943             return ret;
0944         }
0945 
0946         em28xx_videodbg("link %s->%s was %s\n",
0947                 source->name, sink->name,
0948                 flags ? "ENABLED" : "disabled");
0949     }
0950 #endif
0951     return 0;
0952 }
0953 
0954 static const char * const iname[] = {
0955     [EM28XX_VMUX_COMPOSITE]  = "Composite",
0956     [EM28XX_VMUX_SVIDEO]     = "S-Video",
0957     [EM28XX_VMUX_TELEVISION] = "Television",
0958     [EM28XX_RADIO]           = "Radio",
0959 };
0960 
0961 static void em28xx_v4l2_create_entities(struct em28xx *dev)
0962 {
0963 #if defined(CONFIG_MEDIA_CONTROLLER)
0964     struct em28xx_v4l2 *v4l2 = dev->v4l2;
0965     int ret, i;
0966 
0967     /* Initialize Video, VBI and Radio pads */
0968     v4l2->video_pad.flags = MEDIA_PAD_FL_SINK;
0969     ret = media_entity_pads_init(&v4l2->vdev.entity, 1, &v4l2->video_pad);
0970     if (ret < 0)
0971         dev_err(&dev->intf->dev,
0972             "failed to initialize video media entity!\n");
0973 
0974     if (em28xx_vbi_supported(dev)) {
0975         v4l2->vbi_pad.flags = MEDIA_PAD_FL_SINK;
0976         ret = media_entity_pads_init(&v4l2->vbi_dev.entity, 1,
0977                          &v4l2->vbi_pad);
0978         if (ret < 0)
0979             dev_err(&dev->intf->dev,
0980                 "failed to initialize vbi media entity!\n");
0981     }
0982 
0983     /* Webcams don't have input connectors */
0984     if (dev->is_webcam)
0985         return;
0986 
0987     /* Create entities for each input connector */
0988     for (i = 0; i < MAX_EM28XX_INPUT; i++) {
0989         struct media_entity *ent = &dev->input_ent[i];
0990 
0991         if (!INPUT(i)->type)
0992             break;
0993 
0994         ent->name = iname[INPUT(i)->type];
0995         ent->flags = MEDIA_ENT_FL_CONNECTOR;
0996         dev->input_pad[i].flags = MEDIA_PAD_FL_SOURCE;
0997 
0998         switch (INPUT(i)->type) {
0999         case EM28XX_VMUX_COMPOSITE:
1000             ent->function = MEDIA_ENT_F_CONN_COMPOSITE;
1001             break;
1002         case EM28XX_VMUX_SVIDEO:
1003             ent->function = MEDIA_ENT_F_CONN_SVIDEO;
1004             break;
1005         default: /* EM28XX_VMUX_TELEVISION or EM28XX_RADIO */
1006             if (dev->tuner_type != TUNER_ABSENT)
1007                 ent->function = MEDIA_ENT_F_CONN_RF;
1008             break;
1009         }
1010 
1011         ret = media_entity_pads_init(ent, 1, &dev->input_pad[i]);
1012         if (ret < 0)
1013             dev_err(&dev->intf->dev,
1014                 "failed to initialize input pad[%d]!\n", i);
1015 
1016         ret = media_device_register_entity(dev->media_dev, ent);
1017         if (ret < 0)
1018             dev_err(&dev->intf->dev,
1019                 "failed to register input entity %d!\n", i);
1020     }
1021 #endif
1022 }
1023 
1024 /*
1025  * Videobuf2 operations
1026  */
1027 
1028 static int queue_setup(struct vb2_queue *vq,
1029                unsigned int *nbuffers, unsigned int *nplanes,
1030                unsigned int sizes[], struct device *alloc_devs[])
1031 {
1032     struct em28xx *dev = vb2_get_drv_priv(vq);
1033     struct em28xx_v4l2 *v4l2 = dev->v4l2;
1034     unsigned long size =
1035             (v4l2->width * v4l2->height * v4l2->format->depth + 7) >> 3;
1036 
1037     if (*nplanes)
1038         return sizes[0] < size ? -EINVAL : 0;
1039     *nplanes = 1;
1040     sizes[0] = size;
1041 
1042     em28xx_enable_analog_tuner(dev);
1043 
1044     return 0;
1045 }
1046 
1047 static int
1048 buffer_prepare(struct vb2_buffer *vb)
1049 {
1050     struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1051     struct em28xx        *dev = vb2_get_drv_priv(vb->vb2_queue);
1052     struct em28xx_v4l2   *v4l2 = dev->v4l2;
1053     unsigned long size;
1054 
1055     em28xx_videodbg("%s, field=%d\n", __func__, vbuf->field);
1056 
1057     size = (v4l2->width * v4l2->height * v4l2->format->depth + 7) >> 3;
1058 
1059     if (vb2_plane_size(vb, 0) < size) {
1060         em28xx_videodbg("%s data will not fit into plane (%lu < %lu)\n",
1061                 __func__, vb2_plane_size(vb, 0), size);
1062         return -EINVAL;
1063     }
1064     vb2_set_plane_payload(vb, 0, size);
1065 
1066     return 0;
1067 }
1068 
1069 int em28xx_start_analog_streaming(struct vb2_queue *vq, unsigned int count)
1070 {
1071     struct em28xx *dev = vb2_get_drv_priv(vq);
1072     struct em28xx_v4l2 *v4l2 = dev->v4l2;
1073     struct v4l2_frequency f;
1074     struct v4l2_fh *owner;
1075     int rc = 0;
1076 
1077     em28xx_videodbg("%s\n", __func__);
1078 
1079     dev->v4l2->field_count = 0;
1080 
1081     /*
1082      * Make sure streaming is not already in progress for this type
1083      * of filehandle (e.g. video, vbi)
1084      */
1085     rc = res_get(dev, vq->type);
1086     if (rc)
1087         return rc;
1088 
1089     if (v4l2->streaming_users == 0) {
1090         /* First active streaming user, so allocate all the URBs */
1091 
1092         /* Allocate the USB bandwidth */
1093         em28xx_set_alternate(dev);
1094 
1095         /*
1096          * Needed, since GPIO might have disabled power of
1097          * some i2c device
1098          */
1099         em28xx_wake_i2c(dev);
1100 
1101         v4l2->capture_type = -1;
1102         rc = em28xx_init_usb_xfer(dev, EM28XX_ANALOG_MODE,
1103                       dev->analog_xfer_bulk,
1104                       EM28XX_NUM_BUFS,
1105                       dev->max_pkt_size,
1106                       dev->packet_multiplier,
1107                       em28xx_urb_data_copy);
1108         if (rc < 0)
1109             return rc;
1110 
1111         /*
1112          * djh: it's not clear whether this code is still needed.  I'm
1113          * leaving it in here for now entirely out of concern for
1114          * backward compatibility (the old code did it)
1115          */
1116 
1117         /* Ask tuner to go to analog or radio mode */
1118         memset(&f, 0, sizeof(f));
1119         f.frequency = v4l2->frequency;
1120         owner = (struct v4l2_fh *)vq->owner;
1121         if (owner && owner->vdev->vfl_type == VFL_TYPE_RADIO)
1122             f.type = V4L2_TUNER_RADIO;
1123         else
1124             f.type = V4L2_TUNER_ANALOG_TV;
1125         v4l2_device_call_all(&v4l2->v4l2_dev,
1126                      0, tuner, s_frequency, &f);
1127 
1128         /* Enable video stream at TV decoder */
1129         v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 1);
1130     }
1131 
1132     v4l2->streaming_users++;
1133 
1134     return rc;
1135 }
1136 
1137 static void em28xx_stop_streaming(struct vb2_queue *vq)
1138 {
1139     struct em28xx *dev = vb2_get_drv_priv(vq);
1140     struct em28xx_v4l2 *v4l2 = dev->v4l2;
1141     struct em28xx_dmaqueue *vidq = &dev->vidq;
1142     unsigned long flags = 0;
1143 
1144     em28xx_videodbg("%s\n", __func__);
1145 
1146     res_free(dev, vq->type);
1147 
1148     if (v4l2->streaming_users-- == 1) {
1149         /* Disable video stream at TV decoder */
1150         v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 0);
1151 
1152         /* Last active user, so shutdown all the URBS */
1153         em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
1154     }
1155 
1156     spin_lock_irqsave(&dev->slock, flags);
1157     if (dev->usb_ctl.vid_buf) {
1158         vb2_buffer_done(&dev->usb_ctl.vid_buf->vb.vb2_buf,
1159                 VB2_BUF_STATE_ERROR);
1160         dev->usb_ctl.vid_buf = NULL;
1161     }
1162     while (!list_empty(&vidq->active)) {
1163         struct em28xx_buffer *buf;
1164 
1165         buf = list_entry(vidq->active.next, struct em28xx_buffer, list);
1166         list_del(&buf->list);
1167         vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1168     }
1169     spin_unlock_irqrestore(&dev->slock, flags);
1170 }
1171 
1172 void em28xx_stop_vbi_streaming(struct vb2_queue *vq)
1173 {
1174     struct em28xx *dev = vb2_get_drv_priv(vq);
1175     struct em28xx_v4l2 *v4l2 = dev->v4l2;
1176     struct em28xx_dmaqueue *vbiq = &dev->vbiq;
1177     unsigned long flags = 0;
1178 
1179     em28xx_videodbg("%s\n", __func__);
1180 
1181     res_free(dev, vq->type);
1182 
1183     if (v4l2->streaming_users-- == 1) {
1184         /* Disable video stream at TV decoder */
1185         v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_stream, 0);
1186 
1187         /* Last active user, so shutdown all the URBS */
1188         em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
1189     }
1190 
1191     spin_lock_irqsave(&dev->slock, flags);
1192     if (dev->usb_ctl.vbi_buf) {
1193         vb2_buffer_done(&dev->usb_ctl.vbi_buf->vb.vb2_buf,
1194                 VB2_BUF_STATE_ERROR);
1195         dev->usb_ctl.vbi_buf = NULL;
1196     }
1197     while (!list_empty(&vbiq->active)) {
1198         struct em28xx_buffer *buf;
1199 
1200         buf = list_entry(vbiq->active.next, struct em28xx_buffer, list);
1201         list_del(&buf->list);
1202         vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1203     }
1204     spin_unlock_irqrestore(&dev->slock, flags);
1205 }
1206 
1207 static void
1208 buffer_queue(struct vb2_buffer *vb)
1209 {
1210     struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1211     struct em28xx *dev = vb2_get_drv_priv(vb->vb2_queue);
1212     struct em28xx_buffer *buf =
1213         container_of(vbuf, struct em28xx_buffer, vb);
1214     struct em28xx_dmaqueue *vidq = &dev->vidq;
1215     unsigned long flags = 0;
1216 
1217     em28xx_videodbg("%s\n", __func__);
1218     buf->mem = vb2_plane_vaddr(vb, 0);
1219     buf->length = vb2_plane_size(vb, 0);
1220 
1221     spin_lock_irqsave(&dev->slock, flags);
1222     list_add_tail(&buf->list, &vidq->active);
1223     spin_unlock_irqrestore(&dev->slock, flags);
1224 }
1225 
1226 static const struct vb2_ops em28xx_video_qops = {
1227     .queue_setup    = queue_setup,
1228     .buf_prepare    = buffer_prepare,
1229     .buf_queue      = buffer_queue,
1230     .start_streaming = em28xx_start_analog_streaming,
1231     .stop_streaming = em28xx_stop_streaming,
1232     .wait_prepare   = vb2_ops_wait_prepare,
1233     .wait_finish    = vb2_ops_wait_finish,
1234 };
1235 
1236 static int em28xx_vb2_setup(struct em28xx *dev)
1237 {
1238     int rc;
1239     struct vb2_queue *q;
1240     struct em28xx_v4l2 *v4l2 = dev->v4l2;
1241 
1242     /* Setup Videobuf2 for Video capture */
1243     q = &v4l2->vb_vidq;
1244     q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1245     q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1246     q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1247     q->drv_priv = dev;
1248     q->buf_struct_size = sizeof(struct em28xx_buffer);
1249     q->ops = &em28xx_video_qops;
1250     q->mem_ops = &vb2_vmalloc_memops;
1251 
1252     rc = vb2_queue_init(q);
1253     if (rc < 0)
1254         return rc;
1255 
1256     /* Setup Videobuf2 for VBI capture */
1257     q = &v4l2->vb_vbiq;
1258     q->type = V4L2_BUF_TYPE_VBI_CAPTURE;
1259     q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR;
1260     q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1261     q->drv_priv = dev;
1262     q->buf_struct_size = sizeof(struct em28xx_buffer);
1263     q->ops = &em28xx_vbi_qops;
1264     q->mem_ops = &vb2_vmalloc_memops;
1265 
1266     rc = vb2_queue_init(q);
1267     if (rc < 0)
1268         return rc;
1269 
1270     return 0;
1271 }
1272 
1273 /*
1274  * v4l2 interface
1275  */
1276 
1277 static void video_mux(struct em28xx *dev, int index)
1278 {
1279     struct v4l2_device *v4l2_dev = &dev->v4l2->v4l2_dev;
1280 
1281     dev->ctl_input = index;
1282     dev->ctl_ainput = INPUT(index)->amux;
1283     dev->ctl_aoutput = INPUT(index)->aout;
1284 
1285     if (!dev->ctl_aoutput)
1286         dev->ctl_aoutput = EM28XX_AOUT_MASTER;
1287 
1288     v4l2_device_call_all(v4l2_dev, 0, video, s_routing,
1289                  INPUT(index)->vmux, 0, 0);
1290 
1291     if (dev->has_msp34xx) {
1292         if (dev->i2s_speed) {
1293             v4l2_device_call_all(v4l2_dev, 0, audio,
1294                          s_i2s_clock_freq, dev->i2s_speed);
1295         }
1296         /* Note: this is msp3400 specific */
1297         v4l2_device_call_all(v4l2_dev, 0, audio, s_routing,
1298                      dev->ctl_ainput,
1299                      MSP_OUTPUT(MSP_SC_IN_DSP_SCART1), 0);
1300     }
1301 
1302     if (dev->board.adecoder != EM28XX_NOADECODER) {
1303         v4l2_device_call_all(v4l2_dev, 0, audio, s_routing,
1304                      dev->ctl_ainput, dev->ctl_aoutput, 0);
1305     }
1306 
1307     em28xx_audio_analog_set(dev);
1308 }
1309 
1310 static void em28xx_ctrl_notify(struct v4l2_ctrl *ctrl, void *priv)
1311 {
1312     struct em28xx *dev = priv;
1313 
1314     /*
1315      * In the case of non-AC97 volume controls, we still need
1316      * to do some setups at em28xx, in order to mute/unmute
1317      * and to adjust audio volume. However, the value ranges
1318      * should be checked by the corresponding V4L subdriver.
1319      */
1320     switch (ctrl->id) {
1321     case V4L2_CID_AUDIO_MUTE:
1322         dev->mute = ctrl->val;
1323         em28xx_audio_analog_set(dev);
1324         break;
1325     case V4L2_CID_AUDIO_VOLUME:
1326         dev->volume = ctrl->val;
1327         em28xx_audio_analog_set(dev);
1328         break;
1329     }
1330 }
1331 
1332 static int em28xx_s_ctrl(struct v4l2_ctrl *ctrl)
1333 {
1334     struct em28xx_v4l2 *v4l2 =
1335           container_of(ctrl->handler, struct em28xx_v4l2, ctrl_handler);
1336     struct em28xx *dev = v4l2->dev;
1337     int ret = -EINVAL;
1338 
1339     switch (ctrl->id) {
1340     case V4L2_CID_AUDIO_MUTE:
1341         dev->mute = ctrl->val;
1342         ret = em28xx_audio_analog_set(dev);
1343         break;
1344     case V4L2_CID_AUDIO_VOLUME:
1345         dev->volume = ctrl->val;
1346         ret = em28xx_audio_analog_set(dev);
1347         break;
1348     case V4L2_CID_CONTRAST:
1349         ret = em28xx_write_reg(dev, EM28XX_R20_YGAIN, ctrl->val);
1350         break;
1351     case V4L2_CID_BRIGHTNESS:
1352         ret = em28xx_write_reg(dev, EM28XX_R21_YOFFSET, ctrl->val);
1353         break;
1354     case V4L2_CID_SATURATION:
1355         ret = em28xx_write_reg(dev, EM28XX_R22_UVGAIN, ctrl->val);
1356         break;
1357     case V4L2_CID_BLUE_BALANCE:
1358         ret = em28xx_write_reg(dev, EM28XX_R23_UOFFSET, ctrl->val);
1359         break;
1360     case V4L2_CID_RED_BALANCE:
1361         ret = em28xx_write_reg(dev, EM28XX_R24_VOFFSET, ctrl->val);
1362         break;
1363     case V4L2_CID_SHARPNESS:
1364         ret = em28xx_write_reg(dev, EM28XX_R25_SHARPNESS, ctrl->val);
1365         break;
1366     }
1367 
1368     return (ret < 0) ? ret : 0;
1369 }
1370 
1371 static const struct v4l2_ctrl_ops em28xx_ctrl_ops = {
1372     .s_ctrl = em28xx_s_ctrl,
1373 };
1374 
1375 static void size_to_scale(struct em28xx *dev,
1376               unsigned int width, unsigned int height,
1377             unsigned int *hscale, unsigned int *vscale)
1378 {
1379     unsigned int          maxw = norm_maxw(dev);
1380     unsigned int          maxh = norm_maxh(dev);
1381 
1382     *hscale = (((unsigned long)maxw) << 12) / width - 4096L;
1383     if (*hscale > EM28XX_HVSCALE_MAX)
1384         *hscale = EM28XX_HVSCALE_MAX;
1385 
1386     *vscale = (((unsigned long)maxh) << 12) / height - 4096L;
1387     if (*vscale > EM28XX_HVSCALE_MAX)
1388         *vscale = EM28XX_HVSCALE_MAX;
1389 }
1390 
1391 static void scale_to_size(struct em28xx *dev,
1392               unsigned int hscale, unsigned int vscale,
1393               unsigned int *width, unsigned int *height)
1394 {
1395     unsigned int          maxw = norm_maxw(dev);
1396     unsigned int          maxh = norm_maxh(dev);
1397 
1398     *width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
1399     *height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
1400 
1401     /* Don't let width or height to be zero */
1402     if (*width < 1)
1403         *width = 1;
1404     if (*height < 1)
1405         *height = 1;
1406 }
1407 
1408 /*
1409  * IOCTL vidioc handling
1410  */
1411 
1412 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1413                 struct v4l2_format *f)
1414 {
1415     struct em28xx         *dev = video_drvdata(file);
1416     struct em28xx_v4l2    *v4l2 = dev->v4l2;
1417 
1418     f->fmt.pix.width = v4l2->width;
1419     f->fmt.pix.height = v4l2->height;
1420     f->fmt.pix.pixelformat = v4l2->format->fourcc;
1421     f->fmt.pix.bytesperline = (v4l2->width * v4l2->format->depth + 7) >> 3;
1422     f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * v4l2->height;
1423     f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1424 
1425     /* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
1426     if (v4l2->progressive)
1427         f->fmt.pix.field = V4L2_FIELD_NONE;
1428     else
1429         f->fmt.pix.field = v4l2->interlaced_fieldmode ?
1430                V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
1431     return 0;
1432 }
1433 
1434 static struct em28xx_fmt *format_by_fourcc(unsigned int fourcc)
1435 {
1436     unsigned int i;
1437 
1438     for (i = 0; i < ARRAY_SIZE(format); i++)
1439         if (format[i].fourcc == fourcc)
1440             return &format[i];
1441 
1442     return NULL;
1443 }
1444 
1445 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1446                   struct v4l2_format *f)
1447 {
1448     struct em28xx         *dev   = video_drvdata(file);
1449     struct em28xx_v4l2    *v4l2  = dev->v4l2;
1450     unsigned int          width  = f->fmt.pix.width;
1451     unsigned int          height = f->fmt.pix.height;
1452     unsigned int          maxw   = norm_maxw(dev);
1453     unsigned int          maxh   = norm_maxh(dev);
1454     unsigned int          hscale, vscale;
1455     struct em28xx_fmt     *fmt;
1456 
1457     fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1458     if (!fmt) {
1459         fmt = &format[0];
1460         em28xx_videodbg("Fourcc format (%08x) invalid. Using default (%08x).\n",
1461                 f->fmt.pix.pixelformat, fmt->fourcc);
1462     }
1463 
1464     if (dev->board.is_em2800) {
1465         /* the em2800 can only scale down to 50% */
1466         height = height > (3 * maxh / 4) ? maxh : maxh / 2;
1467         width = width > (3 * maxw / 4) ? maxw : maxw / 2;
1468         /*
1469          * MaxPacketSize for em2800 is too small to capture at full
1470          * resolution use half of maxw as the scaler can only scale
1471          * to 50%
1472          */
1473         if (width == maxw && height == maxh)
1474             width /= 2;
1475     } else {
1476         /*
1477          * width must even because of the YUYV format
1478          * height must be even because of interlacing
1479          */
1480         v4l_bound_align_image(&width, 48, maxw, 1, &height, 32, maxh,
1481                       1, 0);
1482     }
1483     /* Avoid division by zero at size_to_scale */
1484     if (width < 1)
1485         width = 1;
1486     if (height < 1)
1487         height = 1;
1488 
1489     size_to_scale(dev, width, height, &hscale, &vscale);
1490     scale_to_size(dev, hscale, vscale, &width, &height);
1491 
1492     f->fmt.pix.width = width;
1493     f->fmt.pix.height = height;
1494     f->fmt.pix.pixelformat = fmt->fourcc;
1495     f->fmt.pix.bytesperline = (width * fmt->depth + 7) >> 3;
1496     f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * height;
1497     f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1498     if (v4l2->progressive)
1499         f->fmt.pix.field = V4L2_FIELD_NONE;
1500     else
1501         f->fmt.pix.field = v4l2->interlaced_fieldmode ?
1502                V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
1503 
1504     return 0;
1505 }
1506 
1507 static int em28xx_set_video_format(struct em28xx *dev, unsigned int fourcc,
1508                    unsigned int width, unsigned int height)
1509 {
1510     struct em28xx_fmt     *fmt;
1511     struct em28xx_v4l2    *v4l2 = dev->v4l2;
1512 
1513     fmt = format_by_fourcc(fourcc);
1514     if (!fmt)
1515         return -EINVAL;
1516 
1517     v4l2->format = fmt;
1518     v4l2->width  = width;
1519     v4l2->height = height;
1520 
1521     /* set new image size */
1522     size_to_scale(dev, v4l2->width, v4l2->height,
1523               &v4l2->hscale, &v4l2->vscale);
1524 
1525     em28xx_resolution_set(dev);
1526 
1527     return 0;
1528 }
1529 
1530 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1531                 struct v4l2_format *f)
1532 {
1533     struct em28xx *dev = video_drvdata(file);
1534     struct em28xx_v4l2 *v4l2 = dev->v4l2;
1535 
1536     if (vb2_is_busy(&v4l2->vb_vidq))
1537         return -EBUSY;
1538 
1539     vidioc_try_fmt_vid_cap(file, priv, f);
1540 
1541     return em28xx_set_video_format(dev, f->fmt.pix.pixelformat,
1542                 f->fmt.pix.width, f->fmt.pix.height);
1543 }
1544 
1545 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
1546 {
1547     struct em28xx *dev = video_drvdata(file);
1548 
1549     *norm = dev->v4l2->norm;
1550 
1551     return 0;
1552 }
1553 
1554 static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *norm)
1555 {
1556     struct em28xx *dev = video_drvdata(file);
1557 
1558     v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, video, querystd, norm);
1559 
1560     return 0;
1561 }
1562 
1563 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
1564 {
1565     struct em28xx      *dev  = video_drvdata(file);
1566     struct em28xx_v4l2 *v4l2 = dev->v4l2;
1567     struct v4l2_format f;
1568 
1569     if (norm == v4l2->norm)
1570         return 0;
1571 
1572     if (v4l2->streaming_users > 0)
1573         return -EBUSY;
1574 
1575     v4l2->norm = norm;
1576 
1577     /* Adjusts width/height, if needed */
1578     f.fmt.pix.width = 720;
1579     f.fmt.pix.height = (norm & V4L2_STD_525_60) ? 480 : 576;
1580     vidioc_try_fmt_vid_cap(file, priv, &f);
1581 
1582     /* set new image size */
1583     v4l2->width = f.fmt.pix.width;
1584     v4l2->height = f.fmt.pix.height;
1585     size_to_scale(dev, v4l2->width, v4l2->height,
1586               &v4l2->hscale, &v4l2->vscale);
1587 
1588     em28xx_resolution_set(dev);
1589     v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_std, v4l2->norm);
1590 
1591     return 0;
1592 }
1593 
1594 static int vidioc_g_parm(struct file *file, void *priv,
1595              struct v4l2_streamparm *p)
1596 {
1597     struct v4l2_subdev_frame_interval ival = { 0 };
1598     struct em28xx      *dev  = video_drvdata(file);
1599     struct em28xx_v4l2 *v4l2 = dev->v4l2;
1600     int rc = 0;
1601 
1602     if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
1603         p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
1604         return -EINVAL;
1605 
1606     p->parm.capture.readbuffers = EM28XX_MIN_BUF;
1607     p->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
1608     if (dev->is_webcam) {
1609         rc = v4l2_device_call_until_err(&v4l2->v4l2_dev, 0,
1610                         video, g_frame_interval, &ival);
1611         if (!rc)
1612             p->parm.capture.timeperframe = ival.interval;
1613     } else {
1614         v4l2_video_std_frame_period(v4l2->norm,
1615                         &p->parm.capture.timeperframe);
1616     }
1617 
1618     return rc;
1619 }
1620 
1621 static int vidioc_s_parm(struct file *file, void *priv,
1622              struct v4l2_streamparm *p)
1623 {
1624     struct em28xx *dev = video_drvdata(file);
1625     struct v4l2_subdev_frame_interval ival = {
1626         0,
1627         p->parm.capture.timeperframe
1628     };
1629     int rc = 0;
1630 
1631     if (!dev->is_webcam)
1632         return -ENOTTY;
1633 
1634     if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
1635         p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
1636         return -EINVAL;
1637 
1638     memset(&p->parm, 0, sizeof(p->parm));
1639     p->parm.capture.readbuffers = EM28XX_MIN_BUF;
1640     p->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
1641     rc = v4l2_device_call_until_err(&dev->v4l2->v4l2_dev, 0,
1642                     video, s_frame_interval, &ival);
1643     if (!rc)
1644         p->parm.capture.timeperframe = ival.interval;
1645     return rc;
1646 }
1647 
1648 static int vidioc_enum_input(struct file *file, void *priv,
1649                  struct v4l2_input *i)
1650 {
1651     struct em28xx *dev = video_drvdata(file);
1652     unsigned int       n;
1653     int j;
1654 
1655     n = i->index;
1656     if (n >= MAX_EM28XX_INPUT)
1657         return -EINVAL;
1658     if (!INPUT(n)->type)
1659         return -EINVAL;
1660 
1661     i->type = V4L2_INPUT_TYPE_CAMERA;
1662 
1663     strscpy(i->name, iname[INPUT(n)->type], sizeof(i->name));
1664 
1665     if (INPUT(n)->type == EM28XX_VMUX_TELEVISION)
1666         i->type = V4L2_INPUT_TYPE_TUNER;
1667 
1668     i->std = dev->v4l2->vdev.tvnorms;
1669     /* webcams do not have the STD API */
1670     if (dev->is_webcam)
1671         i->capabilities = 0;
1672 
1673     /* Dynamically generates an audioset bitmask */
1674     i->audioset = 0;
1675     for (j = 0; j < MAX_EM28XX_INPUT; j++)
1676         if (dev->amux_map[j] != EM28XX_AMUX_UNUSED)
1677             i->audioset |= 1 << j;
1678 
1679     return 0;
1680 }
1681 
1682 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1683 {
1684     struct em28xx *dev = video_drvdata(file);
1685 
1686     *i = dev->ctl_input;
1687 
1688     return 0;
1689 }
1690 
1691 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1692 {
1693     struct em28xx *dev = video_drvdata(file);
1694 
1695     if (i >= MAX_EM28XX_INPUT)
1696         return -EINVAL;
1697     if (!INPUT(i)->type)
1698         return -EINVAL;
1699 
1700     video_mux(dev, i);
1701     return 0;
1702 }
1703 
1704 static int em28xx_fill_audio_input(struct em28xx *dev,
1705                    const char *s,
1706                    struct v4l2_audio *a,
1707                    unsigned int index)
1708 {
1709     unsigned int idx = dev->amux_map[index];
1710 
1711     /*
1712      * With msp3400, almost all mappings use the default (amux = 0).
1713      * The only one may use a different value is WinTV USB2, where it
1714      * can also be SCART1 input.
1715      * As it is very doubtful that we would see new boards with msp3400,
1716      * let's just reuse the existing switch.
1717      */
1718     if (dev->has_msp34xx && idx != EM28XX_AMUX_UNUSED)
1719         idx = EM28XX_AMUX_LINE_IN;
1720 
1721     switch (idx) {
1722     case EM28XX_AMUX_VIDEO:
1723         strscpy(a->name, "Television", sizeof(a->name));
1724         break;
1725     case EM28XX_AMUX_LINE_IN:
1726         strscpy(a->name, "Line In", sizeof(a->name));
1727         break;
1728     case EM28XX_AMUX_VIDEO2:
1729         strscpy(a->name, "Television alt", sizeof(a->name));
1730         break;
1731     case EM28XX_AMUX_PHONE:
1732         strscpy(a->name, "Phone", sizeof(a->name));
1733         break;
1734     case EM28XX_AMUX_MIC:
1735         strscpy(a->name, "Mic", sizeof(a->name));
1736         break;
1737     case EM28XX_AMUX_CD:
1738         strscpy(a->name, "CD", sizeof(a->name));
1739         break;
1740     case EM28XX_AMUX_AUX:
1741         strscpy(a->name, "Aux", sizeof(a->name));
1742         break;
1743     case EM28XX_AMUX_PCM_OUT:
1744         strscpy(a->name, "PCM", sizeof(a->name));
1745         break;
1746     case EM28XX_AMUX_UNUSED:
1747     default:
1748         return -EINVAL;
1749     }
1750     a->index = index;
1751     a->capability = V4L2_AUDCAP_STEREO;
1752 
1753     em28xx_videodbg("%s: audio input index %d is '%s'\n",
1754             s, a->index, a->name);
1755 
1756     return 0;
1757 }
1758 
1759 static int vidioc_enumaudio(struct file *file, void *fh, struct v4l2_audio *a)
1760 {
1761     struct em28xx *dev = video_drvdata(file);
1762 
1763     if (a->index >= MAX_EM28XX_INPUT)
1764         return -EINVAL;
1765 
1766     return em28xx_fill_audio_input(dev, __func__, a, a->index);
1767 }
1768 
1769 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1770 {
1771     struct em28xx *dev = video_drvdata(file);
1772     int i;
1773 
1774     for (i = 0; i < MAX_EM28XX_INPUT; i++)
1775         if (dev->ctl_ainput == dev->amux_map[i])
1776             return em28xx_fill_audio_input(dev, __func__, a, i);
1777 
1778     /* Should never happen! */
1779     return -EINVAL;
1780 }
1781 
1782 static int vidioc_s_audio(struct file *file, void *priv,
1783               const struct v4l2_audio *a)
1784 {
1785     struct em28xx *dev = video_drvdata(file);
1786     int idx, i;
1787 
1788     if (a->index >= MAX_EM28XX_INPUT)
1789         return -EINVAL;
1790 
1791     idx = dev->amux_map[a->index];
1792 
1793     if (idx == EM28XX_AMUX_UNUSED)
1794         return -EINVAL;
1795 
1796     dev->ctl_ainput = idx;
1797 
1798     /*
1799      * FIXME: This is wrong, as different inputs at em28xx_cards
1800      * may have different audio outputs. So, the right thing
1801      * to do is to implement VIDIOC_G_AUDOUT/VIDIOC_S_AUDOUT.
1802      * With the current board definitions, this would work fine,
1803      * as, currently, all boards fit.
1804      */
1805     for (i = 0; i < MAX_EM28XX_INPUT; i++)
1806         if (idx == dev->amux_map[i])
1807             break;
1808     if (i == MAX_EM28XX_INPUT)
1809         return -EINVAL;
1810 
1811     dev->ctl_aoutput = INPUT(i)->aout;
1812 
1813     if (!dev->ctl_aoutput)
1814         dev->ctl_aoutput = EM28XX_AOUT_MASTER;
1815 
1816     em28xx_videodbg("%s: set audio input to %d\n", __func__,
1817             dev->ctl_ainput);
1818 
1819     return 0;
1820 }
1821 
1822 static int vidioc_g_tuner(struct file *file, void *priv,
1823               struct v4l2_tuner *t)
1824 {
1825     struct em28xx *dev = video_drvdata(file);
1826 
1827     if (t->index != 0)
1828         return -EINVAL;
1829 
1830     strscpy(t->name, "Tuner", sizeof(t->name));
1831 
1832     v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, g_tuner, t);
1833     return 0;
1834 }
1835 
1836 static int vidioc_s_tuner(struct file *file, void *priv,
1837               const struct v4l2_tuner *t)
1838 {
1839     struct em28xx *dev = video_drvdata(file);
1840 
1841     if (t->index != 0)
1842         return -EINVAL;
1843 
1844     v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, s_tuner, t);
1845     return 0;
1846 }
1847 
1848 static int vidioc_g_frequency(struct file *file, void *priv,
1849                   struct v4l2_frequency *f)
1850 {
1851     struct em28xx         *dev = video_drvdata(file);
1852     struct em28xx_v4l2    *v4l2 = dev->v4l2;
1853 
1854     if (f->tuner != 0)
1855         return -EINVAL;
1856 
1857     f->frequency = v4l2->frequency;
1858     return 0;
1859 }
1860 
1861 static int vidioc_s_frequency(struct file *file, void *priv,
1862                   const struct v4l2_frequency *f)
1863 {
1864     struct v4l2_frequency  new_freq = *f;
1865     struct em28xx             *dev  = video_drvdata(file);
1866     struct em28xx_v4l2        *v4l2 = dev->v4l2;
1867 
1868     if (f->tuner != 0)
1869         return -EINVAL;
1870 
1871     v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, s_frequency, f);
1872     v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, g_frequency, &new_freq);
1873     v4l2->frequency = new_freq.frequency;
1874 
1875     return 0;
1876 }
1877 
1878 #ifdef CONFIG_VIDEO_ADV_DEBUG
1879 static int vidioc_g_chip_info(struct file *file, void *priv,
1880                   struct v4l2_dbg_chip_info *chip)
1881 {
1882     struct em28xx *dev = video_drvdata(file);
1883 
1884     if (chip->match.addr > 1)
1885         return -EINVAL;
1886     if (chip->match.addr == 1)
1887         strscpy(chip->name, "ac97", sizeof(chip->name));
1888     else
1889         strscpy(chip->name,
1890             dev->v4l2->v4l2_dev.name, sizeof(chip->name));
1891     return 0;
1892 }
1893 
1894 static int em28xx_reg_len(int reg)
1895 {
1896     switch (reg) {
1897     case EM28XX_R40_AC97LSB:
1898     case EM28XX_R30_HSCALELOW:
1899     case EM28XX_R32_VSCALELOW:
1900         return 2;
1901     default:
1902         return 1;
1903     }
1904 }
1905 
1906 static int vidioc_g_register(struct file *file, void *priv,
1907                  struct v4l2_dbg_register *reg)
1908 {
1909     struct em28xx *dev = video_drvdata(file);
1910     int ret;
1911 
1912     if (reg->match.addr > 1)
1913         return -EINVAL;
1914     if (reg->match.addr) {
1915         ret = em28xx_read_ac97(dev, reg->reg);
1916         if (ret < 0)
1917             return ret;
1918 
1919         reg->val = ret;
1920         reg->size = 1;
1921         return 0;
1922     }
1923 
1924     /* Match host */
1925     reg->size = em28xx_reg_len(reg->reg);
1926     if (reg->size == 1) {
1927         ret = em28xx_read_reg(dev, reg->reg);
1928 
1929         if (ret < 0)
1930             return ret;
1931 
1932         reg->val = ret;
1933     } else {
1934         __le16 val = 0;
1935 
1936         ret = dev->em28xx_read_reg_req_len(dev, USB_REQ_GET_STATUS,
1937                            reg->reg, (char *)&val, 2);
1938         if (ret < 0)
1939             return ret;
1940 
1941         reg->val = le16_to_cpu(val);
1942     }
1943 
1944     return 0;
1945 }
1946 
1947 static int vidioc_s_register(struct file *file, void *priv,
1948                  const struct v4l2_dbg_register *reg)
1949 {
1950     struct em28xx *dev = video_drvdata(file);
1951     __le16 buf;
1952 
1953     if (reg->match.addr > 1)
1954         return -EINVAL;
1955     if (reg->match.addr)
1956         return em28xx_write_ac97(dev, reg->reg, reg->val);
1957 
1958     /* Match host */
1959     buf = cpu_to_le16(reg->val);
1960 
1961     return em28xx_write_regs(dev, reg->reg, (char *)&buf,
1962                    em28xx_reg_len(reg->reg));
1963 }
1964 #endif
1965 
1966 static int vidioc_querycap(struct file *file, void  *priv,
1967                struct v4l2_capability *cap)
1968 {
1969     struct em28xx         *dev  = video_drvdata(file);
1970     struct em28xx_v4l2    *v4l2 = dev->v4l2;
1971     struct usb_device *udev = interface_to_usbdev(dev->intf);
1972 
1973     strscpy(cap->driver, "em28xx", sizeof(cap->driver));
1974     strscpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1975     usb_make_path(udev, cap->bus_info, sizeof(cap->bus_info));
1976 
1977     cap->capabilities = V4L2_CAP_DEVICE_CAPS | V4L2_CAP_READWRITE |
1978                 V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
1979     if (dev->int_audio_type != EM28XX_INT_AUDIO_NONE)
1980         cap->capabilities |= V4L2_CAP_AUDIO;
1981     if (dev->tuner_type != TUNER_ABSENT)
1982         cap->capabilities |= V4L2_CAP_TUNER;
1983     if (video_is_registered(&v4l2->vbi_dev))
1984         cap->capabilities |= V4L2_CAP_VBI_CAPTURE;
1985     if (video_is_registered(&v4l2->radio_dev))
1986         cap->capabilities |= V4L2_CAP_RADIO;
1987     return 0;
1988 }
1989 
1990 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1991                    struct v4l2_fmtdesc *f)
1992 {
1993     if (unlikely(f->index >= ARRAY_SIZE(format)))
1994         return -EINVAL;
1995 
1996     f->pixelformat = format[f->index].fourcc;
1997 
1998     return 0;
1999 }
2000 
2001 static int vidioc_enum_framesizes(struct file *file, void *priv,
2002                   struct v4l2_frmsizeenum *fsize)
2003 {
2004     struct em28xx         *dev = video_drvdata(file);
2005     struct em28xx_fmt     *fmt;
2006     unsigned int          maxw = norm_maxw(dev);
2007     unsigned int          maxh = norm_maxh(dev);
2008 
2009     fmt = format_by_fourcc(fsize->pixel_format);
2010     if (!fmt) {
2011         em28xx_videodbg("Fourcc format (%08x) invalid.\n",
2012                 fsize->pixel_format);
2013         return -EINVAL;
2014     }
2015 
2016     if (dev->board.is_em2800) {
2017         if (fsize->index > 1)
2018             return -EINVAL;
2019         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
2020         fsize->discrete.width = maxw / (1 + fsize->index);
2021         fsize->discrete.height = maxh / (1 + fsize->index);
2022         return 0;
2023     }
2024 
2025     if (fsize->index != 0)
2026         return -EINVAL;
2027 
2028     /* Report a continuous range */
2029     fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
2030     scale_to_size(dev, EM28XX_HVSCALE_MAX, EM28XX_HVSCALE_MAX,
2031               &fsize->stepwise.min_width, &fsize->stepwise.min_height);
2032     if (fsize->stepwise.min_width < 48)
2033         fsize->stepwise.min_width = 48;
2034     if (fsize->stepwise.min_height < 38)
2035         fsize->stepwise.min_height = 38;
2036     fsize->stepwise.max_width = maxw;
2037     fsize->stepwise.max_height = maxh;
2038     fsize->stepwise.step_width = 1;
2039     fsize->stepwise.step_height = 1;
2040     return 0;
2041 }
2042 
2043 /* RAW VBI ioctls */
2044 
2045 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
2046                 struct v4l2_format *format)
2047 {
2048     struct em28xx         *dev  = video_drvdata(file);
2049     struct em28xx_v4l2    *v4l2 = dev->v4l2;
2050 
2051     format->fmt.vbi.samples_per_line = v4l2->vbi_width;
2052     format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
2053     format->fmt.vbi.offset = 0;
2054     format->fmt.vbi.flags = 0;
2055     format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
2056     format->fmt.vbi.count[0] = v4l2->vbi_height;
2057     format->fmt.vbi.count[1] = v4l2->vbi_height;
2058     memset(format->fmt.vbi.reserved, 0, sizeof(format->fmt.vbi.reserved));
2059 
2060     /* Varies by video standard (NTSC, PAL, etc.) */
2061     if (v4l2->norm & V4L2_STD_525_60) {
2062         /* NTSC */
2063         format->fmt.vbi.start[0] = 10;
2064         format->fmt.vbi.start[1] = 273;
2065     } else if (v4l2->norm & V4L2_STD_625_50) {
2066         /* PAL */
2067         format->fmt.vbi.start[0] = 6;
2068         format->fmt.vbi.start[1] = 318;
2069     }
2070 
2071     return 0;
2072 }
2073 
2074 /*
2075  * RADIO ESPECIFIC IOCTLS
2076  */
2077 
2078 static int radio_g_tuner(struct file *file, void *priv,
2079              struct v4l2_tuner *t)
2080 {
2081     struct em28xx *dev = video_drvdata(file);
2082 
2083     if (unlikely(t->index > 0))
2084         return -EINVAL;
2085 
2086     strscpy(t->name, "Radio", sizeof(t->name));
2087 
2088     v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, g_tuner, t);
2089 
2090     return 0;
2091 }
2092 
2093 static int radio_s_tuner(struct file *file, void *priv,
2094              const struct v4l2_tuner *t)
2095 {
2096     struct em28xx *dev = video_drvdata(file);
2097 
2098     if (t->index != 0)
2099         return -EINVAL;
2100 
2101     v4l2_device_call_all(&dev->v4l2->v4l2_dev, 0, tuner, s_tuner, t);
2102 
2103     return 0;
2104 }
2105 
2106 /*
2107  * em28xx_free_v4l2() - Free struct em28xx_v4l2
2108  *
2109  * @ref: struct kref for struct em28xx_v4l2
2110  *
2111  * Called when all users of struct em28xx_v4l2 are gone
2112  */
2113 static void em28xx_free_v4l2(struct kref *ref)
2114 {
2115     struct em28xx_v4l2 *v4l2 = container_of(ref, struct em28xx_v4l2, ref);
2116 
2117     v4l2->dev->v4l2 = NULL;
2118     kfree(v4l2);
2119 }
2120 
2121 /*
2122  * em28xx_v4l2_open()
2123  * inits the device and starts isoc transfer
2124  */
2125 static int em28xx_v4l2_open(struct file *filp)
2126 {
2127     struct video_device *vdev = video_devdata(filp);
2128     struct em28xx *dev = video_drvdata(filp);
2129     struct em28xx_v4l2 *v4l2 = dev->v4l2;
2130     enum v4l2_buf_type fh_type = 0;
2131     int ret;
2132 
2133     switch (vdev->vfl_type) {
2134     case VFL_TYPE_VIDEO:
2135         fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2136         break;
2137     case VFL_TYPE_VBI:
2138         fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
2139         break;
2140     case VFL_TYPE_RADIO:
2141         break;
2142     default:
2143         return -EINVAL;
2144     }
2145 
2146     em28xx_videodbg("open dev=%s type=%s users=%d\n",
2147             video_device_node_name(vdev), v4l2_type_names[fh_type],
2148             v4l2->users);
2149 
2150     if (mutex_lock_interruptible(&dev->lock))
2151         return -ERESTARTSYS;
2152 
2153     ret = v4l2_fh_open(filp);
2154     if (ret) {
2155         dev_err(&dev->intf->dev,
2156             "%s: v4l2_fh_open() returned error %d\n",
2157                __func__, ret);
2158         mutex_unlock(&dev->lock);
2159         return ret;
2160     }
2161 
2162     if (v4l2->users == 0) {
2163         em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
2164 
2165         if (vdev->vfl_type != VFL_TYPE_RADIO)
2166             em28xx_resolution_set(dev);
2167 
2168         /*
2169          * Needed, since GPIO might have disabled power
2170          * of some i2c devices
2171          */
2172         em28xx_wake_i2c(dev);
2173     }
2174 
2175     if (vdev->vfl_type == VFL_TYPE_RADIO) {
2176         em28xx_videodbg("video_open: setting radio device\n");
2177         v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, s_radio);
2178     }
2179 
2180     kref_get(&dev->ref);
2181     kref_get(&v4l2->ref);
2182     v4l2->users++;
2183 
2184     mutex_unlock(&dev->lock);
2185 
2186     return 0;
2187 }
2188 
2189 /*
2190  * em28xx_v4l2_fini()
2191  * unregisters the v4l2,i2c and usb devices
2192  * called when the device gets disconnected or at module unload
2193  */
2194 static int em28xx_v4l2_fini(struct em28xx *dev)
2195 {
2196     struct em28xx_v4l2 *v4l2 = dev->v4l2;
2197 
2198     if (dev->is_audio_only) {
2199         /* Shouldn't initialize IR for this interface */
2200         return 0;
2201     }
2202 
2203     if (!dev->has_video) {
2204         /* This device does not support the v4l2 extension */
2205         return 0;
2206     }
2207 
2208     if (!v4l2)
2209         return 0;
2210 
2211     dev_info(&dev->intf->dev, "Closing video extension\n");
2212 
2213     mutex_lock(&dev->lock);
2214 
2215     v4l2_device_disconnect(&v4l2->v4l2_dev);
2216 
2217     em28xx_uninit_usb_xfer(dev, EM28XX_ANALOG_MODE);
2218 
2219     em28xx_v4l2_media_release(dev);
2220 
2221     if (video_is_registered(&v4l2->radio_dev)) {
2222         dev_info(&dev->intf->dev, "V4L2 device %s deregistered\n",
2223              video_device_node_name(&v4l2->radio_dev));
2224         video_unregister_device(&v4l2->radio_dev);
2225     }
2226     if (video_is_registered(&v4l2->vbi_dev)) {
2227         dev_info(&dev->intf->dev, "V4L2 device %s deregistered\n",
2228              video_device_node_name(&v4l2->vbi_dev));
2229         video_unregister_device(&v4l2->vbi_dev);
2230     }
2231     if (video_is_registered(&v4l2->vdev)) {
2232         dev_info(&dev->intf->dev, "V4L2 device %s deregistered\n",
2233              video_device_node_name(&v4l2->vdev));
2234         video_unregister_device(&v4l2->vdev);
2235     }
2236 
2237     v4l2_ctrl_handler_free(&v4l2->ctrl_handler);
2238     v4l2_device_unregister(&v4l2->v4l2_dev);
2239 
2240     kref_put(&v4l2->ref, em28xx_free_v4l2);
2241 
2242     mutex_unlock(&dev->lock);
2243 
2244     kref_put(&dev->ref, em28xx_free_device);
2245 
2246     return 0;
2247 }
2248 
2249 static int em28xx_v4l2_suspend(struct em28xx *dev)
2250 {
2251     if (dev->is_audio_only)
2252         return 0;
2253 
2254     if (!dev->has_video)
2255         return 0;
2256 
2257     dev_info(&dev->intf->dev, "Suspending video extension\n");
2258     em28xx_stop_urbs(dev);
2259     return 0;
2260 }
2261 
2262 static int em28xx_v4l2_resume(struct em28xx *dev)
2263 {
2264     if (dev->is_audio_only)
2265         return 0;
2266 
2267     if (!dev->has_video)
2268         return 0;
2269 
2270     dev_info(&dev->intf->dev, "Resuming video extension\n");
2271     /* what do we do here */
2272     return 0;
2273 }
2274 
2275 /*
2276  * em28xx_v4l2_close()
2277  * stops streaming and deallocates all resources allocated by the v4l2
2278  * calls and ioctls
2279  */
2280 static int em28xx_v4l2_close(struct file *filp)
2281 {
2282     struct em28xx         *dev  = video_drvdata(filp);
2283     struct em28xx_v4l2    *v4l2 = dev->v4l2;
2284     struct usb_device *udev = interface_to_usbdev(dev->intf);
2285     int              err;
2286 
2287     em28xx_videodbg("users=%d\n", v4l2->users);
2288 
2289     vb2_fop_release(filp);
2290     mutex_lock(&dev->lock);
2291 
2292     if (v4l2->users == 1) {
2293         /* No sense to try to write to the device */
2294         if (dev->disconnected)
2295             goto exit;
2296 
2297         /* Save some power by putting tuner to sleep */
2298         v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, standby);
2299 
2300         /* do this before setting alternate! */
2301         em28xx_set_mode(dev, EM28XX_SUSPEND);
2302 
2303         /* set alternate 0 */
2304         dev->alt = 0;
2305         em28xx_videodbg("setting alternate 0\n");
2306         err = usb_set_interface(udev, 0, 0);
2307         if (err < 0) {
2308             dev_err(&dev->intf->dev,
2309                 "cannot change alternate number to 0 (error=%i)\n",
2310                 err);
2311         }
2312     }
2313 
2314 exit:
2315     v4l2->users--;
2316     kref_put(&v4l2->ref, em28xx_free_v4l2);
2317     mutex_unlock(&dev->lock);
2318     kref_put(&dev->ref, em28xx_free_device);
2319 
2320     return 0;
2321 }
2322 
2323 static const struct v4l2_file_operations em28xx_v4l_fops = {
2324     .owner         = THIS_MODULE,
2325     .open          = em28xx_v4l2_open,
2326     .release       = em28xx_v4l2_close,
2327     .read          = vb2_fop_read,
2328     .poll          = vb2_fop_poll,
2329     .mmap          = vb2_fop_mmap,
2330     .unlocked_ioctl = video_ioctl2,
2331 };
2332 
2333 static const struct v4l2_ioctl_ops video_ioctl_ops = {
2334     .vidioc_querycap            = vidioc_querycap,
2335     .vidioc_enum_fmt_vid_cap    = vidioc_enum_fmt_vid_cap,
2336     .vidioc_g_fmt_vid_cap       = vidioc_g_fmt_vid_cap,
2337     .vidioc_try_fmt_vid_cap     = vidioc_try_fmt_vid_cap,
2338     .vidioc_s_fmt_vid_cap       = vidioc_s_fmt_vid_cap,
2339     .vidioc_g_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
2340     .vidioc_try_fmt_vbi_cap     = vidioc_g_fmt_vbi_cap,
2341     .vidioc_s_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
2342     .vidioc_enum_framesizes     = vidioc_enum_framesizes,
2343     .vidioc_enumaudio           = vidioc_enumaudio,
2344     .vidioc_g_audio             = vidioc_g_audio,
2345     .vidioc_s_audio             = vidioc_s_audio,
2346 
2347     .vidioc_reqbufs             = vb2_ioctl_reqbufs,
2348     .vidioc_create_bufs         = vb2_ioctl_create_bufs,
2349     .vidioc_prepare_buf         = vb2_ioctl_prepare_buf,
2350     .vidioc_querybuf            = vb2_ioctl_querybuf,
2351     .vidioc_qbuf                = vb2_ioctl_qbuf,
2352     .vidioc_dqbuf               = vb2_ioctl_dqbuf,
2353 
2354     .vidioc_g_std               = vidioc_g_std,
2355     .vidioc_querystd            = vidioc_querystd,
2356     .vidioc_s_std               = vidioc_s_std,
2357     .vidioc_g_parm          = vidioc_g_parm,
2358     .vidioc_s_parm          = vidioc_s_parm,
2359     .vidioc_enum_input          = vidioc_enum_input,
2360     .vidioc_g_input             = vidioc_g_input,
2361     .vidioc_s_input             = vidioc_s_input,
2362     .vidioc_streamon            = vb2_ioctl_streamon,
2363     .vidioc_streamoff           = vb2_ioctl_streamoff,
2364     .vidioc_g_tuner             = vidioc_g_tuner,
2365     .vidioc_s_tuner             = vidioc_s_tuner,
2366     .vidioc_g_frequency         = vidioc_g_frequency,
2367     .vidioc_s_frequency         = vidioc_s_frequency,
2368     .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2369     .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2370 #ifdef CONFIG_VIDEO_ADV_DEBUG
2371     .vidioc_g_chip_info         = vidioc_g_chip_info,
2372     .vidioc_g_register          = vidioc_g_register,
2373     .vidioc_s_register          = vidioc_s_register,
2374 #endif
2375 };
2376 
2377 static const struct video_device em28xx_video_template = {
2378     .fops       = &em28xx_v4l_fops,
2379     .ioctl_ops  = &video_ioctl_ops,
2380     .release    = video_device_release_empty,
2381     .tvnorms    = V4L2_STD_ALL,
2382 };
2383 
2384 static const struct v4l2_file_operations radio_fops = {
2385     .owner         = THIS_MODULE,
2386     .open          = em28xx_v4l2_open,
2387     .release       = em28xx_v4l2_close,
2388     .unlocked_ioctl = video_ioctl2,
2389 };
2390 
2391 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2392     .vidioc_querycap      = vidioc_querycap,
2393     .vidioc_g_tuner       = radio_g_tuner,
2394     .vidioc_s_tuner       = radio_s_tuner,
2395     .vidioc_g_frequency   = vidioc_g_frequency,
2396     .vidioc_s_frequency   = vidioc_s_frequency,
2397     .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2398     .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2399 #ifdef CONFIG_VIDEO_ADV_DEBUG
2400     .vidioc_g_chip_info   = vidioc_g_chip_info,
2401     .vidioc_g_register    = vidioc_g_register,
2402     .vidioc_s_register    = vidioc_s_register,
2403 #endif
2404 };
2405 
2406 static struct video_device em28xx_radio_template = {
2407     .fops       = &radio_fops,
2408     .ioctl_ops  = &radio_ioctl_ops,
2409     .release    = video_device_release_empty,
2410 };
2411 
2412 /* I2C possible address to saa7115, tvp5150, msp3400, tvaudio */
2413 static unsigned short saa711x_addrs[] = {
2414     0x4a >> 1, 0x48 >> 1,   /* SAA7111, SAA7111A and SAA7113 */
2415     0x42 >> 1, 0x40 >> 1,   /* SAA7114, SAA7115 and SAA7118 */
2416     I2C_CLIENT_END };
2417 
2418 static unsigned short tvp5150_addrs[] = {
2419     0xb8 >> 1,
2420     0xba >> 1,
2421     I2C_CLIENT_END
2422 };
2423 
2424 static unsigned short msp3400_addrs[] = {
2425     0x80 >> 1,
2426     0x88 >> 1,
2427     I2C_CLIENT_END
2428 };
2429 
2430 /******************************** usb interface ******************************/
2431 
2432 static void em28xx_vdev_init(struct em28xx *dev,
2433                  struct video_device *vfd,
2434                  const struct video_device *template,
2435                  const char *type_name)
2436 {
2437     *vfd        = *template;
2438     vfd->v4l2_dev   = &dev->v4l2->v4l2_dev;
2439     vfd->lock   = &dev->lock;
2440     if (dev->is_webcam)
2441         vfd->tvnorms = 0;
2442 
2443     snprintf(vfd->name, sizeof(vfd->name), "%s %s",
2444          dev_name(&dev->intf->dev), type_name);
2445 
2446     video_set_drvdata(vfd, dev);
2447 }
2448 
2449 static void em28xx_tuner_setup(struct em28xx *dev, unsigned short tuner_addr)
2450 {
2451     struct em28xx_v4l2      *v4l2 = dev->v4l2;
2452     struct v4l2_device      *v4l2_dev = &v4l2->v4l2_dev;
2453     struct tuner_setup      tun_setup;
2454     struct v4l2_frequency   f;
2455 
2456     memset(&tun_setup, 0, sizeof(tun_setup));
2457 
2458     tun_setup.mode_mask = T_ANALOG_TV | T_RADIO;
2459     tun_setup.tuner_callback = em28xx_tuner_callback;
2460 
2461     if (dev->board.radio.type) {
2462         tun_setup.type = dev->board.radio.type;
2463         tun_setup.addr = dev->board.radio_addr;
2464 
2465         v4l2_device_call_all(v4l2_dev,
2466                      0, tuner, s_type_addr, &tun_setup);
2467     }
2468 
2469     if (dev->tuner_type != TUNER_ABSENT && dev->tuner_type) {
2470         tun_setup.type   = dev->tuner_type;
2471         tun_setup.addr   = tuner_addr;
2472 
2473         v4l2_device_call_all(v4l2_dev,
2474                      0, tuner, s_type_addr, &tun_setup);
2475     }
2476 
2477     if (dev->board.tda9887_conf) {
2478         struct v4l2_priv_tun_config tda9887_cfg;
2479 
2480         tda9887_cfg.tuner = TUNER_TDA9887;
2481         tda9887_cfg.priv = &dev->board.tda9887_conf;
2482 
2483         v4l2_device_call_all(v4l2_dev,
2484                      0, tuner, s_config, &tda9887_cfg);
2485     }
2486 
2487     if (dev->tuner_type == TUNER_XC2028) {
2488         struct v4l2_priv_tun_config  xc2028_cfg;
2489         struct xc2028_ctrl           ctl;
2490 
2491         memset(&xc2028_cfg, 0, sizeof(xc2028_cfg));
2492         memset(&ctl, 0, sizeof(ctl));
2493 
2494         em28xx_setup_xc3028(dev, &ctl);
2495 
2496         xc2028_cfg.tuner = TUNER_XC2028;
2497         xc2028_cfg.priv  = &ctl;
2498 
2499         v4l2_device_call_all(v4l2_dev, 0, tuner, s_config, &xc2028_cfg);
2500     }
2501 
2502     /* configure tuner */
2503     f.tuner = 0;
2504     f.type = V4L2_TUNER_ANALOG_TV;
2505     f.frequency = 9076;     /* just a magic number */
2506     v4l2->frequency = f.frequency;
2507     v4l2_device_call_all(v4l2_dev, 0, tuner, s_frequency, &f);
2508 }
2509 
2510 static int em28xx_v4l2_init(struct em28xx *dev)
2511 {
2512     u8 val;
2513     int ret;
2514     unsigned int maxw;
2515     struct v4l2_ctrl_handler *hdl;
2516     struct em28xx_v4l2 *v4l2;
2517 
2518     if (dev->is_audio_only) {
2519         /* Shouldn't initialize IR for this interface */
2520         return 0;
2521     }
2522 
2523     if (!dev->has_video) {
2524         /* This device does not support the v4l2 extension */
2525         return 0;
2526     }
2527 
2528     dev_info(&dev->intf->dev, "Registering V4L2 extension\n");
2529 
2530     mutex_lock(&dev->lock);
2531 
2532     v4l2 = kzalloc(sizeof(*v4l2), GFP_KERNEL);
2533     if (!v4l2) {
2534         mutex_unlock(&dev->lock);
2535         return -ENOMEM;
2536     }
2537     kref_init(&v4l2->ref);
2538     v4l2->dev = dev;
2539     dev->v4l2 = v4l2;
2540 
2541 #ifdef CONFIG_MEDIA_CONTROLLER
2542     v4l2->v4l2_dev.mdev = dev->media_dev;
2543 #endif
2544     ret = v4l2_device_register(&dev->intf->dev, &v4l2->v4l2_dev);
2545     if (ret < 0) {
2546         dev_err(&dev->intf->dev,
2547             "Call to v4l2_device_register() failed!\n");
2548         goto err;
2549     }
2550 
2551     hdl = &v4l2->ctrl_handler;
2552     v4l2_ctrl_handler_init(hdl, 8);
2553     v4l2->v4l2_dev.ctrl_handler = hdl;
2554 
2555     if (dev->is_webcam)
2556         v4l2->progressive = true;
2557 
2558     /*
2559      * Default format, used for tvp5150 or saa711x output formats
2560      */
2561     v4l2->vinmode = EM28XX_VINMODE_YUV422_CbYCrY;
2562     v4l2->vinctl  = EM28XX_VINCTRL_INTERLACED |
2563             EM28XX_VINCTRL_CCIR656_ENABLE;
2564 
2565     /* request some modules */
2566 
2567     if (dev->has_msp34xx)
2568         v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2569                     &dev->i2c_adap[dev->def_i2c_bus],
2570                     "msp3400", 0, msp3400_addrs);
2571 
2572     if (dev->board.decoder == EM28XX_SAA711X)
2573         v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2574                     &dev->i2c_adap[dev->def_i2c_bus],
2575                     "saa7115_auto", 0, saa711x_addrs);
2576 
2577     if (dev->board.decoder == EM28XX_TVP5150)
2578         v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2579                     &dev->i2c_adap[dev->def_i2c_bus],
2580                     "tvp5150", 0, tvp5150_addrs);
2581 
2582     if (dev->board.adecoder == EM28XX_TVAUDIO)
2583         v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2584                     &dev->i2c_adap[dev->def_i2c_bus],
2585                     "tvaudio", dev->board.tvaudio_addr, NULL);
2586 
2587     /* Initialize tuner and camera */
2588 
2589     if (dev->board.tuner_type != TUNER_ABSENT) {
2590         unsigned short tuner_addr = dev->board.tuner_addr;
2591         int has_demod = (dev->board.tda9887_conf & TDA9887_PRESENT);
2592 
2593         if (dev->board.radio.type)
2594             v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2595                         &dev->i2c_adap[dev->def_i2c_bus],
2596                         "tuner", dev->board.radio_addr,
2597                         NULL);
2598 
2599         if (has_demod)
2600             v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2601                         &dev->i2c_adap[dev->def_i2c_bus],
2602                         "tuner", 0,
2603                         v4l2_i2c_tuner_addrs(ADDRS_DEMOD));
2604         if (tuner_addr == 0) {
2605             enum v4l2_i2c_tuner_type type =
2606                 has_demod ? ADDRS_TV_WITH_DEMOD : ADDRS_TV;
2607             struct v4l2_subdev *sd;
2608 
2609             sd = v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2610                          &dev->i2c_adap[dev->def_i2c_bus],
2611                          "tuner", 0,
2612                          v4l2_i2c_tuner_addrs(type));
2613 
2614             if (sd)
2615                 tuner_addr = v4l2_i2c_subdev_addr(sd);
2616         } else {
2617             v4l2_i2c_new_subdev(&v4l2->v4l2_dev,
2618                         &dev->i2c_adap[dev->def_i2c_bus],
2619                         "tuner", tuner_addr, NULL);
2620         }
2621 
2622         em28xx_tuner_setup(dev, tuner_addr);
2623     }
2624 
2625     if (dev->em28xx_sensor != EM28XX_NOSENSOR)
2626         em28xx_init_camera(dev);
2627 
2628     /* Configure audio */
2629     ret = em28xx_audio_setup(dev);
2630     if (ret < 0) {
2631         dev_err(&dev->intf->dev,
2632             "%s: Error while setting audio - error [%d]!\n",
2633             __func__, ret);
2634         goto unregister_dev;
2635     }
2636     if (dev->audio_mode.ac97 != EM28XX_NO_AC97) {
2637         v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2638                   V4L2_CID_AUDIO_MUTE, 0, 1, 1, 1);
2639         v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2640                   V4L2_CID_AUDIO_VOLUME, 0, 0x1f, 1, 0x1f);
2641     } else {
2642         /* install the em28xx notify callback */
2643         v4l2_ctrl_notify(v4l2_ctrl_find(hdl, V4L2_CID_AUDIO_MUTE),
2644                  em28xx_ctrl_notify, dev);
2645         v4l2_ctrl_notify(v4l2_ctrl_find(hdl, V4L2_CID_AUDIO_VOLUME),
2646                  em28xx_ctrl_notify, dev);
2647     }
2648 
2649     /* wake i2c devices */
2650     em28xx_wake_i2c(dev);
2651 
2652     /* init video dma queues */
2653     INIT_LIST_HEAD(&dev->vidq.active);
2654     INIT_LIST_HEAD(&dev->vbiq.active);
2655 
2656     if (dev->has_msp34xx) {
2657         /* Send a reset to other chips via gpio */
2658         ret = em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xf7);
2659         if (ret < 0) {
2660             dev_err(&dev->intf->dev,
2661                 "%s: em28xx_write_reg - msp34xx(1) failed! error [%d]\n",
2662                 __func__, ret);
2663             goto unregister_dev;
2664         }
2665         usleep_range(10000, 11000);
2666 
2667         ret = em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xff);
2668         if (ret < 0) {
2669             dev_err(&dev->intf->dev,
2670                 "%s: em28xx_write_reg - msp34xx(2) failed! error [%d]\n",
2671                 __func__, ret);
2672             goto unregister_dev;
2673         }
2674         usleep_range(10000, 11000);
2675     }
2676 
2677     /* set default norm */
2678     v4l2->norm = V4L2_STD_PAL;
2679     v4l2_device_call_all(&v4l2->v4l2_dev, 0, video, s_std, v4l2->norm);
2680     v4l2->interlaced_fieldmode = EM28XX_INTERLACED_DEFAULT;
2681 
2682     /* Analog specific initialization */
2683     v4l2->format = &format[0];
2684 
2685     maxw = norm_maxw(dev);
2686     /*
2687      * MaxPacketSize for em2800 is too small to capture at full resolution
2688      * use half of maxw as the scaler can only scale to 50%
2689      */
2690     if (dev->board.is_em2800)
2691         maxw /= 2;
2692 
2693     em28xx_set_video_format(dev, format[0].fourcc,
2694                 maxw, norm_maxh(dev));
2695 
2696     video_mux(dev, 0);
2697 
2698     /* Audio defaults */
2699     dev->mute = 1;
2700     dev->volume = 0x1f;
2701 
2702 /*  em28xx_write_reg(dev, EM28XX_R0E_AUDIOSRC, 0xc0); audio register */
2703     val = (u8)em28xx_read_reg(dev, EM28XX_R0F_XCLK);
2704     em28xx_write_reg(dev, EM28XX_R0F_XCLK,
2705              (EM28XX_XCLK_AUDIO_UNMUTE | val));
2706 
2707     em28xx_set_outfmt(dev);
2708 
2709     /* Add image controls */
2710 
2711     /*
2712      * NOTE: at this point, the subdevices are already registered, so
2713      * bridge controls are only added/enabled when no subdevice provides
2714      * them
2715      */
2716     if (!v4l2_ctrl_find(hdl, V4L2_CID_CONTRAST))
2717         v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2718                   V4L2_CID_CONTRAST,
2719                   0, 0x1f, 1, CONTRAST_DEFAULT);
2720     if (!v4l2_ctrl_find(hdl, V4L2_CID_BRIGHTNESS))
2721         v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2722                   V4L2_CID_BRIGHTNESS,
2723                   -0x80, 0x7f, 1, BRIGHTNESS_DEFAULT);
2724     if (!v4l2_ctrl_find(hdl, V4L2_CID_SATURATION))
2725         v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2726                   V4L2_CID_SATURATION,
2727                   0, 0x1f, 1, SATURATION_DEFAULT);
2728     if (!v4l2_ctrl_find(hdl, V4L2_CID_BLUE_BALANCE))
2729         v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2730                   V4L2_CID_BLUE_BALANCE,
2731                   -0x30, 0x30, 1, BLUE_BALANCE_DEFAULT);
2732     if (!v4l2_ctrl_find(hdl, V4L2_CID_RED_BALANCE))
2733         v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2734                   V4L2_CID_RED_BALANCE,
2735                   -0x30, 0x30, 1, RED_BALANCE_DEFAULT);
2736     if (!v4l2_ctrl_find(hdl, V4L2_CID_SHARPNESS))
2737         v4l2_ctrl_new_std(hdl, &em28xx_ctrl_ops,
2738                   V4L2_CID_SHARPNESS,
2739                   0, 0x0f, 1, SHARPNESS_DEFAULT);
2740 
2741     /* Reset image controls */
2742     em28xx_colorlevels_set_default(dev);
2743     v4l2_ctrl_handler_setup(hdl);
2744     ret = hdl->error;
2745     if (ret)
2746         goto unregister_dev;
2747 
2748     /* allocate and fill video video_device struct */
2749     em28xx_vdev_init(dev, &v4l2->vdev, &em28xx_video_template, "video");
2750     mutex_init(&v4l2->vb_queue_lock);
2751     mutex_init(&v4l2->vb_vbi_queue_lock);
2752     v4l2->vdev.queue = &v4l2->vb_vidq;
2753     v4l2->vdev.queue->lock = &v4l2->vb_queue_lock;
2754     v4l2->vdev.device_caps = V4L2_CAP_READWRITE | V4L2_CAP_VIDEO_CAPTURE |
2755                  V4L2_CAP_STREAMING;
2756     if (dev->int_audio_type != EM28XX_INT_AUDIO_NONE)
2757         v4l2->vdev.device_caps |= V4L2_CAP_AUDIO;
2758     if (dev->tuner_type != TUNER_ABSENT)
2759         v4l2->vdev.device_caps |= V4L2_CAP_TUNER;
2760 
2761 
2762     /* disable inapplicable ioctls */
2763     if (dev->is_webcam) {
2764         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_QUERYSTD);
2765         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_STD);
2766         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_STD);
2767     } else {
2768         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_PARM);
2769     }
2770     if (dev->tuner_type == TUNER_ABSENT) {
2771         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_TUNER);
2772         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_TUNER);
2773         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_FREQUENCY);
2774         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_FREQUENCY);
2775     }
2776     if (dev->int_audio_type == EM28XX_INT_AUDIO_NONE) {
2777         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_G_AUDIO);
2778         v4l2_disable_ioctl(&v4l2->vdev, VIDIOC_S_AUDIO);
2779     }
2780 
2781     /* register v4l2 video video_device */
2782     ret = video_register_device(&v4l2->vdev, VFL_TYPE_VIDEO,
2783                     video_nr[dev->devno]);
2784     if (ret) {
2785         dev_err(&dev->intf->dev,
2786             "unable to register video device (error=%i).\n", ret);
2787         goto unregister_dev;
2788     }
2789 
2790     /* Allocate and fill vbi video_device struct */
2791     if (em28xx_vbi_supported(dev) == 1) {
2792         em28xx_vdev_init(dev, &v4l2->vbi_dev, &em28xx_video_template,
2793                  "vbi");
2794 
2795         v4l2->vbi_dev.queue = &v4l2->vb_vbiq;
2796         v4l2->vbi_dev.queue->lock = &v4l2->vb_vbi_queue_lock;
2797         v4l2->vbi_dev.device_caps = V4L2_CAP_STREAMING |
2798             V4L2_CAP_READWRITE | V4L2_CAP_VBI_CAPTURE;
2799         if (dev->tuner_type != TUNER_ABSENT)
2800             v4l2->vbi_dev.device_caps |= V4L2_CAP_TUNER;
2801 
2802         /* disable inapplicable ioctls */
2803         v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_PARM);
2804         if (dev->tuner_type == TUNER_ABSENT) {
2805             v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_TUNER);
2806             v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_TUNER);
2807             v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_FREQUENCY);
2808             v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_FREQUENCY);
2809         }
2810         if (dev->int_audio_type == EM28XX_INT_AUDIO_NONE) {
2811             v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_G_AUDIO);
2812             v4l2_disable_ioctl(&v4l2->vbi_dev, VIDIOC_S_AUDIO);
2813         }
2814 
2815         /* register v4l2 vbi video_device */
2816         ret = video_register_device(&v4l2->vbi_dev, VFL_TYPE_VBI,
2817                         vbi_nr[dev->devno]);
2818         if (ret < 0) {
2819             dev_err(&dev->intf->dev,
2820                 "unable to register vbi device\n");
2821             goto unregister_dev;
2822         }
2823     }
2824 
2825     if (em28xx_boards[dev->model].radio.type == EM28XX_RADIO) {
2826         em28xx_vdev_init(dev, &v4l2->radio_dev, &em28xx_radio_template,
2827                  "radio");
2828         v4l2->radio_dev.device_caps = V4L2_CAP_RADIO | V4L2_CAP_TUNER;
2829         ret = video_register_device(&v4l2->radio_dev, VFL_TYPE_RADIO,
2830                         radio_nr[dev->devno]);
2831         if (ret < 0) {
2832             dev_err(&dev->intf->dev,
2833                 "can't register radio device\n");
2834             goto unregister_dev;
2835         }
2836         dev_info(&dev->intf->dev,
2837              "Registered radio device as %s\n",
2838              video_device_node_name(&v4l2->radio_dev));
2839     }
2840 
2841     /* Init entities at the Media Controller */
2842     em28xx_v4l2_create_entities(dev);
2843 
2844 #ifdef CONFIG_MEDIA_CONTROLLER
2845     ret = v4l2_mc_create_media_graph(dev->media_dev);
2846     if (ret) {
2847         dev_err(&dev->intf->dev,
2848             "failed to create media graph\n");
2849         em28xx_v4l2_media_release(dev);
2850         goto unregister_dev;
2851     }
2852 #endif
2853 
2854     dev_info(&dev->intf->dev,
2855          "V4L2 video device registered as %s\n",
2856          video_device_node_name(&v4l2->vdev));
2857 
2858     if (video_is_registered(&v4l2->vbi_dev))
2859         dev_info(&dev->intf->dev,
2860              "V4L2 VBI device registered as %s\n",
2861              video_device_node_name(&v4l2->vbi_dev));
2862 
2863     /* Save some power by putting tuner to sleep */
2864     v4l2_device_call_all(&v4l2->v4l2_dev, 0, tuner, standby);
2865 
2866     /* initialize videobuf2 stuff */
2867     em28xx_vb2_setup(dev);
2868 
2869     dev_info(&dev->intf->dev,
2870          "V4L2 extension successfully initialized\n");
2871 
2872     kref_get(&dev->ref);
2873 
2874     mutex_unlock(&dev->lock);
2875     return 0;
2876 
2877 unregister_dev:
2878     if (video_is_registered(&v4l2->radio_dev)) {
2879         dev_info(&dev->intf->dev,
2880              "V4L2 device %s deregistered\n",
2881              video_device_node_name(&v4l2->radio_dev));
2882         video_unregister_device(&v4l2->radio_dev);
2883     }
2884     if (video_is_registered(&v4l2->vbi_dev)) {
2885         dev_info(&dev->intf->dev,
2886              "V4L2 device %s deregistered\n",
2887              video_device_node_name(&v4l2->vbi_dev));
2888         video_unregister_device(&v4l2->vbi_dev);
2889     }
2890     if (video_is_registered(&v4l2->vdev)) {
2891         dev_info(&dev->intf->dev,
2892              "V4L2 device %s deregistered\n",
2893              video_device_node_name(&v4l2->vdev));
2894         video_unregister_device(&v4l2->vdev);
2895     }
2896 
2897     v4l2_ctrl_handler_free(&v4l2->ctrl_handler);
2898     v4l2_device_unregister(&v4l2->v4l2_dev);
2899 err:
2900     dev->v4l2 = NULL;
2901     kref_put(&v4l2->ref, em28xx_free_v4l2);
2902     mutex_unlock(&dev->lock);
2903     return ret;
2904 }
2905 
2906 static struct em28xx_ops v4l2_ops = {
2907     .id   = EM28XX_V4L2,
2908     .name = "Em28xx v4l2 Extension",
2909     .init = em28xx_v4l2_init,
2910     .fini = em28xx_v4l2_fini,
2911     .suspend = em28xx_v4l2_suspend,
2912     .resume = em28xx_v4l2_resume,
2913 };
2914 
2915 static int __init em28xx_video_register(void)
2916 {
2917     return em28xx_register_extension(&v4l2_ops);
2918 }
2919 
2920 static void __exit em28xx_video_unregister(void)
2921 {
2922     em28xx_unregister_extension(&v4l2_ops);
2923 }
2924 
2925 module_init(em28xx_video_register);
2926 module_exit(em28xx_video_unregister);