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