treewide: remove redundant #include <linux/kconfig.h>
[cascardo/linux.git] / drivers / media / usb / hdpvr / hdpvr-video.c
1 /*
2  * Hauppauge HD PVR USB driver - video 4 linux 2 interface
3  *
4  * Copyright (C) 2008      Janne Grunau (j@jannau.net)
5  *
6  *      This program is free software; you can redistribute it and/or
7  *      modify it under the terms of the GNU General Public License as
8  *      published by the Free Software Foundation, version 2.
9  *
10  */
11
12 #include <linux/kernel.h>
13 #include <linux/errno.h>
14 #include <linux/init.h>
15 #include <linux/slab.h>
16 #include <linux/module.h>
17 #include <linux/uaccess.h>
18 #include <linux/usb.h>
19 #include <linux/mutex.h>
20 #include <linux/workqueue.h>
21
22 #include <linux/videodev2.h>
23 #include <linux/v4l2-dv-timings.h>
24 #include <media/v4l2-dev.h>
25 #include <media/v4l2-common.h>
26 #include <media/v4l2-dv-timings.h>
27 #include <media/v4l2-ioctl.h>
28 #include <media/v4l2-event.h>
29 #include "hdpvr.h"
30
31 #define BULK_URB_TIMEOUT   90 /* 0.09 seconds */
32
33 #define print_buffer_status() { \
34                 v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,       \
35                          "%s:%d buffer stat: %d free, %d proc\n",       \
36                          __func__, __LINE__,                            \
37                          list_size(&dev->free_buff_list),               \
38                          list_size(&dev->rec_buff_list)); }
39
40 static const struct v4l2_dv_timings hdpvr_dv_timings[] = {
41         V4L2_DV_BT_CEA_720X480I59_94,
42         V4L2_DV_BT_CEA_720X576I50,
43         V4L2_DV_BT_CEA_720X480P59_94,
44         V4L2_DV_BT_CEA_720X576P50,
45         V4L2_DV_BT_CEA_1280X720P50,
46         V4L2_DV_BT_CEA_1280X720P60,
47         V4L2_DV_BT_CEA_1920X1080I50,
48         V4L2_DV_BT_CEA_1920X1080I60,
49 };
50
51 /* Use 480i59 as the default timings */
52 #define HDPVR_DEF_DV_TIMINGS_IDX (0)
53
54 struct hdpvr_fh {
55         struct v4l2_fh fh;
56         bool legacy_mode;
57 };
58
59 static uint list_size(struct list_head *list)
60 {
61         struct list_head *tmp;
62         uint count = 0;
63
64         list_for_each(tmp, list) {
65                 count++;
66         }
67
68         return count;
69 }
70
71 /*=========================================================================*/
72 /* urb callback */
73 static void hdpvr_read_bulk_callback(struct urb *urb)
74 {
75         struct hdpvr_buffer *buf = (struct hdpvr_buffer *)urb->context;
76         struct hdpvr_device *dev = buf->dev;
77
78         /* marking buffer as received and wake waiting */
79         buf->status = BUFSTAT_READY;
80         wake_up_interruptible(&dev->wait_data);
81 }
82
83 /*=========================================================================*/
84 /* buffer bits */
85
86 /* function expects dev->io_mutex to be hold by caller */
87 int hdpvr_cancel_queue(struct hdpvr_device *dev)
88 {
89         struct hdpvr_buffer *buf;
90
91         list_for_each_entry(buf, &dev->rec_buff_list, buff_list) {
92                 usb_kill_urb(buf->urb);
93                 buf->status = BUFSTAT_AVAILABLE;
94         }
95
96         list_splice_init(&dev->rec_buff_list, dev->free_buff_list.prev);
97
98         return 0;
99 }
100
101 static int hdpvr_free_queue(struct list_head *q)
102 {
103         struct list_head *tmp;
104         struct list_head *p;
105         struct hdpvr_buffer *buf;
106         struct urb *urb;
107
108         for (p = q->next; p != q;) {
109                 buf = list_entry(p, struct hdpvr_buffer, buff_list);
110
111                 urb = buf->urb;
112                 usb_free_coherent(urb->dev, urb->transfer_buffer_length,
113                                   urb->transfer_buffer, urb->transfer_dma);
114                 usb_free_urb(urb);
115                 tmp = p->next;
116                 list_del(p);
117                 kfree(buf);
118                 p = tmp;
119         }
120
121         return 0;
122 }
123
124 /* function expects dev->io_mutex to be hold by caller */
125 int hdpvr_free_buffers(struct hdpvr_device *dev)
126 {
127         hdpvr_cancel_queue(dev);
128
129         hdpvr_free_queue(&dev->free_buff_list);
130         hdpvr_free_queue(&dev->rec_buff_list);
131
132         return 0;
133 }
134
135 /* function expects dev->io_mutex to be hold by caller */
136 int hdpvr_alloc_buffers(struct hdpvr_device *dev, uint count)
137 {
138         uint i;
139         int retval = -ENOMEM;
140         u8 *mem;
141         struct hdpvr_buffer *buf;
142         struct urb *urb;
143
144         v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
145                  "allocating %u buffers\n", count);
146
147         for (i = 0; i < count; i++) {
148
149                 buf = kzalloc(sizeof(struct hdpvr_buffer), GFP_KERNEL);
150                 if (!buf) {
151                         v4l2_err(&dev->v4l2_dev, "cannot allocate buffer\n");
152                         goto exit;
153                 }
154                 buf->dev = dev;
155
156                 urb = usb_alloc_urb(0, GFP_KERNEL);
157                 if (!urb)
158                         goto exit_urb;
159                 buf->urb = urb;
160
161                 mem = usb_alloc_coherent(dev->udev, dev->bulk_in_size, GFP_KERNEL,
162                                          &urb->transfer_dma);
163                 if (!mem) {
164                         v4l2_err(&dev->v4l2_dev,
165                                  "cannot allocate usb transfer buffer\n");
166                         goto exit_urb_buffer;
167                 }
168
169                 usb_fill_bulk_urb(buf->urb, dev->udev,
170                                   usb_rcvbulkpipe(dev->udev,
171                                                   dev->bulk_in_endpointAddr),
172                                   mem, dev->bulk_in_size,
173                                   hdpvr_read_bulk_callback, buf);
174
175                 buf->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
176                 buf->status = BUFSTAT_AVAILABLE;
177                 list_add_tail(&buf->buff_list, &dev->free_buff_list);
178         }
179         return 0;
180 exit_urb_buffer:
181         usb_free_urb(urb);
182 exit_urb:
183         kfree(buf);
184 exit:
185         hdpvr_free_buffers(dev);
186         return retval;
187 }
188
189 static int hdpvr_submit_buffers(struct hdpvr_device *dev)
190 {
191         struct hdpvr_buffer *buf;
192         struct urb *urb;
193         int ret = 0, err_count = 0;
194
195         mutex_lock(&dev->io_mutex);
196
197         while (dev->status == STATUS_STREAMING &&
198                !list_empty(&dev->free_buff_list)) {
199
200                 buf = list_entry(dev->free_buff_list.next, struct hdpvr_buffer,
201                                  buff_list);
202                 if (buf->status != BUFSTAT_AVAILABLE) {
203                         v4l2_err(&dev->v4l2_dev,
204                                  "buffer not marked as available\n");
205                         ret = -EFAULT;
206                         goto err;
207                 }
208
209                 urb = buf->urb;
210                 urb->status = 0;
211                 urb->actual_length = 0;
212                 ret = usb_submit_urb(urb, GFP_KERNEL);
213                 if (ret) {
214                         v4l2_err(&dev->v4l2_dev,
215                                  "usb_submit_urb in %s returned %d\n",
216                                  __func__, ret);
217                         if (++err_count > 2)
218                                 break;
219                         continue;
220                 }
221                 buf->status = BUFSTAT_INPROGRESS;
222                 list_move_tail(&buf->buff_list, &dev->rec_buff_list);
223         }
224 err:
225         print_buffer_status();
226         mutex_unlock(&dev->io_mutex);
227         return ret;
228 }
229
230 static struct hdpvr_buffer *hdpvr_get_next_buffer(struct hdpvr_device *dev)
231 {
232         struct hdpvr_buffer *buf;
233
234         mutex_lock(&dev->io_mutex);
235
236         if (list_empty(&dev->rec_buff_list)) {
237                 mutex_unlock(&dev->io_mutex);
238                 return NULL;
239         }
240
241         buf = list_entry(dev->rec_buff_list.next, struct hdpvr_buffer,
242                          buff_list);
243         mutex_unlock(&dev->io_mutex);
244
245         return buf;
246 }
247
248 static void hdpvr_transmit_buffers(struct work_struct *work)
249 {
250         struct hdpvr_device *dev = container_of(work, struct hdpvr_device,
251                                                 worker);
252
253         while (dev->status == STATUS_STREAMING) {
254
255                 if (hdpvr_submit_buffers(dev)) {
256                         v4l2_err(&dev->v4l2_dev, "couldn't submit buffers\n");
257                         goto error;
258                 }
259                 if (wait_event_interruptible(dev->wait_buffer,
260                                 !list_empty(&dev->free_buff_list) ||
261                                              dev->status != STATUS_STREAMING))
262                         goto error;
263         }
264
265         v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
266                  "transmit worker exited\n");
267         return;
268 error:
269         v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
270                  "transmit buffers errored\n");
271         dev->status = STATUS_ERROR;
272 }
273
274 /* function expects dev->io_mutex to be hold by caller */
275 static int hdpvr_start_streaming(struct hdpvr_device *dev)
276 {
277         int ret;
278         struct hdpvr_video_info vidinf;
279
280         if (dev->status == STATUS_STREAMING)
281                 return 0;
282         if (dev->status != STATUS_IDLE)
283                 return -EAGAIN;
284
285         ret = get_video_info(dev, &vidinf);
286         if (ret < 0)
287                 return ret;
288
289         if (!vidinf.valid) {
290                 msleep(250);
291                 v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
292                                 "no video signal at input %d\n", dev->options.video_input);
293                 return -EAGAIN;
294         }
295
296         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
297                         "video signal: %dx%d@%dhz\n", vidinf.width,
298                         vidinf.height, vidinf.fps);
299
300         /* start streaming 2 request */
301         ret = usb_control_msg(dev->udev,
302                         usb_sndctrlpipe(dev->udev, 0),
303                         0xb8, 0x38, 0x1, 0, NULL, 0, 8000);
304         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
305                         "encoder start control request returned %d\n", ret);
306         if (ret < 0)
307                 return ret;
308
309         ret = hdpvr_config_call(dev, CTRL_START_STREAMING_VALUE, 0x00);
310         if (ret)
311                 return ret;
312
313         dev->status = STATUS_STREAMING;
314
315         INIT_WORK(&dev->worker, hdpvr_transmit_buffers);
316         schedule_work(&dev->worker);
317
318         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
319                         "streaming started\n");
320
321         return 0;
322 }
323
324
325 /* function expects dev->io_mutex to be hold by caller */
326 static int hdpvr_stop_streaming(struct hdpvr_device *dev)
327 {
328         int actual_length;
329         uint c = 0;
330         u8 *buf;
331
332         if (dev->status == STATUS_IDLE)
333                 return 0;
334         else if (dev->status != STATUS_STREAMING)
335                 return -EAGAIN;
336
337         buf = kmalloc(dev->bulk_in_size, GFP_KERNEL);
338         if (!buf)
339                 v4l2_err(&dev->v4l2_dev, "failed to allocate temporary buffer "
340                          "for emptying the internal device buffer. "
341                          "Next capture start will be slow\n");
342
343         dev->status = STATUS_SHUTTING_DOWN;
344         hdpvr_config_call(dev, CTRL_STOP_STREAMING_VALUE, 0x00);
345         mutex_unlock(&dev->io_mutex);
346
347         wake_up_interruptible(&dev->wait_buffer);
348         msleep(50);
349
350         flush_work(&dev->worker);
351
352         mutex_lock(&dev->io_mutex);
353         /* kill the still outstanding urbs */
354         hdpvr_cancel_queue(dev);
355
356         /* emptying the device buffer beforeshutting it down */
357         while (buf && ++c < 500 &&
358                !usb_bulk_msg(dev->udev,
359                              usb_rcvbulkpipe(dev->udev,
360                                              dev->bulk_in_endpointAddr),
361                              buf, dev->bulk_in_size, &actual_length,
362                              BULK_URB_TIMEOUT)) {
363                 v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
364                          "%2d: got %d bytes\n", c, actual_length);
365         }
366         kfree(buf);
367         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
368                  "used %d urbs to empty device buffers\n", c-1);
369         msleep(10);
370
371         dev->status = STATUS_IDLE;
372
373         return 0;
374 }
375
376
377 /*=======================================================================*/
378 /*
379  * video 4 linux 2 file operations
380  */
381
382 static int hdpvr_open(struct file *file)
383 {
384         struct hdpvr_fh *fh = kzalloc(sizeof(*fh), GFP_KERNEL);
385
386         if (fh == NULL)
387                 return -ENOMEM;
388         fh->legacy_mode = true;
389         v4l2_fh_init(&fh->fh, video_devdata(file));
390         v4l2_fh_add(&fh->fh);
391         file->private_data = fh;
392         return 0;
393 }
394
395 static int hdpvr_release(struct file *file)
396 {
397         struct hdpvr_device *dev = video_drvdata(file);
398
399         mutex_lock(&dev->io_mutex);
400         if (file->private_data == dev->owner) {
401                 hdpvr_stop_streaming(dev);
402                 dev->owner = NULL;
403         }
404         mutex_unlock(&dev->io_mutex);
405
406         return v4l2_fh_release(file);
407 }
408
409 /*
410  * hdpvr_v4l2_read()
411  * will allocate buffers when called for the first time
412  */
413 static ssize_t hdpvr_read(struct file *file, char __user *buffer, size_t count,
414                           loff_t *pos)
415 {
416         struct hdpvr_device *dev = video_drvdata(file);
417         struct hdpvr_buffer *buf = NULL;
418         struct urb *urb;
419         unsigned int ret = 0;
420         int rem, cnt;
421
422         if (*pos)
423                 return -ESPIPE;
424
425         mutex_lock(&dev->io_mutex);
426         if (dev->status == STATUS_IDLE) {
427                 if (hdpvr_start_streaming(dev)) {
428                         v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
429                                  "start_streaming failed\n");
430                         ret = -EIO;
431                         msleep(200);
432                         dev->status = STATUS_IDLE;
433                         mutex_unlock(&dev->io_mutex);
434                         goto err;
435                 }
436                 dev->owner = file->private_data;
437                 print_buffer_status();
438         }
439         mutex_unlock(&dev->io_mutex);
440
441         /* wait for the first buffer */
442         if (!(file->f_flags & O_NONBLOCK)) {
443                 if (wait_event_interruptible(dev->wait_data,
444                                              hdpvr_get_next_buffer(dev)))
445                         return -ERESTARTSYS;
446         }
447
448         buf = hdpvr_get_next_buffer(dev);
449
450         while (count > 0 && buf) {
451
452                 if (buf->status != BUFSTAT_READY &&
453                     dev->status != STATUS_DISCONNECTED) {
454                         /* return nonblocking */
455                         if (file->f_flags & O_NONBLOCK) {
456                                 if (!ret)
457                                         ret = -EAGAIN;
458                                 goto err;
459                         }
460
461                         if (wait_event_interruptible(dev->wait_data,
462                                               buf->status == BUFSTAT_READY))
463                                 return -ERESTARTSYS;
464                 }
465
466                 if (buf->status != BUFSTAT_READY)
467                         break;
468
469                 /* set remaining bytes to copy */
470                 urb = buf->urb;
471                 rem = urb->actual_length - buf->pos;
472                 cnt = rem > count ? count : rem;
473
474                 if (copy_to_user(buffer, urb->transfer_buffer + buf->pos,
475                                  cnt)) {
476                         v4l2_err(&dev->v4l2_dev, "read: copy_to_user failed\n");
477                         if (!ret)
478                                 ret = -EFAULT;
479                         goto err;
480                 }
481
482                 buf->pos += cnt;
483                 count -= cnt;
484                 buffer += cnt;
485                 ret += cnt;
486
487                 /* finished, take next buffer */
488                 if (buf->pos == urb->actual_length) {
489                         mutex_lock(&dev->io_mutex);
490                         buf->pos = 0;
491                         buf->status = BUFSTAT_AVAILABLE;
492
493                         list_move_tail(&buf->buff_list, &dev->free_buff_list);
494
495                         print_buffer_status();
496
497                         mutex_unlock(&dev->io_mutex);
498
499                         wake_up_interruptible(&dev->wait_buffer);
500
501                         buf = hdpvr_get_next_buffer(dev);
502                 }
503         }
504 err:
505         if (!ret && !buf)
506                 ret = -EAGAIN;
507         return ret;
508 }
509
510 static unsigned int hdpvr_poll(struct file *filp, poll_table *wait)
511 {
512         unsigned long req_events = poll_requested_events(wait);
513         struct hdpvr_buffer *buf = NULL;
514         struct hdpvr_device *dev = video_drvdata(filp);
515         unsigned int mask = v4l2_ctrl_poll(filp, wait);
516
517         if (!(req_events & (POLLIN | POLLRDNORM)))
518                 return mask;
519
520         mutex_lock(&dev->io_mutex);
521
522         if (dev->status == STATUS_IDLE) {
523                 if (hdpvr_start_streaming(dev)) {
524                         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
525                                  "start_streaming failed\n");
526                         dev->status = STATUS_IDLE;
527                 } else {
528                         dev->owner = filp->private_data;
529                 }
530
531                 print_buffer_status();
532         }
533         mutex_unlock(&dev->io_mutex);
534
535         buf = hdpvr_get_next_buffer(dev);
536         /* only wait if no data is available */
537         if (!buf || buf->status != BUFSTAT_READY) {
538                 poll_wait(filp, &dev->wait_data, wait);
539                 buf = hdpvr_get_next_buffer(dev);
540         }
541         if (buf && buf->status == BUFSTAT_READY)
542                 mask |= POLLIN | POLLRDNORM;
543
544         return mask;
545 }
546
547
548 static const struct v4l2_file_operations hdpvr_fops = {
549         .owner          = THIS_MODULE,
550         .open           = hdpvr_open,
551         .release        = hdpvr_release,
552         .read           = hdpvr_read,
553         .poll           = hdpvr_poll,
554         .unlocked_ioctl = video_ioctl2,
555 };
556
557 /*=======================================================================*/
558 /*
559  * V4L2 ioctl handling
560  */
561
562 static int vidioc_querycap(struct file *file, void  *priv,
563                            struct v4l2_capability *cap)
564 {
565         struct hdpvr_device *dev = video_drvdata(file);
566
567         strcpy(cap->driver, "hdpvr");
568         strcpy(cap->card, "Hauppauge HD PVR");
569         usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
570         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_AUDIO |
571                             V4L2_CAP_READWRITE;
572         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
573         return 0;
574 }
575
576 static int vidioc_s_std(struct file *file, void *_fh,
577                         v4l2_std_id std)
578 {
579         struct hdpvr_device *dev = video_drvdata(file);
580         struct hdpvr_fh *fh = _fh;
581         u8 std_type = 1;
582
583         if (!fh->legacy_mode && dev->options.video_input == HDPVR_COMPONENT)
584                 return -ENODATA;
585         if (dev->status != STATUS_IDLE)
586                 return -EBUSY;
587         if (std & V4L2_STD_525_60)
588                 std_type = 0;
589         dev->cur_std = std;
590         dev->width = 720;
591         dev->height = std_type ? 576 : 480;
592
593         return hdpvr_config_call(dev, CTRL_VIDEO_STD_TYPE, std_type);
594 }
595
596 static int vidioc_g_std(struct file *file, void *_fh,
597                         v4l2_std_id *std)
598 {
599         struct hdpvr_device *dev = video_drvdata(file);
600         struct hdpvr_fh *fh = _fh;
601
602         if (!fh->legacy_mode && dev->options.video_input == HDPVR_COMPONENT)
603                 return -ENODATA;
604         *std = dev->cur_std;
605         return 0;
606 }
607
608 static int vidioc_querystd(struct file *file, void *_fh, v4l2_std_id *a)
609 {
610         struct hdpvr_device *dev = video_drvdata(file);
611         struct hdpvr_video_info vid_info;
612         struct hdpvr_fh *fh = _fh;
613         int ret;
614
615         *a = V4L2_STD_UNKNOWN;
616         if (dev->options.video_input == HDPVR_COMPONENT)
617                 return fh->legacy_mode ? 0 : -ENODATA;
618         ret = get_video_info(dev, &vid_info);
619         if (vid_info.valid && vid_info.width == 720 &&
620             (vid_info.height == 480 || vid_info.height == 576)) {
621                 *a = (vid_info.height == 480) ?
622                         V4L2_STD_525_60 : V4L2_STD_625_50;
623         }
624         return ret;
625 }
626
627 static int vidioc_s_dv_timings(struct file *file, void *_fh,
628                                     struct v4l2_dv_timings *timings)
629 {
630         struct hdpvr_device *dev = video_drvdata(file);
631         struct hdpvr_fh *fh = _fh;
632         int i;
633
634         fh->legacy_mode = false;
635         if (dev->options.video_input)
636                 return -ENODATA;
637         if (dev->status != STATUS_IDLE)
638                 return -EBUSY;
639         for (i = 0; i < ARRAY_SIZE(hdpvr_dv_timings); i++)
640                 if (v4l2_match_dv_timings(timings, hdpvr_dv_timings + i, 0, false))
641                         break;
642         if (i == ARRAY_SIZE(hdpvr_dv_timings))
643                 return -EINVAL;
644         dev->cur_dv_timings = hdpvr_dv_timings[i];
645         dev->width = hdpvr_dv_timings[i].bt.width;
646         dev->height = hdpvr_dv_timings[i].bt.height;
647         return 0;
648 }
649
650 static int vidioc_g_dv_timings(struct file *file, void *_fh,
651                                     struct v4l2_dv_timings *timings)
652 {
653         struct hdpvr_device *dev = video_drvdata(file);
654         struct hdpvr_fh *fh = _fh;
655
656         fh->legacy_mode = false;
657         if (dev->options.video_input)
658                 return -ENODATA;
659         *timings = dev->cur_dv_timings;
660         return 0;
661 }
662
663 static int vidioc_query_dv_timings(struct file *file, void *_fh,
664                                     struct v4l2_dv_timings *timings)
665 {
666         struct hdpvr_device *dev = video_drvdata(file);
667         struct hdpvr_fh *fh = _fh;
668         struct hdpvr_video_info vid_info;
669         bool interlaced;
670         int ret = 0;
671         int i;
672
673         fh->legacy_mode = false;
674         if (dev->options.video_input)
675                 return -ENODATA;
676         ret = get_video_info(dev, &vid_info);
677         if (ret)
678                 return ret;
679         if (!vid_info.valid)
680                 return -ENOLCK;
681         interlaced = vid_info.fps <= 30;
682         for (i = 0; i < ARRAY_SIZE(hdpvr_dv_timings); i++) {
683                 const struct v4l2_bt_timings *bt = &hdpvr_dv_timings[i].bt;
684                 unsigned hsize;
685                 unsigned vsize;
686                 unsigned fps;
687
688                 hsize = V4L2_DV_BT_FRAME_WIDTH(bt);
689                 vsize = V4L2_DV_BT_FRAME_HEIGHT(bt);
690                 fps = (unsigned)bt->pixelclock / (hsize * vsize);
691                 if (bt->width != vid_info.width ||
692                     bt->height != vid_info.height ||
693                     bt->interlaced != interlaced ||
694                     (fps != vid_info.fps && fps + 1 != vid_info.fps))
695                         continue;
696                 *timings = hdpvr_dv_timings[i];
697                 break;
698         }
699         if (i == ARRAY_SIZE(hdpvr_dv_timings))
700                 ret = -ERANGE;
701
702         return ret;
703 }
704
705 static int vidioc_enum_dv_timings(struct file *file, void *_fh,
706                                     struct v4l2_enum_dv_timings *timings)
707 {
708         struct hdpvr_device *dev = video_drvdata(file);
709         struct hdpvr_fh *fh = _fh;
710
711         fh->legacy_mode = false;
712         memset(timings->reserved, 0, sizeof(timings->reserved));
713         if (dev->options.video_input)
714                 return -ENODATA;
715         if (timings->index >= ARRAY_SIZE(hdpvr_dv_timings))
716                 return -EINVAL;
717         timings->timings = hdpvr_dv_timings[timings->index];
718         return 0;
719 }
720
721 static int vidioc_dv_timings_cap(struct file *file, void *_fh,
722                                     struct v4l2_dv_timings_cap *cap)
723 {
724         struct hdpvr_device *dev = video_drvdata(file);
725         struct hdpvr_fh *fh = _fh;
726
727         fh->legacy_mode = false;
728         if (dev->options.video_input)
729                 return -ENODATA;
730         cap->type = V4L2_DV_BT_656_1120;
731         cap->bt.min_width = 720;
732         cap->bt.max_width = 1920;
733         cap->bt.min_height = 480;
734         cap->bt.max_height = 1080;
735         cap->bt.min_pixelclock = 27000000;
736         cap->bt.max_pixelclock = 74250000;
737         cap->bt.standards = V4L2_DV_BT_STD_CEA861;
738         cap->bt.capabilities = V4L2_DV_BT_CAP_INTERLACED | V4L2_DV_BT_CAP_PROGRESSIVE;
739         return 0;
740 }
741
742 static const char *iname[] = {
743         [HDPVR_COMPONENT] = "Component",
744         [HDPVR_SVIDEO]    = "S-Video",
745         [HDPVR_COMPOSITE] = "Composite",
746 };
747
748 static int vidioc_enum_input(struct file *file, void *_fh, struct v4l2_input *i)
749 {
750         unsigned int n;
751
752         n = i->index;
753         if (n >= HDPVR_VIDEO_INPUTS)
754                 return -EINVAL;
755
756         i->type = V4L2_INPUT_TYPE_CAMERA;
757
758         strncpy(i->name, iname[n], sizeof(i->name) - 1);
759         i->name[sizeof(i->name) - 1] = '\0';
760
761         i->audioset = 1<<HDPVR_RCA_FRONT | 1<<HDPVR_RCA_BACK | 1<<HDPVR_SPDIF;
762
763         i->capabilities = n ? V4L2_IN_CAP_STD : V4L2_IN_CAP_DV_TIMINGS;
764         i->std = n ? V4L2_STD_ALL : 0;
765
766         return 0;
767 }
768
769 static int vidioc_s_input(struct file *file, void *_fh,
770                           unsigned int index)
771 {
772         struct hdpvr_device *dev = video_drvdata(file);
773         int retval;
774
775         if (index >= HDPVR_VIDEO_INPUTS)
776                 return -EINVAL;
777
778         if (dev->status != STATUS_IDLE)
779                 return -EBUSY;
780
781         retval = hdpvr_config_call(dev, CTRL_VIDEO_INPUT_VALUE, index+1);
782         if (!retval) {
783                 dev->options.video_input = index;
784                 /*
785                  * Unfortunately gstreamer calls ENUMSTD and bails out if it
786                  * won't find any formats, even though component input is
787                  * selected. This means that we have to leave tvnorms at
788                  * V4L2_STD_ALL. We cannot use the 'legacy' trick since
789                  * tvnorms is set at the device node level and not at the
790                  * filehandle level.
791                  *
792                  * Comment this out for now, but if the legacy mode can be
793                  * removed in the future, then this code should be enabled
794                  * again.
795                 dev->video_dev.tvnorms =
796                         (index != HDPVR_COMPONENT) ? V4L2_STD_ALL : 0;
797                  */
798         }
799
800         return retval;
801 }
802
803 static int vidioc_g_input(struct file *file, void *private_data,
804                           unsigned int *index)
805 {
806         struct hdpvr_device *dev = video_drvdata(file);
807
808         *index = dev->options.video_input;
809         return 0;
810 }
811
812
813 static const char *audio_iname[] = {
814         [HDPVR_RCA_FRONT] = "RCA front",
815         [HDPVR_RCA_BACK]  = "RCA back",
816         [HDPVR_SPDIF]     = "SPDIF",
817 };
818
819 static int vidioc_enumaudio(struct file *file, void *priv,
820                                 struct v4l2_audio *audio)
821 {
822         unsigned int n;
823
824         n = audio->index;
825         if (n >= HDPVR_AUDIO_INPUTS)
826                 return -EINVAL;
827
828         audio->capability = V4L2_AUDCAP_STEREO;
829
830         strncpy(audio->name, audio_iname[n], sizeof(audio->name) - 1);
831         audio->name[sizeof(audio->name) - 1] = '\0';
832
833         return 0;
834 }
835
836 static int vidioc_s_audio(struct file *file, void *private_data,
837                           const struct v4l2_audio *audio)
838 {
839         struct hdpvr_device *dev = video_drvdata(file);
840         int retval;
841
842         if (audio->index >= HDPVR_AUDIO_INPUTS)
843                 return -EINVAL;
844
845         if (dev->status != STATUS_IDLE)
846                 return -EBUSY;
847
848         retval = hdpvr_set_audio(dev, audio->index+1, dev->options.audio_codec);
849         if (!retval)
850                 dev->options.audio_input = audio->index;
851
852         return retval;
853 }
854
855 static int vidioc_g_audio(struct file *file, void *private_data,
856                           struct v4l2_audio *audio)
857 {
858         struct hdpvr_device *dev = video_drvdata(file);
859
860         audio->index = dev->options.audio_input;
861         audio->capability = V4L2_AUDCAP_STEREO;
862         strncpy(audio->name, audio_iname[audio->index], sizeof(audio->name));
863         audio->name[sizeof(audio->name) - 1] = '\0';
864         return 0;
865 }
866
867 static int hdpvr_try_ctrl(struct v4l2_ctrl *ctrl)
868 {
869         struct hdpvr_device *dev =
870                 container_of(ctrl->handler, struct hdpvr_device, hdl);
871
872         switch (ctrl->id) {
873         case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
874                 if (ctrl->val == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR &&
875                     dev->video_bitrate->val >= dev->video_bitrate_peak->val)
876                         dev->video_bitrate_peak->val =
877                                         dev->video_bitrate->val + 100000;
878                 break;
879         }
880         return 0;
881 }
882
883 static int hdpvr_s_ctrl(struct v4l2_ctrl *ctrl)
884 {
885         struct hdpvr_device *dev =
886                 container_of(ctrl->handler, struct hdpvr_device, hdl);
887         struct hdpvr_options *opt = &dev->options;
888         int ret = -EINVAL;
889
890         switch (ctrl->id) {
891         case V4L2_CID_BRIGHTNESS:
892                 ret = hdpvr_config_call(dev, CTRL_BRIGHTNESS, ctrl->val);
893                 if (ret)
894                         break;
895                 dev->options.brightness = ctrl->val;
896                 return 0;
897         case V4L2_CID_CONTRAST:
898                 ret = hdpvr_config_call(dev, CTRL_CONTRAST, ctrl->val);
899                 if (ret)
900                         break;
901                 dev->options.contrast = ctrl->val;
902                 return 0;
903         case V4L2_CID_SATURATION:
904                 ret = hdpvr_config_call(dev, CTRL_SATURATION, ctrl->val);
905                 if (ret)
906                         break;
907                 dev->options.saturation = ctrl->val;
908                 return 0;
909         case V4L2_CID_HUE:
910                 ret = hdpvr_config_call(dev, CTRL_HUE, ctrl->val);
911                 if (ret)
912                         break;
913                 dev->options.hue = ctrl->val;
914                 return 0;
915         case V4L2_CID_SHARPNESS:
916                 ret = hdpvr_config_call(dev, CTRL_SHARPNESS, ctrl->val);
917                 if (ret)
918                         break;
919                 dev->options.sharpness = ctrl->val;
920                 return 0;
921         case V4L2_CID_MPEG_AUDIO_ENCODING:
922                 if (dev->flags & HDPVR_FLAG_AC3_CAP) {
923                         opt->audio_codec = ctrl->val;
924                         return hdpvr_set_audio(dev, opt->audio_input + 1,
925                                               opt->audio_codec);
926                 }
927                 return 0;
928         case V4L2_CID_MPEG_VIDEO_ENCODING:
929                 return 0;
930 /*      case V4L2_CID_MPEG_VIDEO_B_FRAMES: */
931 /*              if (ctrl->value == 0 && !(opt->gop_mode & 0x2)) { */
932 /*                      opt->gop_mode |= 0x2; */
933 /*                      hdpvr_config_call(dev, CTRL_GOP_MODE_VALUE, */
934 /*                                        opt->gop_mode); */
935 /*              } */
936 /*              if (ctrl->value == 128 && opt->gop_mode & 0x2) { */
937 /*                      opt->gop_mode &= ~0x2; */
938 /*                      hdpvr_config_call(dev, CTRL_GOP_MODE_VALUE, */
939 /*                                        opt->gop_mode); */
940 /*              } */
941 /*              break; */
942         case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: {
943                 uint peak_bitrate = dev->video_bitrate_peak->val / 100000;
944                 uint bitrate = dev->video_bitrate->val / 100000;
945
946                 if (ctrl->is_new) {
947                         if (ctrl->val == V4L2_MPEG_VIDEO_BITRATE_MODE_CBR)
948                                 opt->bitrate_mode = HDPVR_CONSTANT;
949                         else
950                                 opt->bitrate_mode = HDPVR_VARIABLE_AVERAGE;
951                         hdpvr_config_call(dev, CTRL_BITRATE_MODE_VALUE,
952                                           opt->bitrate_mode);
953                         v4l2_ctrl_activate(dev->video_bitrate_peak,
954                                 ctrl->val != V4L2_MPEG_VIDEO_BITRATE_MODE_CBR);
955                 }
956
957                 if (dev->video_bitrate_peak->is_new ||
958                     dev->video_bitrate->is_new) {
959                         opt->bitrate = bitrate;
960                         opt->peak_bitrate = peak_bitrate;
961                         hdpvr_set_bitrate(dev);
962                 }
963                 return 0;
964         }
965         case V4L2_CID_MPEG_STREAM_TYPE:
966                 return 0;
967         default:
968                 break;
969         }
970         return ret;
971 }
972
973 static int vidioc_enum_fmt_vid_cap(struct file *file, void *private_data,
974                                     struct v4l2_fmtdesc *f)
975 {
976         if (f->index != 0)
977                 return -EINVAL;
978
979         f->flags = V4L2_FMT_FLAG_COMPRESSED;
980         strncpy(f->description, "MPEG2-TS with AVC/AAC streams", 32);
981         f->pixelformat = V4L2_PIX_FMT_MPEG;
982
983         return 0;
984 }
985
986 static int vidioc_g_fmt_vid_cap(struct file *file, void *_fh,
987                                 struct v4l2_format *f)
988 {
989         struct hdpvr_device *dev = video_drvdata(file);
990         struct hdpvr_fh *fh = _fh;
991         int ret;
992
993         /*
994          * The original driver would always returns the current detected
995          * resolution as the format (and EFAULT if it couldn't be detected).
996          * With the introduction of VIDIOC_QUERY_DV_TIMINGS there is now a
997          * better way of doing this, but to stay compatible with existing
998          * applications we assume legacy mode every time an application opens
999          * the device. Only if one of the new DV_TIMINGS ioctls is called
1000          * will the filehandle go into 'normal' mode where g_fmt returns the
1001          * last set format.
1002          */
1003         if (fh->legacy_mode) {
1004                 struct hdpvr_video_info vid_info;
1005
1006                 ret = get_video_info(dev, &vid_info);
1007                 if (ret < 0)
1008                         return ret;
1009                 if (!vid_info.valid)
1010                         return -EFAULT;
1011                 f->fmt.pix.width = vid_info.width;
1012                 f->fmt.pix.height = vid_info.height;
1013         } else {
1014                 f->fmt.pix.width = dev->width;
1015                 f->fmt.pix.height = dev->height;
1016         }
1017         f->fmt.pix.pixelformat  = V4L2_PIX_FMT_MPEG;
1018         f->fmt.pix.sizeimage    = dev->bulk_in_size;
1019         f->fmt.pix.bytesperline = 0;
1020         if (f->fmt.pix.width == 720) {
1021                 /* SDTV formats */
1022                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1023                 f->fmt.pix.field = V4L2_FIELD_INTERLACED;
1024         } else {
1025                 /* HDTV formats */
1026                 f->fmt.pix.colorspace = V4L2_COLORSPACE_REC709;
1027                 f->fmt.pix.field = V4L2_FIELD_NONE;
1028         }
1029         return 0;
1030 }
1031
1032 static int vidioc_encoder_cmd(struct file *filp, void *priv,
1033                                struct v4l2_encoder_cmd *a)
1034 {
1035         struct hdpvr_device *dev = video_drvdata(filp);
1036         int res = 0;
1037
1038         mutex_lock(&dev->io_mutex);
1039         a->flags = 0;
1040
1041         switch (a->cmd) {
1042         case V4L2_ENC_CMD_START:
1043                 if (dev->owner && filp->private_data != dev->owner) {
1044                         res = -EBUSY;
1045                         break;
1046                 }
1047                 if (dev->status == STATUS_STREAMING)
1048                         break;
1049                 res = hdpvr_start_streaming(dev);
1050                 if (!res)
1051                         dev->owner = filp->private_data;
1052                 else
1053                         dev->status = STATUS_IDLE;
1054                 break;
1055         case V4L2_ENC_CMD_STOP:
1056                 if (dev->owner && filp->private_data != dev->owner) {
1057                         res = -EBUSY;
1058                         break;
1059                 }
1060                 if (dev->status == STATUS_IDLE)
1061                         break;
1062                 res = hdpvr_stop_streaming(dev);
1063                 if (!res)
1064                         dev->owner = NULL;
1065                 break;
1066         default:
1067                 v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
1068                          "Unsupported encoder cmd %d\n", a->cmd);
1069                 res = -EINVAL;
1070                 break;
1071         }
1072
1073         mutex_unlock(&dev->io_mutex);
1074         return res;
1075 }
1076
1077 static int vidioc_try_encoder_cmd(struct file *filp, void *priv,
1078                                         struct v4l2_encoder_cmd *a)
1079 {
1080         a->flags = 0;
1081         switch (a->cmd) {
1082         case V4L2_ENC_CMD_START:
1083         case V4L2_ENC_CMD_STOP:
1084                 return 0;
1085         default:
1086                 return -EINVAL;
1087         }
1088 }
1089
1090 static const struct v4l2_ioctl_ops hdpvr_ioctl_ops = {
1091         .vidioc_querycap        = vidioc_querycap,
1092         .vidioc_s_std           = vidioc_s_std,
1093         .vidioc_g_std           = vidioc_g_std,
1094         .vidioc_querystd        = vidioc_querystd,
1095         .vidioc_s_dv_timings    = vidioc_s_dv_timings,
1096         .vidioc_g_dv_timings    = vidioc_g_dv_timings,
1097         .vidioc_query_dv_timings= vidioc_query_dv_timings,
1098         .vidioc_enum_dv_timings = vidioc_enum_dv_timings,
1099         .vidioc_dv_timings_cap  = vidioc_dv_timings_cap,
1100         .vidioc_enum_input      = vidioc_enum_input,
1101         .vidioc_g_input         = vidioc_g_input,
1102         .vidioc_s_input         = vidioc_s_input,
1103         .vidioc_enumaudio       = vidioc_enumaudio,
1104         .vidioc_g_audio         = vidioc_g_audio,
1105         .vidioc_s_audio         = vidioc_s_audio,
1106         .vidioc_enum_fmt_vid_cap= vidioc_enum_fmt_vid_cap,
1107         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1108         .vidioc_s_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1109         .vidioc_try_fmt_vid_cap = vidioc_g_fmt_vid_cap,
1110         .vidioc_encoder_cmd     = vidioc_encoder_cmd,
1111         .vidioc_try_encoder_cmd = vidioc_try_encoder_cmd,
1112         .vidioc_log_status      = v4l2_ctrl_log_status,
1113         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1114         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1115 };
1116
1117 static void hdpvr_device_release(struct video_device *vdev)
1118 {
1119         struct hdpvr_device *dev = video_get_drvdata(vdev);
1120
1121         hdpvr_delete(dev);
1122         mutex_lock(&dev->io_mutex);
1123         flush_work(&dev->worker);
1124         mutex_unlock(&dev->io_mutex);
1125
1126         v4l2_device_unregister(&dev->v4l2_dev);
1127         v4l2_ctrl_handler_free(&dev->hdl);
1128
1129         /* deregister I2C adapter */
1130 #if IS_ENABLED(CONFIG_I2C)
1131         mutex_lock(&dev->i2c_mutex);
1132         i2c_del_adapter(&dev->i2c_adapter);
1133         mutex_unlock(&dev->i2c_mutex);
1134 #endif /* CONFIG_I2C */
1135
1136         kfree(dev->usbc_buf);
1137         kfree(dev);
1138 }
1139
1140 static const struct video_device hdpvr_video_template = {
1141         .fops                   = &hdpvr_fops,
1142         .release                = hdpvr_device_release,
1143         .ioctl_ops              = &hdpvr_ioctl_ops,
1144         .tvnorms                = V4L2_STD_ALL,
1145 };
1146
1147 static const struct v4l2_ctrl_ops hdpvr_ctrl_ops = {
1148         .try_ctrl = hdpvr_try_ctrl,
1149         .s_ctrl = hdpvr_s_ctrl,
1150 };
1151
1152 int hdpvr_register_videodev(struct hdpvr_device *dev, struct device *parent,
1153                             int devnum)
1154 {
1155         struct v4l2_ctrl_handler *hdl = &dev->hdl;
1156         bool ac3 = dev->flags & HDPVR_FLAG_AC3_CAP;
1157         int res;
1158
1159         dev->cur_std = V4L2_STD_525_60;
1160         dev->width = 720;
1161         dev->height = 480;
1162         dev->cur_dv_timings = hdpvr_dv_timings[HDPVR_DEF_DV_TIMINGS_IDX];
1163         v4l2_ctrl_handler_init(hdl, 11);
1164         if (dev->fw_ver > 0x15) {
1165                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1166                         V4L2_CID_BRIGHTNESS, 0x0, 0xff, 1, 0x80);
1167                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1168                         V4L2_CID_CONTRAST, 0x0, 0xff, 1, 0x40);
1169                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1170                         V4L2_CID_SATURATION, 0x0, 0xff, 1, 0x40);
1171                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1172                         V4L2_CID_HUE, 0x0, 0x1e, 1, 0xf);
1173                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1174                         V4L2_CID_SHARPNESS, 0x0, 0xff, 1, 0x80);
1175         } else {
1176                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1177                         V4L2_CID_BRIGHTNESS, 0x0, 0xff, 1, 0x86);
1178                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1179                         V4L2_CID_CONTRAST, 0x0, 0xff, 1, 0x80);
1180                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1181                         V4L2_CID_SATURATION, 0x0, 0xff, 1, 0x80);
1182                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1183                         V4L2_CID_HUE, 0x0, 0xff, 1, 0x80);
1184                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1185                         V4L2_CID_SHARPNESS, 0x0, 0xff, 1, 0x80);
1186         }
1187
1188         v4l2_ctrl_new_std_menu(hdl, &hdpvr_ctrl_ops,
1189                 V4L2_CID_MPEG_STREAM_TYPE,
1190                 V4L2_MPEG_STREAM_TYPE_MPEG2_TS,
1191                 0x1, V4L2_MPEG_STREAM_TYPE_MPEG2_TS);
1192         v4l2_ctrl_new_std_menu(hdl, &hdpvr_ctrl_ops,
1193                 V4L2_CID_MPEG_AUDIO_ENCODING,
1194                 ac3 ? V4L2_MPEG_AUDIO_ENCODING_AC3 : V4L2_MPEG_AUDIO_ENCODING_AAC,
1195                 0x7, ac3 ? dev->options.audio_codec : V4L2_MPEG_AUDIO_ENCODING_AAC);
1196         v4l2_ctrl_new_std_menu(hdl, &hdpvr_ctrl_ops,
1197                 V4L2_CID_MPEG_VIDEO_ENCODING,
1198                 V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC, 0x3,
1199                 V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC);
1200
1201         dev->video_mode = v4l2_ctrl_new_std_menu(hdl, &hdpvr_ctrl_ops,
1202                 V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
1203                 V4L2_MPEG_VIDEO_BITRATE_MODE_CBR, 0,
1204                 V4L2_MPEG_VIDEO_BITRATE_MODE_CBR);
1205
1206         dev->video_bitrate = v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1207                 V4L2_CID_MPEG_VIDEO_BITRATE,
1208                 1000000, 13500000, 100000, 6500000);
1209         dev->video_bitrate_peak = v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1210                 V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
1211                 1100000, 20200000, 100000, 9000000);
1212         dev->v4l2_dev.ctrl_handler = hdl;
1213         if (hdl->error) {
1214                 res = hdl->error;
1215                 v4l2_err(&dev->v4l2_dev, "Could not register controls\n");
1216                 goto error;
1217         }
1218         v4l2_ctrl_cluster(3, &dev->video_mode);
1219         res = v4l2_ctrl_handler_setup(hdl);
1220         if (res < 0) {
1221                 v4l2_err(&dev->v4l2_dev, "Could not setup controls\n");
1222                 goto error;
1223         }
1224
1225         /* setup and register video device */
1226         dev->video_dev = hdpvr_video_template;
1227         strcpy(dev->video_dev.name, "Hauppauge HD PVR");
1228         dev->video_dev.v4l2_dev = &dev->v4l2_dev;
1229         video_set_drvdata(&dev->video_dev, dev);
1230
1231         res = video_register_device(&dev->video_dev, VFL_TYPE_GRABBER, devnum);
1232         if (res < 0) {
1233                 v4l2_err(&dev->v4l2_dev, "video_device registration failed\n");
1234                 goto error;
1235         }
1236
1237         return 0;
1238 error:
1239         v4l2_ctrl_handler_free(hdl);
1240         return res;
1241 }