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