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