ff358cbf6133a289c00e7b01b5c8ff2df4c19272
[cascardo/linux.git] / drivers / media / video / uvc / uvc_v4l2.c
1 /*
2  *      uvc_v4l2.c  --  USB Video Class driver - V4L2 API
3  *
4  *      Copyright (C) 2005-2010
5  *          Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6  *
7  *      This program is free software; you can redistribute it and/or modify
8  *      it under the terms of the GNU General Public License as published by
9  *      the Free Software Foundation; either version 2 of the License, or
10  *      (at your option) any later version.
11  *
12  */
13
14 #include <linux/compat.h>
15 #include <linux/kernel.h>
16 #include <linux/version.h>
17 #include <linux/list.h>
18 #include <linux/module.h>
19 #include <linux/slab.h>
20 #include <linux/usb.h>
21 #include <linux/videodev2.h>
22 #include <linux/vmalloc.h>
23 #include <linux/mm.h>
24 #include <linux/wait.h>
25 #include <linux/atomic.h>
26
27 #include <media/v4l2-common.h>
28 #include <media/v4l2-ioctl.h>
29
30 #include "uvcvideo.h"
31
32 /* ------------------------------------------------------------------------
33  * UVC ioctls
34  */
35 static int uvc_ioctl_ctrl_map(struct uvc_video_chain *chain,
36         struct uvc_xu_control_mapping *xmap)
37 {
38         struct uvc_control_mapping *map;
39         unsigned int size;
40         int ret;
41
42         map = kzalloc(sizeof *map, GFP_KERNEL);
43         if (map == NULL)
44                 return -ENOMEM;
45
46         map->id = xmap->id;
47         memcpy(map->name, xmap->name, sizeof map->name);
48         memcpy(map->entity, xmap->entity, sizeof map->entity);
49         map->selector = xmap->selector;
50         map->size = xmap->size;
51         map->offset = xmap->offset;
52         map->v4l2_type = xmap->v4l2_type;
53         map->data_type = xmap->data_type;
54
55         switch (xmap->v4l2_type) {
56         case V4L2_CTRL_TYPE_INTEGER:
57         case V4L2_CTRL_TYPE_BOOLEAN:
58         case V4L2_CTRL_TYPE_BUTTON:
59                 break;
60
61         case V4L2_CTRL_TYPE_MENU:
62                 /* Prevent excessive memory consumption, as well as integer
63                  * overflows.
64                  */
65                 if (xmap->menu_count == 0 ||
66                     xmap->menu_count > UVC_MAX_CONTROL_MENU_ENTRIES) {
67                         ret = -EINVAL;
68                         goto done;
69                 }
70
71                 size = xmap->menu_count * sizeof(*map->menu_info);
72                 map->menu_info = kmalloc(size, GFP_KERNEL);
73                 if (map->menu_info == NULL) {
74                         ret = -ENOMEM;
75                         goto done;
76                 }
77
78                 if (copy_from_user(map->menu_info, xmap->menu_info, size)) {
79                         ret = -EFAULT;
80                         goto done;
81                 }
82
83                 map->menu_count = xmap->menu_count;
84                 break;
85
86         default:
87                 uvc_trace(UVC_TRACE_CONTROL, "Unsupported V4L2 control type "
88                           "%u.\n", xmap->v4l2_type);
89                 ret = -ENOTTY;
90                 goto done;
91         }
92
93         ret = uvc_ctrl_add_mapping(chain, map);
94
95 done:
96         kfree(map->menu_info);
97         kfree(map);
98
99         return ret;
100 }
101
102 /* ------------------------------------------------------------------------
103  * V4L2 interface
104  */
105
106 /*
107  * Find the frame interval closest to the requested frame interval for the
108  * given frame format and size. This should be done by the device as part of
109  * the Video Probe and Commit negotiation, but some hardware don't implement
110  * that feature.
111  */
112 static __u32 uvc_try_frame_interval(struct uvc_frame *frame, __u32 interval)
113 {
114         unsigned int i;
115
116         if (frame->bFrameIntervalType) {
117                 __u32 best = -1, dist;
118
119                 for (i = 0; i < frame->bFrameIntervalType; ++i) {
120                         dist = interval > frame->dwFrameInterval[i]
121                              ? interval - frame->dwFrameInterval[i]
122                              : frame->dwFrameInterval[i] - interval;
123
124                         if (dist > best)
125                                 break;
126
127                         best = dist;
128                 }
129
130                 interval = frame->dwFrameInterval[i-1];
131         } else {
132                 const __u32 min = frame->dwFrameInterval[0];
133                 const __u32 max = frame->dwFrameInterval[1];
134                 const __u32 step = frame->dwFrameInterval[2];
135
136                 interval = min + (interval - min + step/2) / step * step;
137                 if (interval > max)
138                         interval = max;
139         }
140
141         return interval;
142 }
143
144 static int uvc_v4l2_try_format(struct uvc_streaming *stream,
145         struct v4l2_format *fmt, struct uvc_streaming_control *probe,
146         struct uvc_format **uvc_format, struct uvc_frame **uvc_frame)
147 {
148         struct uvc_format *format = NULL;
149         struct uvc_frame *frame = NULL;
150         __u16 rw, rh;
151         unsigned int d, maxd;
152         unsigned int i;
153         __u32 interval;
154         int ret = 0;
155         __u8 *fcc;
156
157         if (fmt->type != stream->type)
158                 return -EINVAL;
159
160         fcc = (__u8 *)&fmt->fmt.pix.pixelformat;
161         uvc_trace(UVC_TRACE_FORMAT, "Trying format 0x%08x (%c%c%c%c): %ux%u.\n",
162                         fmt->fmt.pix.pixelformat,
163                         fcc[0], fcc[1], fcc[2], fcc[3],
164                         fmt->fmt.pix.width, fmt->fmt.pix.height);
165
166         /* Check if the hardware supports the requested format. */
167         for (i = 0; i < stream->nformats; ++i) {
168                 format = &stream->format[i];
169                 if (format->fcc == fmt->fmt.pix.pixelformat)
170                         break;
171         }
172
173         if (format == NULL || format->fcc != fmt->fmt.pix.pixelformat) {
174                 uvc_trace(UVC_TRACE_FORMAT, "Unsupported format 0x%08x.\n",
175                                 fmt->fmt.pix.pixelformat);
176                 return -EINVAL;
177         }
178
179         /* Find the closest image size. The distance between image sizes is
180          * the size in pixels of the non-overlapping regions between the
181          * requested size and the frame-specified size.
182          */
183         rw = fmt->fmt.pix.width;
184         rh = fmt->fmt.pix.height;
185         maxd = (unsigned int)-1;
186
187         for (i = 0; i < format->nframes; ++i) {
188                 __u16 w = format->frame[i].wWidth;
189                 __u16 h = format->frame[i].wHeight;
190
191                 d = min(w, rw) * min(h, rh);
192                 d = w*h + rw*rh - 2*d;
193                 if (d < maxd) {
194                         maxd = d;
195                         frame = &format->frame[i];
196                 }
197
198                 if (maxd == 0)
199                         break;
200         }
201
202         if (frame == NULL) {
203                 uvc_trace(UVC_TRACE_FORMAT, "Unsupported size %ux%u.\n",
204                                 fmt->fmt.pix.width, fmt->fmt.pix.height);
205                 return -EINVAL;
206         }
207
208         /* Use the default frame interval. */
209         interval = frame->dwDefaultFrameInterval;
210         uvc_trace(UVC_TRACE_FORMAT, "Using default frame interval %u.%u us "
211                 "(%u.%u fps).\n", interval/10, interval%10, 10000000/interval,
212                 (100000000/interval)%10);
213
214         /* Set the format index, frame index and frame interval. */
215         memset(probe, 0, sizeof *probe);
216         probe->bmHint = 1;      /* dwFrameInterval */
217         probe->bFormatIndex = format->index;
218         probe->bFrameIndex = frame->bFrameIndex;
219         probe->dwFrameInterval = uvc_try_frame_interval(frame, interval);
220         /* Some webcams stall the probe control set request when the
221          * dwMaxVideoFrameSize field is set to zero. The UVC specification
222          * clearly states that the field is read-only from the host, so this
223          * is a webcam bug. Set dwMaxVideoFrameSize to the value reported by
224          * the webcam to work around the problem.
225          *
226          * The workaround could probably be enabled for all webcams, so the
227          * quirk can be removed if needed. It's currently useful to detect
228          * webcam bugs and fix them before they hit the market (providing
229          * developers test their webcams with the Linux driver as well as with
230          * the Windows driver).
231          */
232         mutex_lock(&stream->mutex);
233         if (stream->dev->quirks & UVC_QUIRK_PROBE_EXTRAFIELDS)
234                 probe->dwMaxVideoFrameSize =
235                         stream->ctrl.dwMaxVideoFrameSize;
236
237         /* Probe the device. */
238         ret = uvc_probe_video(stream, probe);
239         mutex_unlock(&stream->mutex);
240         if (ret < 0)
241                 goto done;
242
243         fmt->fmt.pix.width = frame->wWidth;
244         fmt->fmt.pix.height = frame->wHeight;
245         fmt->fmt.pix.field = V4L2_FIELD_NONE;
246         fmt->fmt.pix.bytesperline = format->bpp * frame->wWidth / 8;
247         fmt->fmt.pix.sizeimage = probe->dwMaxVideoFrameSize;
248         fmt->fmt.pix.colorspace = format->colorspace;
249         fmt->fmt.pix.priv = 0;
250
251         if (uvc_format != NULL)
252                 *uvc_format = format;
253         if (uvc_frame != NULL)
254                 *uvc_frame = frame;
255
256 done:
257         return ret;
258 }
259
260 static int uvc_v4l2_get_format(struct uvc_streaming *stream,
261         struct v4l2_format *fmt)
262 {
263         struct uvc_format *format;
264         struct uvc_frame *frame;
265         int ret = 0;
266
267         if (fmt->type != stream->type)
268                 return -EINVAL;
269
270         mutex_lock(&stream->mutex);
271         format = stream->cur_format;
272         frame = stream->cur_frame;
273
274         if (format == NULL || frame == NULL) {
275                 ret = -EINVAL;
276                 goto done;
277         }
278
279         fmt->fmt.pix.pixelformat = format->fcc;
280         fmt->fmt.pix.width = frame->wWidth;
281         fmt->fmt.pix.height = frame->wHeight;
282         fmt->fmt.pix.field = V4L2_FIELD_NONE;
283         fmt->fmt.pix.bytesperline = format->bpp * frame->wWidth / 8;
284         fmt->fmt.pix.sizeimage = stream->ctrl.dwMaxVideoFrameSize;
285         fmt->fmt.pix.colorspace = format->colorspace;
286         fmt->fmt.pix.priv = 0;
287
288 done:
289         mutex_unlock(&stream->mutex);
290         return ret;
291 }
292
293 static int uvc_v4l2_set_format(struct uvc_streaming *stream,
294         struct v4l2_format *fmt)
295 {
296         struct uvc_streaming_control probe;
297         struct uvc_format *format;
298         struct uvc_frame *frame;
299         int ret;
300
301         if (fmt->type != stream->type)
302                 return -EINVAL;
303
304         ret = uvc_v4l2_try_format(stream, fmt, &probe, &format, &frame);
305         if (ret < 0)
306                 return ret;
307
308         mutex_lock(&stream->mutex);
309
310         if (uvc_queue_allocated(&stream->queue)) {
311                 ret = -EBUSY;
312                 goto done;
313         }
314
315         memcpy(&stream->ctrl, &probe, sizeof probe);
316         stream->cur_format = format;
317         stream->cur_frame = frame;
318
319 done:
320         mutex_unlock(&stream->mutex);
321         return ret;
322 }
323
324 static int uvc_v4l2_get_streamparm(struct uvc_streaming *stream,
325                 struct v4l2_streamparm *parm)
326 {
327         uint32_t numerator, denominator;
328
329         if (parm->type != stream->type)
330                 return -EINVAL;
331
332         mutex_lock(&stream->mutex);
333         numerator = stream->ctrl.dwFrameInterval;
334         mutex_unlock(&stream->mutex);
335
336         denominator = 10000000;
337         uvc_simplify_fraction(&numerator, &denominator, 8, 333);
338
339         memset(parm, 0, sizeof *parm);
340         parm->type = stream->type;
341
342         if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
343                 parm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
344                 parm->parm.capture.capturemode = 0;
345                 parm->parm.capture.timeperframe.numerator = numerator;
346                 parm->parm.capture.timeperframe.denominator = denominator;
347                 parm->parm.capture.extendedmode = 0;
348                 parm->parm.capture.readbuffers = 0;
349         } else {
350                 parm->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
351                 parm->parm.output.outputmode = 0;
352                 parm->parm.output.timeperframe.numerator = numerator;
353                 parm->parm.output.timeperframe.denominator = denominator;
354         }
355
356         return 0;
357 }
358
359 static int uvc_v4l2_set_streamparm(struct uvc_streaming *stream,
360                 struct v4l2_streamparm *parm)
361 {
362         struct uvc_streaming_control probe;
363         struct v4l2_fract timeperframe;
364         uint32_t interval;
365         int ret;
366
367         if (parm->type != stream->type)
368                 return -EINVAL;
369
370         if (parm->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
371                 timeperframe = parm->parm.capture.timeperframe;
372         else
373                 timeperframe = parm->parm.output.timeperframe;
374
375         interval = uvc_fraction_to_interval(timeperframe.numerator,
376                 timeperframe.denominator);
377         uvc_trace(UVC_TRACE_FORMAT, "Setting frame interval to %u/%u (%u).\n",
378                 timeperframe.numerator, timeperframe.denominator, interval);
379
380         mutex_lock(&stream->mutex);
381
382         if (uvc_queue_streaming(&stream->queue)) {
383                 mutex_unlock(&stream->mutex);
384                 return -EBUSY;
385         }
386
387         memcpy(&probe, &stream->ctrl, sizeof probe);
388         probe.dwFrameInterval =
389                 uvc_try_frame_interval(stream->cur_frame, interval);
390
391         /* Probe the device with the new settings. */
392         ret = uvc_probe_video(stream, &probe);
393         if (ret < 0) {
394                 mutex_unlock(&stream->mutex);
395                 return ret;
396         }
397
398         memcpy(&stream->ctrl, &probe, sizeof probe);
399         mutex_unlock(&stream->mutex);
400
401         /* Return the actual frame period. */
402         timeperframe.numerator = probe.dwFrameInterval;
403         timeperframe.denominator = 10000000;
404         uvc_simplify_fraction(&timeperframe.numerator,
405                 &timeperframe.denominator, 8, 333);
406
407         if (parm->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
408                 parm->parm.capture.timeperframe = timeperframe;
409         else
410                 parm->parm.output.timeperframe = timeperframe;
411
412         return 0;
413 }
414
415 /* ------------------------------------------------------------------------
416  * Privilege management
417  */
418
419 /*
420  * Privilege management is the multiple-open implementation basis. The current
421  * implementation is completely transparent for the end-user and doesn't
422  * require explicit use of the VIDIOC_G_PRIORITY and VIDIOC_S_PRIORITY ioctls.
423  * Those ioctls enable finer control on the device (by making possible for a
424  * user to request exclusive access to a device), but are not mature yet.
425  * Switching to the V4L2 priority mechanism might be considered in the future
426  * if this situation changes.
427  *
428  * Each open instance of a UVC device can either be in a privileged or
429  * unprivileged state. Only a single instance can be in a privileged state at
430  * a given time. Trying to perform an operation that requires privileges will
431  * automatically acquire the required privileges if possible, or return -EBUSY
432  * otherwise. Privileges are dismissed when closing the instance or when
433  * freeing the video buffers using VIDIOC_REQBUFS.
434  *
435  * Operations that require privileges are:
436  *
437  * - VIDIOC_S_INPUT
438  * - VIDIOC_S_PARM
439  * - VIDIOC_S_FMT
440  * - VIDIOC_REQBUFS
441  */
442 static int uvc_acquire_privileges(struct uvc_fh *handle)
443 {
444         /* Always succeed if the handle is already privileged. */
445         if (handle->state == UVC_HANDLE_ACTIVE)
446                 return 0;
447
448         /* Check if the device already has a privileged handle. */
449         if (atomic_inc_return(&handle->stream->active) != 1) {
450                 atomic_dec(&handle->stream->active);
451                 return -EBUSY;
452         }
453
454         handle->state = UVC_HANDLE_ACTIVE;
455         return 0;
456 }
457
458 static void uvc_dismiss_privileges(struct uvc_fh *handle)
459 {
460         if (handle->state == UVC_HANDLE_ACTIVE)
461                 atomic_dec(&handle->stream->active);
462
463         handle->state = UVC_HANDLE_PASSIVE;
464 }
465
466 static int uvc_has_privileges(struct uvc_fh *handle)
467 {
468         return handle->state == UVC_HANDLE_ACTIVE;
469 }
470
471 /* ------------------------------------------------------------------------
472  * V4L2 file operations
473  */
474
475 static int uvc_v4l2_open(struct file *file)
476 {
477         struct uvc_streaming *stream;
478         struct uvc_fh *handle;
479         unsigned long timeout;
480         int ret = 0;
481
482         uvc_trace(UVC_TRACE_CALLS, "uvc_v4l2_open\n");
483         stream = video_drvdata(file);
484
485         if (stream->dev->state & UVC_DEV_DISCONNECTED)
486                 return -ENODEV;
487
488         ret = usb_autopm_get_interface(stream->dev->intf);
489         if (ret < 0)
490                 return ret;
491
492         /* Create the device handle. */
493         handle = kzalloc(sizeof *handle, GFP_KERNEL);
494         if (handle == NULL) {
495                 usb_autopm_put_interface(stream->dev->intf);
496                 return -ENOMEM;
497         }
498
499         if (atomic_inc_return(&stream->dev->users) == 1) {
500                 timeout = jiffies + msecs_to_jiffies(UVC_STATUS_START_TIMEOUT);
501                 /* -EPERM means stop in progress, wait for completion */
502                 do {
503                         ret = uvc_status_start(stream->dev);
504                         if (ret == -EPERM)
505                                 usleep_range(5000, 6000);
506                 } while (ret == -EPERM && time_before(jiffies, timeout));
507
508                 if (ret < 0) {
509                         usb_autopm_put_interface(stream->dev->intf);
510                         atomic_dec(&stream->dev->users);
511                         kfree(handle);
512                         return ret;
513                 }
514         }
515
516         handle->chain = stream->chain;
517         handle->stream = stream;
518         handle->state = UVC_HANDLE_PASSIVE;
519         file->private_data = handle;
520
521         return 0;
522 }
523
524 static int uvc_v4l2_release(struct file *file)
525 {
526         struct uvc_fh *handle = file->private_data;
527         struct uvc_streaming *stream = handle->stream;
528
529         uvc_trace(UVC_TRACE_CALLS, "uvc_v4l2_release\n");
530
531         /* Only free resources if this is a privileged handle. */
532         if (uvc_has_privileges(handle)) {
533                 uvc_video_enable(stream, 0);
534                 uvc_free_buffers(&stream->queue);
535         }
536
537         /* Release the file handle. */
538         uvc_dismiss_privileges(handle);
539         kfree(handle);
540         file->private_data = NULL;
541
542         if (atomic_dec_return(&stream->dev->users) == 0)
543                 uvc_status_stop(stream->dev);
544
545         usb_autopm_put_interface(stream->dev->intf);
546         return 0;
547 }
548
549 static long uvc_v4l2_do_ioctl(struct file *file, unsigned int cmd, void *arg)
550 {
551         struct video_device *vdev = video_devdata(file);
552         struct uvc_fh *handle = file->private_data;
553         struct uvc_video_chain *chain = handle->chain;
554         struct uvc_streaming *stream = handle->stream;
555         long ret = 0;
556
557         switch (cmd) {
558         /* Query capabilities */
559         case VIDIOC_QUERYCAP:
560         {
561                 struct v4l2_capability *cap = arg;
562
563                 memset(cap, 0, sizeof *cap);
564                 strlcpy(cap->driver, "uvcvideo", sizeof cap->driver);
565                 strlcpy(cap->card, vdev->name, sizeof cap->card);
566                 usb_make_path(stream->dev->udev,
567                               cap->bus_info, sizeof(cap->bus_info));
568                 cap->version = LINUX_VERSION_CODE;
569                 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
570                         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
571                                           | V4L2_CAP_STREAMING;
572                 else
573                         cap->capabilities = V4L2_CAP_VIDEO_OUTPUT
574                                           | V4L2_CAP_STREAMING;
575                 break;
576         }
577
578         /* Get, Set & Query control */
579         case VIDIOC_QUERYCTRL:
580                 return uvc_query_v4l2_ctrl(chain, arg);
581
582         case VIDIOC_G_CTRL:
583         {
584                 struct v4l2_control *ctrl = arg;
585                 struct v4l2_ext_control xctrl;
586
587                 memset(&xctrl, 0, sizeof xctrl);
588                 xctrl.id = ctrl->id;
589
590                 ret = uvc_ctrl_begin(chain);
591                 if (ret < 0)
592                         return ret;
593
594                 ret = uvc_ctrl_get(chain, &xctrl);
595                 uvc_ctrl_rollback(chain);
596                 if (ret >= 0)
597                         ctrl->value = xctrl.value;
598                 break;
599         }
600
601         case VIDIOC_S_CTRL:
602         {
603                 struct v4l2_control *ctrl = arg;
604                 struct v4l2_ext_control xctrl;
605
606                 memset(&xctrl, 0, sizeof xctrl);
607                 xctrl.id = ctrl->id;
608                 xctrl.value = ctrl->value;
609
610                 ret = uvc_ctrl_begin(chain);
611                 if (ret < 0)
612                         return ret;
613
614                 ret = uvc_ctrl_set(chain, &xctrl);
615                 if (ret < 0) {
616                         uvc_ctrl_rollback(chain);
617                         return ret;
618                 }
619                 ret = uvc_ctrl_commit(chain);
620                 if (ret == 0)
621                         ctrl->value = xctrl.value;
622                 break;
623         }
624
625         case VIDIOC_QUERYMENU:
626                 return uvc_query_v4l2_menu(chain, arg);
627
628         case VIDIOC_G_EXT_CTRLS:
629         {
630                 struct v4l2_ext_controls *ctrls = arg;
631                 struct v4l2_ext_control *ctrl = ctrls->controls;
632                 unsigned int i;
633
634                 ret = uvc_ctrl_begin(chain);
635                 if (ret < 0)
636                         return ret;
637
638                 for (i = 0; i < ctrls->count; ++ctrl, ++i) {
639                         ret = uvc_ctrl_get(chain, ctrl);
640                         if (ret < 0) {
641                                 uvc_ctrl_rollback(chain);
642                                 ctrls->error_idx = i;
643                                 return ret;
644                         }
645                 }
646                 ctrls->error_idx = 0;
647                 ret = uvc_ctrl_rollback(chain);
648                 break;
649         }
650
651         case VIDIOC_S_EXT_CTRLS:
652         case VIDIOC_TRY_EXT_CTRLS:
653         {
654                 struct v4l2_ext_controls *ctrls = arg;
655                 struct v4l2_ext_control *ctrl = ctrls->controls;
656                 unsigned int i;
657
658                 ret = uvc_ctrl_begin(chain);
659                 if (ret < 0)
660                         return ret;
661
662                 for (i = 0; i < ctrls->count; ++ctrl, ++i) {
663                         ret = uvc_ctrl_set(chain, ctrl);
664                         if (ret < 0) {
665                                 uvc_ctrl_rollback(chain);
666                                 ctrls->error_idx = i;
667                                 return ret;
668                         }
669                 }
670
671                 ctrls->error_idx = 0;
672
673                 if (cmd == VIDIOC_S_EXT_CTRLS)
674                         ret = uvc_ctrl_commit(chain);
675                 else
676                         ret = uvc_ctrl_rollback(chain);
677                 break;
678         }
679
680         /* Get, Set & Enum input */
681         case VIDIOC_ENUMINPUT:
682         {
683                 const struct uvc_entity *selector = chain->selector;
684                 struct v4l2_input *input = arg;
685                 struct uvc_entity *iterm = NULL;
686                 u32 index = input->index;
687                 int pin = 0;
688
689                 if (selector == NULL ||
690                     (chain->dev->quirks & UVC_QUIRK_IGNORE_SELECTOR_UNIT)) {
691                         if (index != 0)
692                                 return -EINVAL;
693                         list_for_each_entry(iterm, &chain->entities, chain) {
694                                 if (UVC_ENTITY_IS_ITERM(iterm))
695                                         break;
696                         }
697                         pin = iterm->id;
698                 } else if (pin < selector->bNrInPins) {
699                         pin = selector->baSourceID[index];
700                         list_for_each_entry(iterm, &chain->entities, chain) {
701                                 if (!UVC_ENTITY_IS_ITERM(iterm))
702                                         continue;
703                                 if (iterm->id == pin)
704                                         break;
705                         }
706                 }
707
708                 if (iterm == NULL || iterm->id != pin)
709                         return -EINVAL;
710
711                 memset(input, 0, sizeof *input);
712                 input->index = index;
713                 strlcpy(input->name, iterm->name, sizeof input->name);
714                 if (UVC_ENTITY_TYPE(iterm) == UVC_ITT_CAMERA)
715                         input->type = V4L2_INPUT_TYPE_CAMERA;
716                 break;
717         }
718
719         case VIDIOC_G_INPUT:
720         {
721                 u8 input;
722
723                 if (chain->selector == NULL ||
724                     (chain->dev->quirks & UVC_QUIRK_IGNORE_SELECTOR_UNIT)) {
725                         *(int *)arg = 0;
726                         break;
727                 }
728
729                 ret = uvc_query_ctrl(chain->dev, UVC_GET_CUR,
730                         chain->selector->id, chain->dev->intfnum,
731                         UVC_SU_INPUT_SELECT_CONTROL, &input, 1);
732                 if (ret < 0)
733                         return ret;
734
735                 *(int *)arg = input - 1;
736                 break;
737         }
738
739         case VIDIOC_S_INPUT:
740         {
741                 u32 input = *(u32 *)arg + 1;
742
743                 if ((ret = uvc_acquire_privileges(handle)) < 0)
744                         return ret;
745
746                 if (chain->selector == NULL ||
747                     (chain->dev->quirks & UVC_QUIRK_IGNORE_SELECTOR_UNIT)) {
748                         if (input != 1)
749                                 return -EINVAL;
750                         break;
751                 }
752
753                 if (input == 0 || input > chain->selector->bNrInPins)
754                         return -EINVAL;
755
756                 return uvc_query_ctrl(chain->dev, UVC_SET_CUR,
757                         chain->selector->id, chain->dev->intfnum,
758                         UVC_SU_INPUT_SELECT_CONTROL, &input, 1);
759         }
760
761         /* Try, Get, Set & Enum format */
762         case VIDIOC_ENUM_FMT:
763         {
764                 struct v4l2_fmtdesc *fmt = arg;
765                 struct uvc_format *format;
766                 enum v4l2_buf_type type = fmt->type;
767                 __u32 index = fmt->index;
768
769                 if (fmt->type != stream->type ||
770                     fmt->index >= stream->nformats)
771                         return -EINVAL;
772
773                 memset(fmt, 0, sizeof(*fmt));
774                 fmt->index = index;
775                 fmt->type = type;
776
777                 format = &stream->format[fmt->index];
778                 fmt->flags = 0;
779                 if (format->flags & UVC_FMT_FLAG_COMPRESSED)
780                         fmt->flags |= V4L2_FMT_FLAG_COMPRESSED;
781                 strlcpy(fmt->description, format->name,
782                         sizeof fmt->description);
783                 fmt->description[sizeof fmt->description - 1] = 0;
784                 fmt->pixelformat = format->fcc;
785                 break;
786         }
787
788         case VIDIOC_TRY_FMT:
789         {
790                 struct uvc_streaming_control probe;
791
792                 return uvc_v4l2_try_format(stream, arg, &probe, NULL, NULL);
793         }
794
795         case VIDIOC_S_FMT:
796                 if ((ret = uvc_acquire_privileges(handle)) < 0)
797                         return ret;
798
799                 return uvc_v4l2_set_format(stream, arg);
800
801         case VIDIOC_G_FMT:
802                 return uvc_v4l2_get_format(stream, arg);
803
804         /* Frame size enumeration */
805         case VIDIOC_ENUM_FRAMESIZES:
806         {
807                 struct v4l2_frmsizeenum *fsize = arg;
808                 struct uvc_format *format = NULL;
809                 struct uvc_frame *frame;
810                 int i;
811
812                 /* Look for the given pixel format */
813                 for (i = 0; i < stream->nformats; i++) {
814                         if (stream->format[i].fcc ==
815                                         fsize->pixel_format) {
816                                 format = &stream->format[i];
817                                 break;
818                         }
819                 }
820                 if (format == NULL)
821                         return -EINVAL;
822
823                 if (fsize->index >= format->nframes)
824                         return -EINVAL;
825
826                 frame = &format->frame[fsize->index];
827                 fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
828                 fsize->discrete.width = frame->wWidth;
829                 fsize->discrete.height = frame->wHeight;
830                 break;
831         }
832
833         /* Frame interval enumeration */
834         case VIDIOC_ENUM_FRAMEINTERVALS:
835         {
836                 struct v4l2_frmivalenum *fival = arg;
837                 struct uvc_format *format = NULL;
838                 struct uvc_frame *frame = NULL;
839                 int i;
840
841                 /* Look for the given pixel format and frame size */
842                 for (i = 0; i < stream->nformats; i++) {
843                         if (stream->format[i].fcc ==
844                                         fival->pixel_format) {
845                                 format = &stream->format[i];
846                                 break;
847                         }
848                 }
849                 if (format == NULL)
850                         return -EINVAL;
851
852                 for (i = 0; i < format->nframes; i++) {
853                         if (format->frame[i].wWidth == fival->width &&
854                             format->frame[i].wHeight == fival->height) {
855                                 frame = &format->frame[i];
856                                 break;
857                         }
858                 }
859                 if (frame == NULL)
860                         return -EINVAL;
861
862                 if (frame->bFrameIntervalType) {
863                         if (fival->index >= frame->bFrameIntervalType)
864                                 return -EINVAL;
865
866                         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
867                         fival->discrete.numerator =
868                                 frame->dwFrameInterval[fival->index];
869                         fival->discrete.denominator = 10000000;
870                         uvc_simplify_fraction(&fival->discrete.numerator,
871                                 &fival->discrete.denominator, 8, 333);
872                 } else {
873                         fival->type = V4L2_FRMIVAL_TYPE_STEPWISE;
874                         fival->stepwise.min.numerator =
875                                 frame->dwFrameInterval[0];
876                         fival->stepwise.min.denominator = 10000000;
877                         fival->stepwise.max.numerator =
878                                 frame->dwFrameInterval[1];
879                         fival->stepwise.max.denominator = 10000000;
880                         fival->stepwise.step.numerator =
881                                 frame->dwFrameInterval[2];
882                         fival->stepwise.step.denominator = 10000000;
883                         uvc_simplify_fraction(&fival->stepwise.min.numerator,
884                                 &fival->stepwise.min.denominator, 8, 333);
885                         uvc_simplify_fraction(&fival->stepwise.max.numerator,
886                                 &fival->stepwise.max.denominator, 8, 333);
887                         uvc_simplify_fraction(&fival->stepwise.step.numerator,
888                                 &fival->stepwise.step.denominator, 8, 333);
889                 }
890                 break;
891         }
892
893         /* Get & Set streaming parameters */
894         case VIDIOC_G_PARM:
895                 return uvc_v4l2_get_streamparm(stream, arg);
896
897         case VIDIOC_S_PARM:
898                 if ((ret = uvc_acquire_privileges(handle)) < 0)
899                         return ret;
900
901                 return uvc_v4l2_set_streamparm(stream, arg);
902
903         /* Cropping and scaling */
904         case VIDIOC_CROPCAP:
905         {
906                 struct v4l2_cropcap *ccap = arg;
907
908                 if (ccap->type != stream->type)
909                         return -EINVAL;
910
911                 ccap->bounds.left = 0;
912                 ccap->bounds.top = 0;
913
914                 mutex_lock(&stream->mutex);
915                 ccap->bounds.width = stream->cur_frame->wWidth;
916                 ccap->bounds.height = stream->cur_frame->wHeight;
917                 mutex_unlock(&stream->mutex);
918
919                 ccap->defrect = ccap->bounds;
920
921                 ccap->pixelaspect.numerator = 1;
922                 ccap->pixelaspect.denominator = 1;
923                 break;
924         }
925
926         case VIDIOC_G_CROP:
927         case VIDIOC_S_CROP:
928                 return -EINVAL;
929
930         /* Buffers & streaming */
931         case VIDIOC_REQBUFS:
932                 if ((ret = uvc_acquire_privileges(handle)) < 0)
933                         return ret;
934
935                 mutex_lock(&stream->mutex);
936                 ret = uvc_alloc_buffers(&stream->queue, arg);
937                 mutex_unlock(&stream->mutex);
938                 if (ret < 0)
939                         return ret;
940
941                 if (ret == 0)
942                         uvc_dismiss_privileges(handle);
943
944                 ret = 0;
945                 break;
946
947         case VIDIOC_QUERYBUF:
948         {
949                 struct v4l2_buffer *buf = arg;
950
951                 if (!uvc_has_privileges(handle))
952                         return -EBUSY;
953
954                 return uvc_query_buffer(&stream->queue, buf);
955         }
956
957         case VIDIOC_QBUF:
958                 if (!uvc_has_privileges(handle))
959                         return -EBUSY;
960
961                 return uvc_queue_buffer(&stream->queue, arg);
962
963         case VIDIOC_DQBUF:
964                 if (!uvc_has_privileges(handle))
965                         return -EBUSY;
966
967                 return uvc_dequeue_buffer(&stream->queue, arg,
968                         file->f_flags & O_NONBLOCK);
969
970         case VIDIOC_STREAMON:
971         {
972                 int *type = arg;
973
974                 if (*type != stream->type)
975                         return -EINVAL;
976
977                 if (!uvc_has_privileges(handle))
978                         return -EBUSY;
979
980                 mutex_lock(&stream->mutex);
981                 ret = uvc_video_enable(stream, 1);
982                 mutex_unlock(&stream->mutex);
983                 if (ret < 0)
984                         return ret;
985                 break;
986         }
987
988         case VIDIOC_STREAMOFF:
989         {
990                 int *type = arg;
991
992                 if (*type != stream->type)
993                         return -EINVAL;
994
995                 if (!uvc_has_privileges(handle))
996                         return -EBUSY;
997
998                 return uvc_video_enable(stream, 0);
999         }
1000
1001         /* Analog video standards make no sense for digital cameras. */
1002         case VIDIOC_ENUMSTD:
1003         case VIDIOC_QUERYSTD:
1004         case VIDIOC_G_STD:
1005         case VIDIOC_S_STD:
1006
1007         case VIDIOC_OVERLAY:
1008
1009         case VIDIOC_ENUMAUDIO:
1010         case VIDIOC_ENUMAUDOUT:
1011
1012         case VIDIOC_ENUMOUTPUT:
1013                 uvc_trace(UVC_TRACE_IOCTL, "Unsupported ioctl 0x%08x\n", cmd);
1014                 return -EINVAL;
1015
1016         case UVCIOC_CTRL_MAP:
1017                 return uvc_ioctl_ctrl_map(chain, arg);
1018
1019         case UVCIOC_CTRL_QUERY:
1020                 return uvc_xu_ctrl_query(chain, arg);
1021
1022         default:
1023                 uvc_trace(UVC_TRACE_IOCTL, "Unknown ioctl 0x%08x\n", cmd);
1024                 return -ENOTTY;
1025         }
1026
1027         return ret;
1028 }
1029
1030 static long uvc_v4l2_ioctl(struct file *file,
1031                      unsigned int cmd, unsigned long arg)
1032 {
1033         if (uvc_trace_param & UVC_TRACE_IOCTL) {
1034                 uvc_printk(KERN_DEBUG, "uvc_v4l2_ioctl(");
1035                 v4l_printk_ioctl(cmd);
1036                 printk(")\n");
1037         }
1038
1039         return video_usercopy(file, cmd, arg, uvc_v4l2_do_ioctl);
1040 }
1041
1042 #ifdef CONFIG_COMPAT
1043 struct uvc_xu_control_mapping32 {
1044         __u32 id;
1045         __u8 name[32];
1046         __u8 entity[16];
1047         __u8 selector;
1048
1049         __u8 size;
1050         __u8 offset;
1051         __u32 v4l2_type;
1052         __u32 data_type;
1053
1054         compat_caddr_t menu_info;
1055         __u32 menu_count;
1056
1057         __u32 reserved[4];
1058 };
1059
1060 static int uvc_v4l2_get_xu_mapping(struct uvc_xu_control_mapping *kp,
1061                         const struct uvc_xu_control_mapping32 __user *up)
1062 {
1063         struct uvc_menu_info __user *umenus;
1064         struct uvc_menu_info __user *kmenus;
1065         compat_caddr_t p;
1066
1067         if (!access_ok(VERIFY_READ, up, sizeof(*up)) ||
1068             __copy_from_user(kp, up, offsetof(typeof(*up), menu_info)) ||
1069             __get_user(kp->menu_count, &up->menu_count))
1070                 return -EFAULT;
1071
1072         memset(kp->reserved, 0, sizeof(kp->reserved));
1073
1074         if (kp->menu_count == 0) {
1075                 kp->menu_info = NULL;
1076                 return 0;
1077         }
1078
1079         if (__get_user(p, &up->menu_info))
1080                 return -EFAULT;
1081         umenus = compat_ptr(p);
1082         if (!access_ok(VERIFY_READ, umenus, kp->menu_count * sizeof(*umenus)))
1083                 return -EFAULT;
1084
1085         kmenus = compat_alloc_user_space(kp->menu_count * sizeof(*kmenus));
1086         if (kmenus == NULL)
1087                 return -EFAULT;
1088         kp->menu_info = kmenus;
1089
1090         if (copy_in_user(kmenus, umenus, kp->menu_count * sizeof(*umenus)))
1091                 return -EFAULT;
1092
1093         return 0;
1094 }
1095
1096 static int uvc_v4l2_put_xu_mapping(const struct uvc_xu_control_mapping *kp,
1097                         struct uvc_xu_control_mapping32 __user *up)
1098 {
1099         struct uvc_menu_info __user *umenus;
1100         struct uvc_menu_info __user *kmenus = kp->menu_info;
1101         compat_caddr_t p;
1102
1103         if (!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
1104             __copy_to_user(up, kp, offsetof(typeof(*up), menu_info)) ||
1105             __put_user(kp->menu_count, &up->menu_count))
1106                 return -EFAULT;
1107
1108         if (__clear_user(up->reserved, sizeof(up->reserved)))
1109                 return -EFAULT;
1110
1111         if (kp->menu_count == 0)
1112                 return 0;
1113
1114         if (get_user(p, &up->menu_info))
1115                 return -EFAULT;
1116         umenus = compat_ptr(p);
1117         if (!access_ok(VERIFY_WRITE, umenus, kp->menu_count * sizeof(*umenus)))
1118                 return -EFAULT;
1119
1120         if (copy_in_user(umenus, kmenus, kp->menu_count * sizeof(*umenus)))
1121                 return -EFAULT;
1122
1123         return 0;
1124 }
1125
1126 struct uvc_xu_control_query32 {
1127         __u8 unit;
1128         __u8 selector;
1129         __u8 query;
1130         __u16 size;
1131         compat_caddr_t data;
1132 };
1133
1134 static int uvc_v4l2_get_xu_query(struct uvc_xu_control_query *kp,
1135                         const struct uvc_xu_control_query32 __user *up)
1136 {
1137         u8 __user *udata;
1138         u8 __user *kdata;
1139         compat_caddr_t p;
1140
1141         if (!access_ok(VERIFY_READ, up, sizeof(*up)) ||
1142             __copy_from_user(kp, up, offsetof(typeof(*up), data)))
1143                 return -EFAULT;
1144
1145         if (kp->size == 0) {
1146                 kp->data = NULL;
1147                 return 0;
1148         }
1149
1150         if (__get_user(p, &up->data))
1151                 return -EFAULT;
1152         udata = compat_ptr(p);
1153         if (!access_ok(VERIFY_READ, udata, kp->size))
1154                 return -EFAULT;
1155
1156         kdata = compat_alloc_user_space(kp->size);
1157         if (kdata == NULL)
1158                 return -EFAULT;
1159         kp->data = kdata;
1160
1161         if (copy_in_user(kdata, udata, kp->size))
1162                 return -EFAULT;
1163
1164         return 0;
1165 }
1166
1167 static int uvc_v4l2_put_xu_query(const struct uvc_xu_control_query *kp,
1168                         struct uvc_xu_control_query32 __user *up)
1169 {
1170         u8 __user *udata;
1171         u8 __user *kdata = kp->data;
1172         compat_caddr_t p;
1173
1174         if (!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
1175             __copy_to_user(up, kp, offsetof(typeof(*up), data)))
1176                 return -EFAULT;
1177
1178         if (kp->size == 0)
1179                 return 0;
1180
1181         if (get_user(p, &up->data))
1182                 return -EFAULT;
1183         udata = compat_ptr(p);
1184         if (!access_ok(VERIFY_READ, udata, kp->size))
1185                 return -EFAULT;
1186
1187         if (copy_in_user(udata, kdata, kp->size))
1188                 return -EFAULT;
1189
1190         return 0;
1191 }
1192
1193 #define UVCIOC_CTRL_MAP32       _IOWR('u', 0x20, struct uvc_xu_control_mapping32)
1194 #define UVCIOC_CTRL_QUERY32     _IOWR('u', 0x21, struct uvc_xu_control_query32)
1195
1196 static long uvc_v4l2_compat_ioctl32(struct file *file,
1197                      unsigned int cmd, unsigned long arg)
1198 {
1199         union {
1200                 struct uvc_xu_control_mapping xmap;
1201                 struct uvc_xu_control_query xqry;
1202         } karg;
1203         void __user *up = compat_ptr(arg);
1204         mm_segment_t old_fs;
1205         long ret;
1206
1207         switch (cmd) {
1208         case UVCIOC_CTRL_MAP32:
1209                 cmd = UVCIOC_CTRL_MAP;
1210                 ret = uvc_v4l2_get_xu_mapping(&karg.xmap, up);
1211                 break;
1212
1213         case UVCIOC_CTRL_QUERY32:
1214                 cmd = UVCIOC_CTRL_QUERY;
1215                 ret = uvc_v4l2_get_xu_query(&karg.xqry, up);
1216                 break;
1217
1218         default:
1219                 return -ENOIOCTLCMD;
1220         }
1221
1222         old_fs = get_fs();
1223         set_fs(KERNEL_DS);
1224         ret = uvc_v4l2_ioctl(file, cmd, (unsigned long)&karg);
1225         set_fs(old_fs);
1226
1227         if (ret < 0)
1228                 return ret;
1229
1230         switch (cmd) {
1231         case UVCIOC_CTRL_MAP:
1232                 ret = uvc_v4l2_put_xu_mapping(&karg.xmap, up);
1233                 break;
1234
1235         case UVCIOC_CTRL_QUERY:
1236                 ret = uvc_v4l2_put_xu_query(&karg.xqry, up);
1237                 break;
1238         }
1239
1240         return ret;
1241 }
1242 #endif
1243
1244 static ssize_t uvc_v4l2_read(struct file *file, char __user *data,
1245                     size_t count, loff_t *ppos)
1246 {
1247         uvc_trace(UVC_TRACE_CALLS, "uvc_v4l2_read: not implemented.\n");
1248         return -EINVAL;
1249 }
1250
1251 static int uvc_v4l2_mmap(struct file *file, struct vm_area_struct *vma)
1252 {
1253         struct uvc_fh *handle = file->private_data;
1254         struct uvc_streaming *stream = handle->stream;
1255
1256         uvc_trace(UVC_TRACE_CALLS, "uvc_v4l2_mmap\n");
1257
1258         return uvc_queue_mmap(&stream->queue, vma);
1259 }
1260
1261 static unsigned int uvc_v4l2_poll(struct file *file, poll_table *wait)
1262 {
1263         struct uvc_fh *handle = file->private_data;
1264         struct uvc_streaming *stream = handle->stream;
1265
1266         uvc_trace(UVC_TRACE_CALLS, "uvc_v4l2_poll\n");
1267
1268         return uvc_queue_poll(&stream->queue, file, wait);
1269 }
1270
1271 #ifndef CONFIG_MMU
1272 static unsigned long uvc_v4l2_get_unmapped_area(struct file *file,
1273                 unsigned long addr, unsigned long len, unsigned long pgoff,
1274                 unsigned long flags)
1275 {
1276         struct uvc_fh *handle = file->private_data;
1277         struct uvc_streaming *stream = handle->stream;
1278
1279         uvc_trace(UVC_TRACE_CALLS, "uvc_v4l2_get_unmapped_area\n");
1280
1281         return uvc_queue_get_unmapped_area(&stream->queue, pgoff);
1282 }
1283 #endif
1284
1285 const struct v4l2_file_operations uvc_fops = {
1286         .owner          = THIS_MODULE,
1287         .open           = uvc_v4l2_open,
1288         .release        = uvc_v4l2_release,
1289         .unlocked_ioctl = uvc_v4l2_ioctl,
1290 #ifdef CONFIG_COMPAT
1291         .compat_ioctl32 = uvc_v4l2_compat_ioctl32,
1292 #endif
1293         .read           = uvc_v4l2_read,
1294         .mmap           = uvc_v4l2_mmap,
1295         .poll           = uvc_v4l2_poll,
1296 #ifndef CONFIG_MMU
1297         .get_unmapped_area = uvc_v4l2_get_unmapped_area,
1298 #endif
1299 };
1300