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