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