Merge branch 'docs-move' of git://git.kernel.org/pub/scm/linux/kernel/git/rdunlap...
[pandora-kernel.git] / drivers / media / video / uvc / uvc_driver.c
1 /*
2  *      uvc_driver.c  --  USB Video Class driver
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 /*
15  * This driver aims to support video input and ouput devices compliant with the
16  * 'USB Video Class' specification.
17  *
18  * The driver doesn't support the deprecated v4l1 interface. It implements the
19  * mmap capture method only, and doesn't do any image format conversion in
20  * software. If your user-space application doesn't support YUYV or MJPEG, fix
21  * it :-). Please note that the MJPEG data have been stripped from their
22  * Huffman tables (DHT marker), you will need to add it back if your JPEG
23  * codec can't handle MJPEG data.
24  */
25
26 #include <linux/kernel.h>
27 #include <linux/list.h>
28 #include <linux/module.h>
29 #include <linux/slab.h>
30 #include <linux/usb.h>
31 #include <linux/videodev2.h>
32 #include <linux/vmalloc.h>
33 #include <linux/wait.h>
34 #include <asm/atomic.h>
35 #include <asm/unaligned.h>
36
37 #include <media/v4l2-common.h>
38
39 #include "uvcvideo.h"
40
41 #define DRIVER_AUTHOR           "Laurent Pinchart " \
42                                 "<laurent.pinchart@ideasonboard.com>"
43 #define DRIVER_DESC             "USB Video Class driver"
44
45 unsigned int uvc_clock_param = CLOCK_MONOTONIC;
46 unsigned int uvc_no_drop_param;
47 static unsigned int uvc_quirks_param = -1;
48 unsigned int uvc_trace_param;
49 unsigned int uvc_timeout_param = UVC_CTRL_STREAMING_TIMEOUT;
50
51 /* ------------------------------------------------------------------------
52  * Video formats
53  */
54
55 static struct uvc_format_desc uvc_fmts[] = {
56         {
57                 .name           = "YUV 4:2:2 (YUYV)",
58                 .guid           = UVC_GUID_FORMAT_YUY2,
59                 .fcc            = V4L2_PIX_FMT_YUYV,
60         },
61         {
62                 .name           = "YUV 4:2:2 (YUYV)",
63                 .guid           = UVC_GUID_FORMAT_YUY2_ISIGHT,
64                 .fcc            = V4L2_PIX_FMT_YUYV,
65         },
66         {
67                 .name           = "YUV 4:2:0 (NV12)",
68                 .guid           = UVC_GUID_FORMAT_NV12,
69                 .fcc            = V4L2_PIX_FMT_NV12,
70         },
71         {
72                 .name           = "MJPEG",
73                 .guid           = UVC_GUID_FORMAT_MJPEG,
74                 .fcc            = V4L2_PIX_FMT_MJPEG,
75         },
76         {
77                 .name           = "YVU 4:2:0 (YV12)",
78                 .guid           = UVC_GUID_FORMAT_YV12,
79                 .fcc            = V4L2_PIX_FMT_YVU420,
80         },
81         {
82                 .name           = "YUV 4:2:0 (I420)",
83                 .guid           = UVC_GUID_FORMAT_I420,
84                 .fcc            = V4L2_PIX_FMT_YUV420,
85         },
86         {
87                 .name           = "YUV 4:2:0 (M420)",
88                 .guid           = UVC_GUID_FORMAT_M420,
89                 .fcc            = V4L2_PIX_FMT_M420,
90         },
91         {
92                 .name           = "YUV 4:2:2 (UYVY)",
93                 .guid           = UVC_GUID_FORMAT_UYVY,
94                 .fcc            = V4L2_PIX_FMT_UYVY,
95         },
96         {
97                 .name           = "Greyscale (8-bit)",
98                 .guid           = UVC_GUID_FORMAT_Y800,
99                 .fcc            = V4L2_PIX_FMT_GREY,
100         },
101         {
102                 .name           = "Greyscale (16-bit)",
103                 .guid           = UVC_GUID_FORMAT_Y16,
104                 .fcc            = V4L2_PIX_FMT_Y16,
105         },
106         {
107                 .name           = "RGB Bayer",
108                 .guid           = UVC_GUID_FORMAT_BY8,
109                 .fcc            = V4L2_PIX_FMT_SBGGR8,
110         },
111         {
112                 .name           = "RGB565",
113                 .guid           = UVC_GUID_FORMAT_RGBP,
114                 .fcc            = V4L2_PIX_FMT_RGB565,
115         },
116 };
117
118 /* ------------------------------------------------------------------------
119  * Utility functions
120  */
121
122 struct usb_host_endpoint *uvc_find_endpoint(struct usb_host_interface *alts,
123                 __u8 epaddr)
124 {
125         struct usb_host_endpoint *ep;
126         unsigned int i;
127
128         for (i = 0; i < alts->desc.bNumEndpoints; ++i) {
129                 ep = &alts->endpoint[i];
130                 if (ep->desc.bEndpointAddress == epaddr)
131                         return ep;
132         }
133
134         return NULL;
135 }
136
137 static struct uvc_format_desc *uvc_format_by_guid(const __u8 guid[16])
138 {
139         unsigned int len = ARRAY_SIZE(uvc_fmts);
140         unsigned int i;
141
142         for (i = 0; i < len; ++i) {
143                 if (memcmp(guid, uvc_fmts[i].guid, 16) == 0)
144                         return &uvc_fmts[i];
145         }
146
147         return NULL;
148 }
149
150 static __u32 uvc_colorspace(const __u8 primaries)
151 {
152         static const __u8 colorprimaries[] = {
153                 0,
154                 V4L2_COLORSPACE_SRGB,
155                 V4L2_COLORSPACE_470_SYSTEM_M,
156                 V4L2_COLORSPACE_470_SYSTEM_BG,
157                 V4L2_COLORSPACE_SMPTE170M,
158                 V4L2_COLORSPACE_SMPTE240M,
159         };
160
161         if (primaries < ARRAY_SIZE(colorprimaries))
162                 return colorprimaries[primaries];
163
164         return 0;
165 }
166
167 /* Simplify a fraction using a simple continued fraction decomposition. The
168  * idea here is to convert fractions such as 333333/10000000 to 1/30 using
169  * 32 bit arithmetic only. The algorithm is not perfect and relies upon two
170  * arbitrary parameters to remove non-significative terms from the simple
171  * continued fraction decomposition. Using 8 and 333 for n_terms and threshold
172  * respectively seems to give nice results.
173  */
174 void uvc_simplify_fraction(uint32_t *numerator, uint32_t *denominator,
175                 unsigned int n_terms, unsigned int threshold)
176 {
177         uint32_t *an;
178         uint32_t x, y, r;
179         unsigned int i, n;
180
181         an = kmalloc(n_terms * sizeof *an, GFP_KERNEL);
182         if (an == NULL)
183                 return;
184
185         /* Convert the fraction to a simple continued fraction. See
186          * http://mathforum.org/dr.math/faq/faq.fractions.html
187          * Stop if the current term is bigger than or equal to the given
188          * threshold.
189          */
190         x = *numerator;
191         y = *denominator;
192
193         for (n = 0; n < n_terms && y != 0; ++n) {
194                 an[n] = x / y;
195                 if (an[n] >= threshold) {
196                         if (n < 2)
197                                 n++;
198                         break;
199                 }
200
201                 r = x - an[n] * y;
202                 x = y;
203                 y = r;
204         }
205
206         /* Expand the simple continued fraction back to an integer fraction. */
207         x = 0;
208         y = 1;
209
210         for (i = n; i > 0; --i) {
211                 r = y;
212                 y = an[i-1] * y + x;
213                 x = r;
214         }
215
216         *numerator = y;
217         *denominator = x;
218         kfree(an);
219 }
220
221 /* Convert a fraction to a frame interval in 100ns multiples. The idea here is
222  * to compute numerator / denominator * 10000000 using 32 bit fixed point
223  * arithmetic only.
224  */
225 uint32_t uvc_fraction_to_interval(uint32_t numerator, uint32_t denominator)
226 {
227         uint32_t multiplier;
228
229         /* Saturate the result if the operation would overflow. */
230         if (denominator == 0 ||
231             numerator/denominator >= ((uint32_t)-1)/10000000)
232                 return (uint32_t)-1;
233
234         /* Divide both the denominator and the multiplier by two until
235          * numerator * multiplier doesn't overflow. If anyone knows a better
236          * algorithm please let me know.
237          */
238         multiplier = 10000000;
239         while (numerator > ((uint32_t)-1)/multiplier) {
240                 multiplier /= 2;
241                 denominator /= 2;
242         }
243
244         return denominator ? numerator * multiplier / denominator : 0;
245 }
246
247 /* ------------------------------------------------------------------------
248  * Terminal and unit management
249  */
250
251 struct uvc_entity *uvc_entity_by_id(struct uvc_device *dev, int id)
252 {
253         struct uvc_entity *entity;
254
255         list_for_each_entry(entity, &dev->entities, list) {
256                 if (entity->id == id)
257                         return entity;
258         }
259
260         return NULL;
261 }
262
263 static struct uvc_entity *uvc_entity_by_reference(struct uvc_device *dev,
264         int id, struct uvc_entity *entity)
265 {
266         unsigned int i;
267
268         if (entity == NULL)
269                 entity = list_entry(&dev->entities, struct uvc_entity, list);
270
271         list_for_each_entry_continue(entity, &dev->entities, list) {
272                 for (i = 0; i < entity->bNrInPins; ++i)
273                         if (entity->baSourceID[i] == id)
274                                 return entity;
275         }
276
277         return NULL;
278 }
279
280 static struct uvc_streaming *uvc_stream_by_id(struct uvc_device *dev, int id)
281 {
282         struct uvc_streaming *stream;
283
284         list_for_each_entry(stream, &dev->streams, list) {
285                 if (stream->header.bTerminalLink == id)
286                         return stream;
287         }
288
289         return NULL;
290 }
291
292 /* ------------------------------------------------------------------------
293  * Descriptors parsing
294  */
295
296 static int uvc_parse_format(struct uvc_device *dev,
297         struct uvc_streaming *streaming, struct uvc_format *format,
298         __u32 **intervals, unsigned char *buffer, int buflen)
299 {
300         struct usb_interface *intf = streaming->intf;
301         struct usb_host_interface *alts = intf->cur_altsetting;
302         struct uvc_format_desc *fmtdesc;
303         struct uvc_frame *frame;
304         const unsigned char *start = buffer;
305         unsigned int interval;
306         unsigned int i, n;
307         __u8 ftype;
308
309         format->type = buffer[2];
310         format->index = buffer[3];
311
312         switch (buffer[2]) {
313         case UVC_VS_FORMAT_UNCOMPRESSED:
314         case UVC_VS_FORMAT_FRAME_BASED:
315                 n = buffer[2] == UVC_VS_FORMAT_UNCOMPRESSED ? 27 : 28;
316                 if (buflen < n) {
317                         uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
318                                "interface %d FORMAT error\n",
319                                dev->udev->devnum,
320                                alts->desc.bInterfaceNumber);
321                         return -EINVAL;
322                 }
323
324                 /* Find the format descriptor from its GUID. */
325                 fmtdesc = uvc_format_by_guid(&buffer[5]);
326
327                 if (fmtdesc != NULL) {
328                         strlcpy(format->name, fmtdesc->name,
329                                 sizeof format->name);
330                         format->fcc = fmtdesc->fcc;
331                 } else {
332                         uvc_printk(KERN_INFO, "Unknown video format %pUl\n",
333                                 &buffer[5]);
334                         snprintf(format->name, sizeof(format->name), "%pUl\n",
335                                 &buffer[5]);
336                         format->fcc = 0;
337                 }
338
339                 format->bpp = buffer[21];
340                 if (buffer[2] == UVC_VS_FORMAT_UNCOMPRESSED) {
341                         ftype = UVC_VS_FRAME_UNCOMPRESSED;
342                 } else {
343                         ftype = UVC_VS_FRAME_FRAME_BASED;
344                         if (buffer[27])
345                                 format->flags = UVC_FMT_FLAG_COMPRESSED;
346                 }
347                 break;
348
349         case UVC_VS_FORMAT_MJPEG:
350                 if (buflen < 11) {
351                         uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
352                                "interface %d FORMAT error\n",
353                                dev->udev->devnum,
354                                alts->desc.bInterfaceNumber);
355                         return -EINVAL;
356                 }
357
358                 strlcpy(format->name, "MJPEG", sizeof format->name);
359                 format->fcc = V4L2_PIX_FMT_MJPEG;
360                 format->flags = UVC_FMT_FLAG_COMPRESSED;
361                 format->bpp = 0;
362                 ftype = UVC_VS_FRAME_MJPEG;
363                 break;
364
365         case UVC_VS_FORMAT_DV:
366                 if (buflen < 9) {
367                         uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
368                                "interface %d FORMAT error\n",
369                                dev->udev->devnum,
370                                alts->desc.bInterfaceNumber);
371                         return -EINVAL;
372                 }
373
374                 switch (buffer[8] & 0x7f) {
375                 case 0:
376                         strlcpy(format->name, "SD-DV", sizeof format->name);
377                         break;
378                 case 1:
379                         strlcpy(format->name, "SDL-DV", sizeof format->name);
380                         break;
381                 case 2:
382                         strlcpy(format->name, "HD-DV", sizeof format->name);
383                         break;
384                 default:
385                         uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
386                                "interface %d: unknown DV format %u\n",
387                                dev->udev->devnum,
388                                alts->desc.bInterfaceNumber, buffer[8]);
389                         return -EINVAL;
390                 }
391
392                 strlcat(format->name, buffer[8] & (1 << 7) ? " 60Hz" : " 50Hz",
393                         sizeof format->name);
394
395                 format->fcc = V4L2_PIX_FMT_DV;
396                 format->flags = UVC_FMT_FLAG_COMPRESSED | UVC_FMT_FLAG_STREAM;
397                 format->bpp = 0;
398                 ftype = 0;
399
400                 /* Create a dummy frame descriptor. */
401                 frame = &format->frame[0];
402                 memset(&format->frame[0], 0, sizeof format->frame[0]);
403                 frame->bFrameIntervalType = 1;
404                 frame->dwDefaultFrameInterval = 1;
405                 frame->dwFrameInterval = *intervals;
406                 *(*intervals)++ = 1;
407                 format->nframes = 1;
408                 break;
409
410         case UVC_VS_FORMAT_MPEG2TS:
411         case UVC_VS_FORMAT_STREAM_BASED:
412                 /* Not supported yet. */
413         default:
414                 uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
415                        "interface %d unsupported format %u\n",
416                        dev->udev->devnum, alts->desc.bInterfaceNumber,
417                        buffer[2]);
418                 return -EINVAL;
419         }
420
421         uvc_trace(UVC_TRACE_DESCR, "Found format %s.\n", format->name);
422
423         buflen -= buffer[0];
424         buffer += buffer[0];
425
426         /* Parse the frame descriptors. Only uncompressed, MJPEG and frame
427          * based formats have frame descriptors.
428          */
429         while (buflen > 2 && buffer[1] == USB_DT_CS_INTERFACE &&
430                buffer[2] == ftype) {
431                 frame = &format->frame[format->nframes];
432                 if (ftype != UVC_VS_FRAME_FRAME_BASED)
433                         n = buflen > 25 ? buffer[25] : 0;
434                 else
435                         n = buflen > 21 ? buffer[21] : 0;
436
437                 n = n ? n : 3;
438
439                 if (buflen < 26 + 4*n) {
440                         uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
441                                "interface %d FRAME error\n", dev->udev->devnum,
442                                alts->desc.bInterfaceNumber);
443                         return -EINVAL;
444                 }
445
446                 frame->bFrameIndex = buffer[3];
447                 frame->bmCapabilities = buffer[4];
448                 frame->wWidth = get_unaligned_le16(&buffer[5]);
449                 frame->wHeight = get_unaligned_le16(&buffer[7]);
450                 frame->dwMinBitRate = get_unaligned_le32(&buffer[9]);
451                 frame->dwMaxBitRate = get_unaligned_le32(&buffer[13]);
452                 if (ftype != UVC_VS_FRAME_FRAME_BASED) {
453                         frame->dwMaxVideoFrameBufferSize =
454                                 get_unaligned_le32(&buffer[17]);
455                         frame->dwDefaultFrameInterval =
456                                 get_unaligned_le32(&buffer[21]);
457                         frame->bFrameIntervalType = buffer[25];
458                 } else {
459                         frame->dwMaxVideoFrameBufferSize = 0;
460                         frame->dwDefaultFrameInterval =
461                                 get_unaligned_le32(&buffer[17]);
462                         frame->bFrameIntervalType = buffer[21];
463                 }
464                 frame->dwFrameInterval = *intervals;
465
466                 /* Several UVC chipsets screw up dwMaxVideoFrameBufferSize
467                  * completely. Observed behaviours range from setting the
468                  * value to 1.1x the actual frame size to hardwiring the
469                  * 16 low bits to 0. This results in a higher than necessary
470                  * memory usage as well as a wrong image size information. For
471                  * uncompressed formats this can be fixed by computing the
472                  * value from the frame size.
473                  */
474                 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED))
475                         frame->dwMaxVideoFrameBufferSize = format->bpp
476                                 * frame->wWidth * frame->wHeight / 8;
477
478                 /* Some bogus devices report dwMinFrameInterval equal to
479                  * dwMaxFrameInterval and have dwFrameIntervalStep set to
480                  * zero. Setting all null intervals to 1 fixes the problem and
481                  * some other divisions by zero that could happen.
482                  */
483                 for (i = 0; i < n; ++i) {
484                         interval = get_unaligned_le32(&buffer[26+4*i]);
485                         *(*intervals)++ = interval ? interval : 1;
486                 }
487
488                 /* Make sure that the default frame interval stays between
489                  * the boundaries.
490                  */
491                 n -= frame->bFrameIntervalType ? 1 : 2;
492                 frame->dwDefaultFrameInterval =
493                         min(frame->dwFrameInterval[n],
494                             max(frame->dwFrameInterval[0],
495                                 frame->dwDefaultFrameInterval));
496
497                 if (dev->quirks & UVC_QUIRK_RESTRICT_FRAME_RATE) {
498                         frame->bFrameIntervalType = 1;
499                         frame->dwFrameInterval[0] =
500                                 frame->dwDefaultFrameInterval;
501                 }
502
503                 uvc_trace(UVC_TRACE_DESCR, "- %ux%u (%u.%u fps)\n",
504                         frame->wWidth, frame->wHeight,
505                         10000000/frame->dwDefaultFrameInterval,
506                         (100000000/frame->dwDefaultFrameInterval)%10);
507
508                 format->nframes++;
509                 buflen -= buffer[0];
510                 buffer += buffer[0];
511         }
512
513         if (buflen > 2 && buffer[1] == USB_DT_CS_INTERFACE &&
514             buffer[2] == UVC_VS_STILL_IMAGE_FRAME) {
515                 buflen -= buffer[0];
516                 buffer += buffer[0];
517         }
518
519         if (buflen > 2 && buffer[1] == USB_DT_CS_INTERFACE &&
520             buffer[2] == UVC_VS_COLORFORMAT) {
521                 if (buflen < 6) {
522                         uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
523                                "interface %d COLORFORMAT error\n",
524                                dev->udev->devnum,
525                                alts->desc.bInterfaceNumber);
526                         return -EINVAL;
527                 }
528
529                 format->colorspace = uvc_colorspace(buffer[3]);
530
531                 buflen -= buffer[0];
532                 buffer += buffer[0];
533         }
534
535         return buffer - start;
536 }
537
538 static int uvc_parse_streaming(struct uvc_device *dev,
539         struct usb_interface *intf)
540 {
541         struct uvc_streaming *streaming = NULL;
542         struct uvc_format *format;
543         struct uvc_frame *frame;
544         struct usb_host_interface *alts = &intf->altsetting[0];
545         unsigned char *_buffer, *buffer = alts->extra;
546         int _buflen, buflen = alts->extralen;
547         unsigned int nformats = 0, nframes = 0, nintervals = 0;
548         unsigned int size, i, n, p;
549         __u32 *interval;
550         __u16 psize;
551         int ret = -EINVAL;
552
553         if (intf->cur_altsetting->desc.bInterfaceSubClass
554                 != UVC_SC_VIDEOSTREAMING) {
555                 uvc_trace(UVC_TRACE_DESCR, "device %d interface %d isn't a "
556                         "video streaming interface\n", dev->udev->devnum,
557                         intf->altsetting[0].desc.bInterfaceNumber);
558                 return -EINVAL;
559         }
560
561         if (usb_driver_claim_interface(&uvc_driver.driver, intf, dev)) {
562                 uvc_trace(UVC_TRACE_DESCR, "device %d interface %d is already "
563                         "claimed\n", dev->udev->devnum,
564                         intf->altsetting[0].desc.bInterfaceNumber);
565                 return -EINVAL;
566         }
567
568         streaming = kzalloc(sizeof *streaming, GFP_KERNEL);
569         if (streaming == NULL) {
570                 usb_driver_release_interface(&uvc_driver.driver, intf);
571                 return -EINVAL;
572         }
573
574         mutex_init(&streaming->mutex);
575         streaming->dev = dev;
576         streaming->intf = usb_get_intf(intf);
577         streaming->intfnum = intf->cur_altsetting->desc.bInterfaceNumber;
578
579         /* The Pico iMage webcam has its class-specific interface descriptors
580          * after the endpoint descriptors.
581          */
582         if (buflen == 0) {
583                 for (i = 0; i < alts->desc.bNumEndpoints; ++i) {
584                         struct usb_host_endpoint *ep = &alts->endpoint[i];
585
586                         if (ep->extralen == 0)
587                                 continue;
588
589                         if (ep->extralen > 2 &&
590                             ep->extra[1] == USB_DT_CS_INTERFACE) {
591                                 uvc_trace(UVC_TRACE_DESCR, "trying extra data "
592                                         "from endpoint %u.\n", i);
593                                 buffer = alts->endpoint[i].extra;
594                                 buflen = alts->endpoint[i].extralen;
595                                 break;
596                         }
597                 }
598         }
599
600         /* Skip the standard interface descriptors. */
601         while (buflen > 2 && buffer[1] != USB_DT_CS_INTERFACE) {
602                 buflen -= buffer[0];
603                 buffer += buffer[0];
604         }
605
606         if (buflen <= 2) {
607                 uvc_trace(UVC_TRACE_DESCR, "no class-specific streaming "
608                         "interface descriptors found.\n");
609                 goto error;
610         }
611
612         /* Parse the header descriptor. */
613         switch (buffer[2]) {
614         case UVC_VS_OUTPUT_HEADER:
615                 streaming->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
616                 size = 9;
617                 break;
618
619         case UVC_VS_INPUT_HEADER:
620                 streaming->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
621                 size = 13;
622                 break;
623
624         default:
625                 uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming interface "
626                         "%d HEADER descriptor not found.\n", dev->udev->devnum,
627                         alts->desc.bInterfaceNumber);
628                 goto error;
629         }
630
631         p = buflen >= 4 ? buffer[3] : 0;
632         n = buflen >= size ? buffer[size-1] : 0;
633
634         if (buflen < size + p*n) {
635                 uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
636                         "interface %d HEADER descriptor is invalid.\n",
637                         dev->udev->devnum, alts->desc.bInterfaceNumber);
638                 goto error;
639         }
640
641         streaming->header.bNumFormats = p;
642         streaming->header.bEndpointAddress = buffer[6];
643         if (buffer[2] == UVC_VS_INPUT_HEADER) {
644                 streaming->header.bmInfo = buffer[7];
645                 streaming->header.bTerminalLink = buffer[8];
646                 streaming->header.bStillCaptureMethod = buffer[9];
647                 streaming->header.bTriggerSupport = buffer[10];
648                 streaming->header.bTriggerUsage = buffer[11];
649         } else {
650                 streaming->header.bTerminalLink = buffer[7];
651         }
652         streaming->header.bControlSize = n;
653
654         streaming->header.bmaControls = kmemdup(&buffer[size], p * n,
655                                                 GFP_KERNEL);
656         if (streaming->header.bmaControls == NULL) {
657                 ret = -ENOMEM;
658                 goto error;
659         }
660
661         buflen -= buffer[0];
662         buffer += buffer[0];
663
664         _buffer = buffer;
665         _buflen = buflen;
666
667         /* Count the format and frame descriptors. */
668         while (_buflen > 2 && _buffer[1] == USB_DT_CS_INTERFACE) {
669                 switch (_buffer[2]) {
670                 case UVC_VS_FORMAT_UNCOMPRESSED:
671                 case UVC_VS_FORMAT_MJPEG:
672                 case UVC_VS_FORMAT_FRAME_BASED:
673                         nformats++;
674                         break;
675
676                 case UVC_VS_FORMAT_DV:
677                         /* DV format has no frame descriptor. We will create a
678                          * dummy frame descriptor with a dummy frame interval.
679                          */
680                         nformats++;
681                         nframes++;
682                         nintervals++;
683                         break;
684
685                 case UVC_VS_FORMAT_MPEG2TS:
686                 case UVC_VS_FORMAT_STREAM_BASED:
687                         uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
688                                 "interface %d FORMAT %u is not supported.\n",
689                                 dev->udev->devnum,
690                                 alts->desc.bInterfaceNumber, _buffer[2]);
691                         break;
692
693                 case UVC_VS_FRAME_UNCOMPRESSED:
694                 case UVC_VS_FRAME_MJPEG:
695                         nframes++;
696                         if (_buflen > 25)
697                                 nintervals += _buffer[25] ? _buffer[25] : 3;
698                         break;
699
700                 case UVC_VS_FRAME_FRAME_BASED:
701                         nframes++;
702                         if (_buflen > 21)
703                                 nintervals += _buffer[21] ? _buffer[21] : 3;
704                         break;
705                 }
706
707                 _buflen -= _buffer[0];
708                 _buffer += _buffer[0];
709         }
710
711         if (nformats == 0) {
712                 uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming interface "
713                         "%d has no supported formats defined.\n",
714                         dev->udev->devnum, alts->desc.bInterfaceNumber);
715                 goto error;
716         }
717
718         size = nformats * sizeof *format + nframes * sizeof *frame
719              + nintervals * sizeof *interval;
720         format = kzalloc(size, GFP_KERNEL);
721         if (format == NULL) {
722                 ret = -ENOMEM;
723                 goto error;
724         }
725
726         frame = (struct uvc_frame *)&format[nformats];
727         interval = (__u32 *)&frame[nframes];
728
729         streaming->format = format;
730         streaming->nformats = nformats;
731
732         /* Parse the format descriptors. */
733         while (buflen > 2 && buffer[1] == USB_DT_CS_INTERFACE) {
734                 switch (buffer[2]) {
735                 case UVC_VS_FORMAT_UNCOMPRESSED:
736                 case UVC_VS_FORMAT_MJPEG:
737                 case UVC_VS_FORMAT_DV:
738                 case UVC_VS_FORMAT_FRAME_BASED:
739                         format->frame = frame;
740                         ret = uvc_parse_format(dev, streaming, format,
741                                 &interval, buffer, buflen);
742                         if (ret < 0)
743                                 goto error;
744
745                         frame += format->nframes;
746                         format++;
747
748                         buflen -= ret;
749                         buffer += ret;
750                         continue;
751
752                 default:
753                         break;
754                 }
755
756                 buflen -= buffer[0];
757                 buffer += buffer[0];
758         }
759
760         if (buflen)
761                 uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming interface "
762                         "%d has %u bytes of trailing descriptor garbage.\n",
763                         dev->udev->devnum, alts->desc.bInterfaceNumber, buflen);
764
765         /* Parse the alternate settings to find the maximum bandwidth. */
766         for (i = 0; i < intf->num_altsetting; ++i) {
767                 struct usb_host_endpoint *ep;
768                 alts = &intf->altsetting[i];
769                 ep = uvc_find_endpoint(alts,
770                                 streaming->header.bEndpointAddress);
771                 if (ep == NULL)
772                         continue;
773
774                 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
775                 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
776                 if (psize > streaming->maxpsize)
777                         streaming->maxpsize = psize;
778         }
779
780         list_add_tail(&streaming->list, &dev->streams);
781         return 0;
782
783 error:
784         usb_driver_release_interface(&uvc_driver.driver, intf);
785         usb_put_intf(intf);
786         kfree(streaming->format);
787         kfree(streaming->header.bmaControls);
788         kfree(streaming);
789         return ret;
790 }
791
792 static struct uvc_entity *uvc_alloc_entity(u16 type, u8 id,
793                 unsigned int num_pads, unsigned int extra_size)
794 {
795         struct uvc_entity *entity;
796         unsigned int num_inputs;
797         unsigned int size;
798         unsigned int i;
799
800         extra_size = ALIGN(extra_size, sizeof(*entity->pads));
801         num_inputs = (type & UVC_TERM_OUTPUT) ? num_pads : num_pads - 1;
802         size = sizeof(*entity) + extra_size + sizeof(*entity->pads) * num_pads
803              + num_inputs;
804         entity = kzalloc(size, GFP_KERNEL);
805         if (entity == NULL)
806                 return NULL;
807
808         entity->id = id;
809         entity->type = type;
810
811         entity->num_links = 0;
812         entity->num_pads = num_pads;
813         entity->pads = ((void *)(entity + 1)) + extra_size;
814
815         for (i = 0; i < num_inputs; ++i)
816                 entity->pads[i].flags = MEDIA_PAD_FL_SINK;
817         if (!UVC_ENTITY_IS_OTERM(entity))
818                 entity->pads[num_pads-1].flags = MEDIA_PAD_FL_SOURCE;
819
820         entity->bNrInPins = num_inputs;
821         entity->baSourceID = (__u8 *)(&entity->pads[num_pads]);
822
823         return entity;
824 }
825
826 /* Parse vendor-specific extensions. */
827 static int uvc_parse_vendor_control(struct uvc_device *dev,
828         const unsigned char *buffer, int buflen)
829 {
830         struct usb_device *udev = dev->udev;
831         struct usb_host_interface *alts = dev->intf->cur_altsetting;
832         struct uvc_entity *unit;
833         unsigned int n, p;
834         int handled = 0;
835
836         switch (le16_to_cpu(dev->udev->descriptor.idVendor)) {
837         case 0x046d:            /* Logitech */
838                 if (buffer[1] != 0x41 || buffer[2] != 0x01)
839                         break;
840
841                 /* Logitech implements several vendor specific functions
842                  * through vendor specific extension units (LXU).
843                  *
844                  * The LXU descriptors are similar to XU descriptors
845                  * (see "USB Device Video Class for Video Devices", section
846                  * 3.7.2.6 "Extension Unit Descriptor") with the following
847                  * differences:
848                  *
849                  * ----------------------------------------------------------
850                  * 0            bLength         1        Number
851                  *      Size of this descriptor, in bytes: 24+p+n*2
852                  * ----------------------------------------------------------
853                  * 23+p+n       bmControlsType  N       Bitmap
854                  *      Individual bits in the set are defined:
855                  *      0: Absolute
856                  *      1: Relative
857                  *
858                  *      This bitset is mapped exactly the same as bmControls.
859                  * ----------------------------------------------------------
860                  * 23+p+n*2     bReserved       1       Boolean
861                  * ----------------------------------------------------------
862                  * 24+p+n*2     iExtension      1       Index
863                  *      Index of a string descriptor that describes this
864                  *      extension unit.
865                  * ----------------------------------------------------------
866                  */
867                 p = buflen >= 22 ? buffer[21] : 0;
868                 n = buflen >= 25 + p ? buffer[22+p] : 0;
869
870                 if (buflen < 25 + p + 2*n) {
871                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
872                                 "interface %d EXTENSION_UNIT error\n",
873                                 udev->devnum, alts->desc.bInterfaceNumber);
874                         break;
875                 }
876
877                 unit = uvc_alloc_entity(UVC_VC_EXTENSION_UNIT, buffer[3],
878                                         p + 1, 2*n);
879                 if (unit == NULL)
880                         return -ENOMEM;
881
882                 memcpy(unit->extension.guidExtensionCode, &buffer[4], 16);
883                 unit->extension.bNumControls = buffer[20];
884                 memcpy(unit->baSourceID, &buffer[22], p);
885                 unit->extension.bControlSize = buffer[22+p];
886                 unit->extension.bmControls = (__u8 *)unit + sizeof(*unit);
887                 unit->extension.bmControlsType = (__u8 *)unit + sizeof(*unit)
888                                                + n;
889                 memcpy(unit->extension.bmControls, &buffer[23+p], 2*n);
890
891                 if (buffer[24+p+2*n] != 0)
892                         usb_string(udev, buffer[24+p+2*n], unit->name,
893                                    sizeof unit->name);
894                 else
895                         sprintf(unit->name, "Extension %u", buffer[3]);
896
897                 list_add_tail(&unit->list, &dev->entities);
898                 handled = 1;
899                 break;
900         }
901
902         return handled;
903 }
904
905 static int uvc_parse_standard_control(struct uvc_device *dev,
906         const unsigned char *buffer, int buflen)
907 {
908         struct usb_device *udev = dev->udev;
909         struct uvc_entity *unit, *term;
910         struct usb_interface *intf;
911         struct usb_host_interface *alts = dev->intf->cur_altsetting;
912         unsigned int i, n, p, len;
913         __u16 type;
914
915         switch (buffer[2]) {
916         case UVC_VC_HEADER:
917                 n = buflen >= 12 ? buffer[11] : 0;
918
919                 if (buflen < 12 || buflen < 12 + n) {
920                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
921                                 "interface %d HEADER error\n", udev->devnum,
922                                 alts->desc.bInterfaceNumber);
923                         return -EINVAL;
924                 }
925
926                 dev->uvc_version = get_unaligned_le16(&buffer[3]);
927                 dev->clock_frequency = get_unaligned_le32(&buffer[7]);
928
929                 /* Parse all USB Video Streaming interfaces. */
930                 for (i = 0; i < n; ++i) {
931                         intf = usb_ifnum_to_if(udev, buffer[12+i]);
932                         if (intf == NULL) {
933                                 uvc_trace(UVC_TRACE_DESCR, "device %d "
934                                         "interface %d doesn't exists\n",
935                                         udev->devnum, i);
936                                 continue;
937                         }
938
939                         uvc_parse_streaming(dev, intf);
940                 }
941                 break;
942
943         case UVC_VC_INPUT_TERMINAL:
944                 if (buflen < 8) {
945                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
946                                 "interface %d INPUT_TERMINAL error\n",
947                                 udev->devnum, alts->desc.bInterfaceNumber);
948                         return -EINVAL;
949                 }
950
951                 /* Make sure the terminal type MSB is not null, otherwise it
952                  * could be confused with a unit.
953                  */
954                 type = get_unaligned_le16(&buffer[4]);
955                 if ((type & 0xff00) == 0) {
956                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
957                                 "interface %d INPUT_TERMINAL %d has invalid "
958                                 "type 0x%04x, skipping\n", udev->devnum,
959                                 alts->desc.bInterfaceNumber,
960                                 buffer[3], type);
961                         return 0;
962                 }
963
964                 n = 0;
965                 p = 0;
966                 len = 8;
967
968                 if (type == UVC_ITT_CAMERA) {
969                         n = buflen >= 15 ? buffer[14] : 0;
970                         len = 15;
971
972                 } else if (type == UVC_ITT_MEDIA_TRANSPORT_INPUT) {
973                         n = buflen >= 9 ? buffer[8] : 0;
974                         p = buflen >= 10 + n ? buffer[9+n] : 0;
975                         len = 10;
976                 }
977
978                 if (buflen < len + n + p) {
979                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
980                                 "interface %d INPUT_TERMINAL error\n",
981                                 udev->devnum, alts->desc.bInterfaceNumber);
982                         return -EINVAL;
983                 }
984
985                 term = uvc_alloc_entity(type | UVC_TERM_INPUT, buffer[3],
986                                         1, n + p);
987                 if (term == NULL)
988                         return -ENOMEM;
989
990                 if (UVC_ENTITY_TYPE(term) == UVC_ITT_CAMERA) {
991                         term->camera.bControlSize = n;
992                         term->camera.bmControls = (__u8 *)term + sizeof *term;
993                         term->camera.wObjectiveFocalLengthMin =
994                                 get_unaligned_le16(&buffer[8]);
995                         term->camera.wObjectiveFocalLengthMax =
996                                 get_unaligned_le16(&buffer[10]);
997                         term->camera.wOcularFocalLength =
998                                 get_unaligned_le16(&buffer[12]);
999                         memcpy(term->camera.bmControls, &buffer[15], n);
1000                 } else if (UVC_ENTITY_TYPE(term) ==
1001                            UVC_ITT_MEDIA_TRANSPORT_INPUT) {
1002                         term->media.bControlSize = n;
1003                         term->media.bmControls = (__u8 *)term + sizeof *term;
1004                         term->media.bTransportModeSize = p;
1005                         term->media.bmTransportModes = (__u8 *)term
1006                                                      + sizeof *term + n;
1007                         memcpy(term->media.bmControls, &buffer[9], n);
1008                         memcpy(term->media.bmTransportModes, &buffer[10+n], p);
1009                 }
1010
1011                 if (buffer[7] != 0)
1012                         usb_string(udev, buffer[7], term->name,
1013                                    sizeof term->name);
1014                 else if (UVC_ENTITY_TYPE(term) == UVC_ITT_CAMERA)
1015                         sprintf(term->name, "Camera %u", buffer[3]);
1016                 else if (UVC_ENTITY_TYPE(term) == UVC_ITT_MEDIA_TRANSPORT_INPUT)
1017                         sprintf(term->name, "Media %u", buffer[3]);
1018                 else
1019                         sprintf(term->name, "Input %u", buffer[3]);
1020
1021                 list_add_tail(&term->list, &dev->entities);
1022                 break;
1023
1024         case UVC_VC_OUTPUT_TERMINAL:
1025                 if (buflen < 9) {
1026                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
1027                                 "interface %d OUTPUT_TERMINAL error\n",
1028                                 udev->devnum, alts->desc.bInterfaceNumber);
1029                         return -EINVAL;
1030                 }
1031
1032                 /* Make sure the terminal type MSB is not null, otherwise it
1033                  * could be confused with a unit.
1034                  */
1035                 type = get_unaligned_le16(&buffer[4]);
1036                 if ((type & 0xff00) == 0) {
1037                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
1038                                 "interface %d OUTPUT_TERMINAL %d has invalid "
1039                                 "type 0x%04x, skipping\n", udev->devnum,
1040                                 alts->desc.bInterfaceNumber, buffer[3], type);
1041                         return 0;
1042                 }
1043
1044                 term = uvc_alloc_entity(type | UVC_TERM_OUTPUT, buffer[3],
1045                                         1, 0);
1046                 if (term == NULL)
1047                         return -ENOMEM;
1048
1049                 memcpy(term->baSourceID, &buffer[7], 1);
1050
1051                 if (buffer[8] != 0)
1052                         usb_string(udev, buffer[8], term->name,
1053                                    sizeof term->name);
1054                 else
1055                         sprintf(term->name, "Output %u", buffer[3]);
1056
1057                 list_add_tail(&term->list, &dev->entities);
1058                 break;
1059
1060         case UVC_VC_SELECTOR_UNIT:
1061                 p = buflen >= 5 ? buffer[4] : 0;
1062
1063                 if (buflen < 5 || buflen < 6 + p) {
1064                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
1065                                 "interface %d SELECTOR_UNIT error\n",
1066                                 udev->devnum, alts->desc.bInterfaceNumber);
1067                         return -EINVAL;
1068                 }
1069
1070                 unit = uvc_alloc_entity(buffer[2], buffer[3], p + 1, 0);
1071                 if (unit == NULL)
1072                         return -ENOMEM;
1073
1074                 memcpy(unit->baSourceID, &buffer[5], p);
1075
1076                 if (buffer[5+p] != 0)
1077                         usb_string(udev, buffer[5+p], unit->name,
1078                                    sizeof unit->name);
1079                 else
1080                         sprintf(unit->name, "Selector %u", buffer[3]);
1081
1082                 list_add_tail(&unit->list, &dev->entities);
1083                 break;
1084
1085         case UVC_VC_PROCESSING_UNIT:
1086                 n = buflen >= 8 ? buffer[7] : 0;
1087                 p = dev->uvc_version >= 0x0110 ? 10 : 9;
1088
1089                 if (buflen < p + n) {
1090                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
1091                                 "interface %d PROCESSING_UNIT error\n",
1092                                 udev->devnum, alts->desc.bInterfaceNumber);
1093                         return -EINVAL;
1094                 }
1095
1096                 unit = uvc_alloc_entity(buffer[2], buffer[3], 2, n);
1097                 if (unit == NULL)
1098                         return -ENOMEM;
1099
1100                 memcpy(unit->baSourceID, &buffer[4], 1);
1101                 unit->processing.wMaxMultiplier =
1102                         get_unaligned_le16(&buffer[5]);
1103                 unit->processing.bControlSize = buffer[7];
1104                 unit->processing.bmControls = (__u8 *)unit + sizeof *unit;
1105                 memcpy(unit->processing.bmControls, &buffer[8], n);
1106                 if (dev->uvc_version >= 0x0110)
1107                         unit->processing.bmVideoStandards = buffer[9+n];
1108
1109                 if (buffer[8+n] != 0)
1110                         usb_string(udev, buffer[8+n], unit->name,
1111                                    sizeof unit->name);
1112                 else
1113                         sprintf(unit->name, "Processing %u", buffer[3]);
1114
1115                 list_add_tail(&unit->list, &dev->entities);
1116                 break;
1117
1118         case UVC_VC_EXTENSION_UNIT:
1119                 p = buflen >= 22 ? buffer[21] : 0;
1120                 n = buflen >= 24 + p ? buffer[22+p] : 0;
1121
1122                 if (buflen < 24 + p + n) {
1123                         uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
1124                                 "interface %d EXTENSION_UNIT error\n",
1125                                 udev->devnum, alts->desc.bInterfaceNumber);
1126                         return -EINVAL;
1127                 }
1128
1129                 unit = uvc_alloc_entity(buffer[2], buffer[3], p + 1, n);
1130                 if (unit == NULL)
1131                         return -ENOMEM;
1132
1133                 memcpy(unit->extension.guidExtensionCode, &buffer[4], 16);
1134                 unit->extension.bNumControls = buffer[20];
1135                 memcpy(unit->baSourceID, &buffer[22], p);
1136                 unit->extension.bControlSize = buffer[22+p];
1137                 unit->extension.bmControls = (__u8 *)unit + sizeof *unit;
1138                 memcpy(unit->extension.bmControls, &buffer[23+p], n);
1139
1140                 if (buffer[23+p+n] != 0)
1141                         usb_string(udev, buffer[23+p+n], unit->name,
1142                                    sizeof unit->name);
1143                 else
1144                         sprintf(unit->name, "Extension %u", buffer[3]);
1145
1146                 list_add_tail(&unit->list, &dev->entities);
1147                 break;
1148
1149         default:
1150                 uvc_trace(UVC_TRACE_DESCR, "Found an unknown CS_INTERFACE "
1151                         "descriptor (%u)\n", buffer[2]);
1152                 break;
1153         }
1154
1155         return 0;
1156 }
1157
1158 static int uvc_parse_control(struct uvc_device *dev)
1159 {
1160         struct usb_host_interface *alts = dev->intf->cur_altsetting;
1161         unsigned char *buffer = alts->extra;
1162         int buflen = alts->extralen;
1163         int ret;
1164
1165         /* Parse the default alternate setting only, as the UVC specification
1166          * defines a single alternate setting, the default alternate setting
1167          * zero.
1168          */
1169
1170         while (buflen > 2) {
1171                 if (uvc_parse_vendor_control(dev, buffer, buflen) ||
1172                     buffer[1] != USB_DT_CS_INTERFACE)
1173                         goto next_descriptor;
1174
1175                 if ((ret = uvc_parse_standard_control(dev, buffer, buflen)) < 0)
1176                         return ret;
1177
1178 next_descriptor:
1179                 buflen -= buffer[0];
1180                 buffer += buffer[0];
1181         }
1182
1183         /* Check if the optional status endpoint is present. Built-in iSight
1184          * webcams have an interrupt endpoint but spit proprietary data that
1185          * don't conform to the UVC status endpoint messages. Don't try to
1186          * handle the interrupt endpoint for those cameras.
1187          */
1188         if (alts->desc.bNumEndpoints == 1 &&
1189             !(dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)) {
1190                 struct usb_host_endpoint *ep = &alts->endpoint[0];
1191                 struct usb_endpoint_descriptor *desc = &ep->desc;
1192
1193                 if (usb_endpoint_is_int_in(desc) &&
1194                     le16_to_cpu(desc->wMaxPacketSize) >= 8 &&
1195                     desc->bInterval != 0) {
1196                         uvc_trace(UVC_TRACE_DESCR, "Found a Status endpoint "
1197                                 "(addr %02x).\n", desc->bEndpointAddress);
1198                         dev->int_ep = ep;
1199                 }
1200         }
1201
1202         return 0;
1203 }
1204
1205 /* ------------------------------------------------------------------------
1206  * UVC device scan
1207  */
1208
1209 /*
1210  * Scan the UVC descriptors to locate a chain starting at an Output Terminal
1211  * and containing the following units:
1212  *
1213  * - one or more Output Terminals (USB Streaming or Display)
1214  * - zero or one Processing Unit
1215  * - zero, one or more single-input Selector Units
1216  * - zero or one multiple-input Selector Units, provided all inputs are
1217  *   connected to input terminals
1218  * - zero, one or mode single-input Extension Units
1219  * - one or more Input Terminals (Camera, External or USB Streaming)
1220  *
1221  * The terminal and units must match on of the following structures:
1222  *
1223  * ITT_*(0) -> +---------+    +---------+    +---------+ -> TT_STREAMING(0)
1224  * ...         | SU{0,1} | -> | PU{0,1} | -> | XU{0,n} |    ...
1225  * ITT_*(n) -> +---------+    +---------+    +---------+ -> TT_STREAMING(n)
1226  *
1227  *                 +---------+    +---------+ -> OTT_*(0)
1228  * TT_STREAMING -> | PU{0,1} | -> | XU{0,n} |    ...
1229  *                 +---------+    +---------+ -> OTT_*(n)
1230  *
1231  * The Processing Unit and Extension Units can be in any order. Additional
1232  * Extension Units connected to the main chain as single-unit branches are
1233  * also supported. Single-input Selector Units are ignored.
1234  */
1235 static int uvc_scan_chain_entity(struct uvc_video_chain *chain,
1236         struct uvc_entity *entity)
1237 {
1238         switch (UVC_ENTITY_TYPE(entity)) {
1239         case UVC_VC_EXTENSION_UNIT:
1240                 if (uvc_trace_param & UVC_TRACE_PROBE)
1241                         printk(" <- XU %d", entity->id);
1242
1243                 if (entity->bNrInPins != 1) {
1244                         uvc_trace(UVC_TRACE_DESCR, "Extension unit %d has more "
1245                                 "than 1 input pin.\n", entity->id);
1246                         return -1;
1247                 }
1248
1249                 break;
1250
1251         case UVC_VC_PROCESSING_UNIT:
1252                 if (uvc_trace_param & UVC_TRACE_PROBE)
1253                         printk(" <- PU %d", entity->id);
1254
1255                 if (chain->processing != NULL) {
1256                         uvc_trace(UVC_TRACE_DESCR, "Found multiple "
1257                                 "Processing Units in chain.\n");
1258                         return -1;
1259                 }
1260
1261                 chain->processing = entity;
1262                 break;
1263
1264         case UVC_VC_SELECTOR_UNIT:
1265                 if (uvc_trace_param & UVC_TRACE_PROBE)
1266                         printk(" <- SU %d", entity->id);
1267
1268                 /* Single-input selector units are ignored. */
1269                 if (entity->bNrInPins == 1)
1270                         break;
1271
1272                 if (chain->selector != NULL) {
1273                         uvc_trace(UVC_TRACE_DESCR, "Found multiple Selector "
1274                                 "Units in chain.\n");
1275                         return -1;
1276                 }
1277
1278                 chain->selector = entity;
1279                 break;
1280
1281         case UVC_ITT_VENDOR_SPECIFIC:
1282         case UVC_ITT_CAMERA:
1283         case UVC_ITT_MEDIA_TRANSPORT_INPUT:
1284                 if (uvc_trace_param & UVC_TRACE_PROBE)
1285                         printk(" <- IT %d\n", entity->id);
1286
1287                 break;
1288
1289         case UVC_OTT_VENDOR_SPECIFIC:
1290         case UVC_OTT_DISPLAY:
1291         case UVC_OTT_MEDIA_TRANSPORT_OUTPUT:
1292                 if (uvc_trace_param & UVC_TRACE_PROBE)
1293                         printk(" OT %d", entity->id);
1294
1295                 break;
1296
1297         case UVC_TT_STREAMING:
1298                 if (UVC_ENTITY_IS_ITERM(entity)) {
1299                         if (uvc_trace_param & UVC_TRACE_PROBE)
1300                                 printk(" <- IT %d\n", entity->id);
1301                 } else {
1302                         if (uvc_trace_param & UVC_TRACE_PROBE)
1303                                 printk(" OT %d", entity->id);
1304                 }
1305
1306                 break;
1307
1308         default:
1309                 uvc_trace(UVC_TRACE_DESCR, "Unsupported entity type "
1310                         "0x%04x found in chain.\n", UVC_ENTITY_TYPE(entity));
1311                 return -1;
1312         }
1313
1314         list_add_tail(&entity->chain, &chain->entities);
1315         return 0;
1316 }
1317
1318 static int uvc_scan_chain_forward(struct uvc_video_chain *chain,
1319         struct uvc_entity *entity, struct uvc_entity *prev)
1320 {
1321         struct uvc_entity *forward;
1322         int found;
1323
1324         /* Forward scan */
1325         forward = NULL;
1326         found = 0;
1327
1328         while (1) {
1329                 forward = uvc_entity_by_reference(chain->dev, entity->id,
1330                         forward);
1331                 if (forward == NULL)
1332                         break;
1333                 if (forward == prev)
1334                         continue;
1335
1336                 switch (UVC_ENTITY_TYPE(forward)) {
1337                 case UVC_VC_EXTENSION_UNIT:
1338                         if (forward->bNrInPins != 1) {
1339                                 uvc_trace(UVC_TRACE_DESCR, "Extension unit %d "
1340                                           "has more than 1 input pin.\n",
1341                                           entity->id);
1342                                 return -EINVAL;
1343                         }
1344
1345                         list_add_tail(&forward->chain, &chain->entities);
1346                         if (uvc_trace_param & UVC_TRACE_PROBE) {
1347                                 if (!found)
1348                                         printk(" (->");
1349
1350                                 printk(" XU %d", forward->id);
1351                                 found = 1;
1352                         }
1353                         break;
1354
1355                 case UVC_OTT_VENDOR_SPECIFIC:
1356                 case UVC_OTT_DISPLAY:
1357                 case UVC_OTT_MEDIA_TRANSPORT_OUTPUT:
1358                 case UVC_TT_STREAMING:
1359                         if (UVC_ENTITY_IS_ITERM(forward)) {
1360                                 uvc_trace(UVC_TRACE_DESCR, "Unsupported input "
1361                                         "terminal %u.\n", forward->id);
1362                                 return -EINVAL;
1363                         }
1364
1365                         list_add_tail(&forward->chain, &chain->entities);
1366                         if (uvc_trace_param & UVC_TRACE_PROBE) {
1367                                 if (!found)
1368                                         printk(" (->");
1369
1370                                 printk(" OT %d", forward->id);
1371                                 found = 1;
1372                         }
1373                         break;
1374                 }
1375         }
1376         if (found)
1377                 printk(")");
1378
1379         return 0;
1380 }
1381
1382 static int uvc_scan_chain_backward(struct uvc_video_chain *chain,
1383         struct uvc_entity **_entity)
1384 {
1385         struct uvc_entity *entity = *_entity;
1386         struct uvc_entity *term;
1387         int id = -EINVAL, i;
1388
1389         switch (UVC_ENTITY_TYPE(entity)) {
1390         case UVC_VC_EXTENSION_UNIT:
1391         case UVC_VC_PROCESSING_UNIT:
1392                 id = entity->baSourceID[0];
1393                 break;
1394
1395         case UVC_VC_SELECTOR_UNIT:
1396                 /* Single-input selector units are ignored. */
1397                 if (entity->bNrInPins == 1) {
1398                         id = entity->baSourceID[0];
1399                         break;
1400                 }
1401
1402                 if (uvc_trace_param & UVC_TRACE_PROBE)
1403                         printk(" <- IT");
1404
1405                 chain->selector = entity;
1406                 for (i = 0; i < entity->bNrInPins; ++i) {
1407                         id = entity->baSourceID[i];
1408                         term = uvc_entity_by_id(chain->dev, id);
1409                         if (term == NULL || !UVC_ENTITY_IS_ITERM(term)) {
1410                                 uvc_trace(UVC_TRACE_DESCR, "Selector unit %d "
1411                                         "input %d isn't connected to an "
1412                                         "input terminal\n", entity->id, i);
1413                                 return -1;
1414                         }
1415
1416                         if (uvc_trace_param & UVC_TRACE_PROBE)
1417                                 printk(" %d", term->id);
1418
1419                         list_add_tail(&term->chain, &chain->entities);
1420                         uvc_scan_chain_forward(chain, term, entity);
1421                 }
1422
1423                 if (uvc_trace_param & UVC_TRACE_PROBE)
1424                         printk("\n");
1425
1426                 id = 0;
1427                 break;
1428
1429         case UVC_ITT_VENDOR_SPECIFIC:
1430         case UVC_ITT_CAMERA:
1431         case UVC_ITT_MEDIA_TRANSPORT_INPUT:
1432         case UVC_OTT_VENDOR_SPECIFIC:
1433         case UVC_OTT_DISPLAY:
1434         case UVC_OTT_MEDIA_TRANSPORT_OUTPUT:
1435         case UVC_TT_STREAMING:
1436                 id = UVC_ENTITY_IS_OTERM(entity) ? entity->baSourceID[0] : 0;
1437                 break;
1438         }
1439
1440         if (id <= 0) {
1441                 *_entity = NULL;
1442                 return id;
1443         }
1444
1445         entity = uvc_entity_by_id(chain->dev, id);
1446         if (entity == NULL) {
1447                 uvc_trace(UVC_TRACE_DESCR, "Found reference to "
1448                         "unknown entity %d.\n", id);
1449                 return -EINVAL;
1450         }
1451
1452         *_entity = entity;
1453         return 0;
1454 }
1455
1456 static int uvc_scan_chain(struct uvc_video_chain *chain,
1457                           struct uvc_entity *term)
1458 {
1459         struct uvc_entity *entity, *prev;
1460
1461         uvc_trace(UVC_TRACE_PROBE, "Scanning UVC chain:");
1462
1463         entity = term;
1464         prev = NULL;
1465
1466         while (entity != NULL) {
1467                 /* Entity must not be part of an existing chain */
1468                 if (entity->chain.next || entity->chain.prev) {
1469                         uvc_trace(UVC_TRACE_DESCR, "Found reference to "
1470                                 "entity %d already in chain.\n", entity->id);
1471                         return -EINVAL;
1472                 }
1473
1474                 /* Process entity */
1475                 if (uvc_scan_chain_entity(chain, entity) < 0)
1476                         return -EINVAL;
1477
1478                 /* Forward scan */
1479                 if (uvc_scan_chain_forward(chain, entity, prev) < 0)
1480                         return -EINVAL;
1481
1482                 /* Backward scan */
1483                 prev = entity;
1484                 if (uvc_scan_chain_backward(chain, &entity) < 0)
1485                         return -EINVAL;
1486         }
1487
1488         return 0;
1489 }
1490
1491 static unsigned int uvc_print_terms(struct list_head *terms, u16 dir,
1492                 char *buffer)
1493 {
1494         struct uvc_entity *term;
1495         unsigned int nterms = 0;
1496         char *p = buffer;
1497
1498         list_for_each_entry(term, terms, chain) {
1499                 if (!UVC_ENTITY_IS_TERM(term) ||
1500                     UVC_TERM_DIRECTION(term) != dir)
1501                         continue;
1502
1503                 if (nterms)
1504                         p += sprintf(p, ",");
1505                 if (++nterms >= 4) {
1506                         p += sprintf(p, "...");
1507                         break;
1508                 }
1509                 p += sprintf(p, "%u", term->id);
1510         }
1511
1512         return p - buffer;
1513 }
1514
1515 static const char *uvc_print_chain(struct uvc_video_chain *chain)
1516 {
1517         static char buffer[43];
1518         char *p = buffer;
1519
1520         p += uvc_print_terms(&chain->entities, UVC_TERM_INPUT, p);
1521         p += sprintf(p, " -> ");
1522         uvc_print_terms(&chain->entities, UVC_TERM_OUTPUT, p);
1523
1524         return buffer;
1525 }
1526
1527 /*
1528  * Scan the device for video chains and register video devices.
1529  *
1530  * Chains are scanned starting at their output terminals and walked backwards.
1531  */
1532 static int uvc_scan_device(struct uvc_device *dev)
1533 {
1534         struct uvc_video_chain *chain;
1535         struct uvc_entity *term;
1536
1537         list_for_each_entry(term, &dev->entities, list) {
1538                 if (!UVC_ENTITY_IS_OTERM(term))
1539                         continue;
1540
1541                 /* If the terminal is already included in a chain, skip it.
1542                  * This can happen for chains that have multiple output
1543                  * terminals, where all output terminals beside the first one
1544                  * will be inserted in the chain in forward scans.
1545                  */
1546                 if (term->chain.next || term->chain.prev)
1547                         continue;
1548
1549                 chain = kzalloc(sizeof(*chain), GFP_KERNEL);
1550                 if (chain == NULL)
1551                         return -ENOMEM;
1552
1553                 INIT_LIST_HEAD(&chain->entities);
1554                 mutex_init(&chain->ctrl_mutex);
1555                 chain->dev = dev;
1556
1557                 if (uvc_scan_chain(chain, term) < 0) {
1558                         kfree(chain);
1559                         continue;
1560                 }
1561
1562                 uvc_trace(UVC_TRACE_PROBE, "Found a valid video chain (%s).\n",
1563                           uvc_print_chain(chain));
1564
1565                 list_add_tail(&chain->list, &dev->chains);
1566         }
1567
1568         if (list_empty(&dev->chains)) {
1569                 uvc_printk(KERN_INFO, "No valid video chain found.\n");
1570                 return -1;
1571         }
1572
1573         return 0;
1574 }
1575
1576 /* ------------------------------------------------------------------------
1577  * Video device registration and unregistration
1578  */
1579
1580 /*
1581  * Delete the UVC device.
1582  *
1583  * Called by the kernel when the last reference to the uvc_device structure
1584  * is released.
1585  *
1586  * As this function is called after or during disconnect(), all URBs have
1587  * already been canceled by the USB core. There is no need to kill the
1588  * interrupt URB manually.
1589  */
1590 static void uvc_delete(struct uvc_device *dev)
1591 {
1592         struct list_head *p, *n;
1593
1594         usb_put_intf(dev->intf);
1595         usb_put_dev(dev->udev);
1596
1597         uvc_status_cleanup(dev);
1598         uvc_ctrl_cleanup_device(dev);
1599
1600         if (dev->vdev.dev)
1601                 v4l2_device_unregister(&dev->vdev);
1602 #ifdef CONFIG_MEDIA_CONTROLLER
1603         if (media_devnode_is_registered(&dev->mdev.devnode))
1604                 media_device_unregister(&dev->mdev);
1605 #endif
1606
1607         list_for_each_safe(p, n, &dev->chains) {
1608                 struct uvc_video_chain *chain;
1609                 chain = list_entry(p, struct uvc_video_chain, list);
1610                 kfree(chain);
1611         }
1612
1613         list_for_each_safe(p, n, &dev->entities) {
1614                 struct uvc_entity *entity;
1615                 entity = list_entry(p, struct uvc_entity, list);
1616 #ifdef CONFIG_MEDIA_CONTROLLER
1617                 uvc_mc_cleanup_entity(entity);
1618 #endif
1619                 if (entity->vdev) {
1620                         video_device_release(entity->vdev);
1621                         entity->vdev = NULL;
1622                 }
1623                 kfree(entity);
1624         }
1625
1626         list_for_each_safe(p, n, &dev->streams) {
1627                 struct uvc_streaming *streaming;
1628                 streaming = list_entry(p, struct uvc_streaming, list);
1629                 usb_driver_release_interface(&uvc_driver.driver,
1630                         streaming->intf);
1631                 usb_put_intf(streaming->intf);
1632                 kfree(streaming->format);
1633                 kfree(streaming->header.bmaControls);
1634                 kfree(streaming);
1635         }
1636
1637         kfree(dev);
1638 }
1639
1640 static void uvc_release(struct video_device *vdev)
1641 {
1642         struct uvc_streaming *stream = video_get_drvdata(vdev);
1643         struct uvc_device *dev = stream->dev;
1644
1645         /* Decrement the registered streams count and delete the device when it
1646          * reaches zero.
1647          */
1648         if (atomic_dec_and_test(&dev->nstreams))
1649                 uvc_delete(dev);
1650 }
1651
1652 /*
1653  * Unregister the video devices.
1654  */
1655 static void uvc_unregister_video(struct uvc_device *dev)
1656 {
1657         struct uvc_streaming *stream;
1658
1659         /* Unregistering all video devices might result in uvc_delete() being
1660          * called from inside the loop if there's no open file handle. To avoid
1661          * that, increment the stream count before iterating over the streams
1662          * and decrement it when done.
1663          */
1664         atomic_inc(&dev->nstreams);
1665
1666         list_for_each_entry(stream, &dev->streams, list) {
1667                 if (stream->vdev == NULL)
1668                         continue;
1669
1670                 video_unregister_device(stream->vdev);
1671                 stream->vdev = NULL;
1672         }
1673
1674         /* Decrement the stream count and call uvc_delete explicitly if there
1675          * are no stream left.
1676          */
1677         if (atomic_dec_and_test(&dev->nstreams))
1678                 uvc_delete(dev);
1679 }
1680
1681 static int uvc_register_video(struct uvc_device *dev,
1682                 struct uvc_streaming *stream)
1683 {
1684         struct video_device *vdev;
1685         int ret;
1686
1687         /* Initialize the streaming interface with default streaming
1688          * parameters.
1689          */
1690         ret = uvc_video_init(stream);
1691         if (ret < 0) {
1692                 uvc_printk(KERN_ERR, "Failed to initialize the device "
1693                         "(%d).\n", ret);
1694                 return ret;
1695         }
1696
1697         /* Register the device with V4L. */
1698         vdev = video_device_alloc();
1699         if (vdev == NULL) {
1700                 uvc_printk(KERN_ERR, "Failed to allocate video device (%d).\n",
1701                            ret);
1702                 return -ENOMEM;
1703         }
1704
1705         /* We already hold a reference to dev->udev. The video device will be
1706          * unregistered before the reference is released, so we don't need to
1707          * get another one.
1708          */
1709         vdev->v4l2_dev = &dev->vdev;
1710         vdev->fops = &uvc_fops;
1711         vdev->release = uvc_release;
1712         strlcpy(vdev->name, dev->name, sizeof vdev->name);
1713
1714         /* Set the driver data before calling video_register_device, otherwise
1715          * uvc_v4l2_open might race us.
1716          */
1717         stream->vdev = vdev;
1718         video_set_drvdata(vdev, stream);
1719
1720         ret = video_register_device(vdev, VFL_TYPE_GRABBER, -1);
1721         if (ret < 0) {
1722                 uvc_printk(KERN_ERR, "Failed to register video device (%d).\n",
1723                            ret);
1724                 stream->vdev = NULL;
1725                 video_device_release(vdev);
1726                 return ret;
1727         }
1728
1729         atomic_inc(&dev->nstreams);
1730         return 0;
1731 }
1732
1733 /*
1734  * Register all video devices in all chains.
1735  */
1736 static int uvc_register_terms(struct uvc_device *dev,
1737         struct uvc_video_chain *chain)
1738 {
1739         struct uvc_streaming *stream;
1740         struct uvc_entity *term;
1741         int ret;
1742
1743         list_for_each_entry(term, &chain->entities, chain) {
1744                 if (UVC_ENTITY_TYPE(term) != UVC_TT_STREAMING)
1745                         continue;
1746
1747                 stream = uvc_stream_by_id(dev, term->id);
1748                 if (stream == NULL) {
1749                         uvc_printk(KERN_INFO, "No streaming interface found "
1750                                    "for terminal %u.", term->id);
1751                         continue;
1752                 }
1753
1754                 stream->chain = chain;
1755                 ret = uvc_register_video(dev, stream);
1756                 if (ret < 0)
1757                         return ret;
1758
1759                 term->vdev = stream->vdev;
1760         }
1761
1762         return 0;
1763 }
1764
1765 static int uvc_register_chains(struct uvc_device *dev)
1766 {
1767         struct uvc_video_chain *chain;
1768         int ret;
1769
1770         list_for_each_entry(chain, &dev->chains, list) {
1771                 ret = uvc_register_terms(dev, chain);
1772                 if (ret < 0)
1773                         return ret;
1774
1775 #ifdef CONFIG_MEDIA_CONTROLLER
1776                 ret = uvc_mc_register_entities(chain);
1777                 if (ret < 0) {
1778                         uvc_printk(KERN_INFO, "Failed to register entites "
1779                                 "(%d).\n", ret);
1780                 }
1781 #endif
1782         }
1783
1784         return 0;
1785 }
1786
1787 /* ------------------------------------------------------------------------
1788  * USB probe, disconnect, suspend and resume
1789  */
1790
1791 static int uvc_probe(struct usb_interface *intf,
1792                      const struct usb_device_id *id)
1793 {
1794         struct usb_device *udev = interface_to_usbdev(intf);
1795         struct uvc_device *dev;
1796         int ret;
1797
1798         if (id->idVendor && id->idProduct)
1799                 uvc_trace(UVC_TRACE_PROBE, "Probing known UVC device %s "
1800                                 "(%04x:%04x)\n", udev->devpath, id->idVendor,
1801                                 id->idProduct);
1802         else
1803                 uvc_trace(UVC_TRACE_PROBE, "Probing generic UVC device %s\n",
1804                                 udev->devpath);
1805
1806         /* Allocate memory for the device and initialize it. */
1807         if ((dev = kzalloc(sizeof *dev, GFP_KERNEL)) == NULL)
1808                 return -ENOMEM;
1809
1810         INIT_LIST_HEAD(&dev->entities);
1811         INIT_LIST_HEAD(&dev->chains);
1812         INIT_LIST_HEAD(&dev->streams);
1813         atomic_set(&dev->nstreams, 0);
1814         atomic_set(&dev->users, 0);
1815         atomic_set(&dev->nmappings, 0);
1816
1817         dev->udev = usb_get_dev(udev);
1818         dev->intf = usb_get_intf(intf);
1819         dev->intfnum = intf->cur_altsetting->desc.bInterfaceNumber;
1820         dev->quirks = (uvc_quirks_param == -1)
1821                     ? id->driver_info : uvc_quirks_param;
1822
1823         if (udev->product != NULL)
1824                 strlcpy(dev->name, udev->product, sizeof dev->name);
1825         else
1826                 snprintf(dev->name, sizeof dev->name,
1827                         "UVC Camera (%04x:%04x)",
1828                         le16_to_cpu(udev->descriptor.idVendor),
1829                         le16_to_cpu(udev->descriptor.idProduct));
1830
1831         /* Parse the Video Class control descriptor. */
1832         if (uvc_parse_control(dev) < 0) {
1833                 uvc_trace(UVC_TRACE_PROBE, "Unable to parse UVC "
1834                         "descriptors.\n");
1835                 goto error;
1836         }
1837
1838         uvc_printk(KERN_INFO, "Found UVC %u.%02x device %s (%04x:%04x)\n",
1839                 dev->uvc_version >> 8, dev->uvc_version & 0xff,
1840                 udev->product ? udev->product : "<unnamed>",
1841                 le16_to_cpu(udev->descriptor.idVendor),
1842                 le16_to_cpu(udev->descriptor.idProduct));
1843
1844         if (dev->quirks != id->driver_info) {
1845                 uvc_printk(KERN_INFO, "Forcing device quirks to 0x%x by module "
1846                         "parameter for testing purpose.\n", dev->quirks);
1847                 uvc_printk(KERN_INFO, "Please report required quirks to the "
1848                         "linux-uvc-devel mailing list.\n");
1849         }
1850
1851         /* Register the media and V4L2 devices. */
1852 #ifdef CONFIG_MEDIA_CONTROLLER
1853         dev->mdev.dev = &intf->dev;
1854         strlcpy(dev->mdev.model, dev->name, sizeof(dev->mdev.model));
1855         if (udev->serial)
1856                 strlcpy(dev->mdev.serial, udev->serial,
1857                         sizeof(dev->mdev.serial));
1858         strcpy(dev->mdev.bus_info, udev->devpath);
1859         dev->mdev.hw_revision = le16_to_cpu(udev->descriptor.bcdDevice);
1860         dev->mdev.driver_version = DRIVER_VERSION_NUMBER;
1861         if (media_device_register(&dev->mdev) < 0)
1862                 goto error;
1863
1864         dev->vdev.mdev = &dev->mdev;
1865 #endif
1866         if (v4l2_device_register(&intf->dev, &dev->vdev) < 0)
1867                 goto error;
1868
1869         /* Initialize controls. */
1870         if (uvc_ctrl_init_device(dev) < 0)
1871                 goto error;
1872
1873         /* Scan the device for video chains. */
1874         if (uvc_scan_device(dev) < 0)
1875                 goto error;
1876
1877         /* Register video device nodes. */
1878         if (uvc_register_chains(dev) < 0)
1879                 goto error;
1880
1881         /* Save our data pointer in the interface data. */
1882         usb_set_intfdata(intf, dev);
1883
1884         /* Initialize the interrupt URB. */
1885         if ((ret = uvc_status_init(dev)) < 0) {
1886                 uvc_printk(KERN_INFO, "Unable to initialize the status "
1887                         "endpoint (%d), status interrupt will not be "
1888                         "supported.\n", ret);
1889         }
1890
1891         uvc_trace(UVC_TRACE_PROBE, "UVC device initialized.\n");
1892         usb_enable_autosuspend(udev);
1893         return 0;
1894
1895 error:
1896         uvc_unregister_video(dev);
1897         return -ENODEV;
1898 }
1899
1900 static void uvc_disconnect(struct usb_interface *intf)
1901 {
1902         struct uvc_device *dev = usb_get_intfdata(intf);
1903
1904         /* Set the USB interface data to NULL. This can be done outside the
1905          * lock, as there's no other reader.
1906          */
1907         usb_set_intfdata(intf, NULL);
1908
1909         if (intf->cur_altsetting->desc.bInterfaceSubClass ==
1910             UVC_SC_VIDEOSTREAMING)
1911                 return;
1912
1913         dev->state |= UVC_DEV_DISCONNECTED;
1914
1915         uvc_unregister_video(dev);
1916 }
1917
1918 static int uvc_suspend(struct usb_interface *intf, pm_message_t message)
1919 {
1920         struct uvc_device *dev = usb_get_intfdata(intf);
1921         struct uvc_streaming *stream;
1922
1923         uvc_trace(UVC_TRACE_SUSPEND, "Suspending interface %u\n",
1924                 intf->cur_altsetting->desc.bInterfaceNumber);
1925
1926         /* Controls are cached on the fly so they don't need to be saved. */
1927         if (intf->cur_altsetting->desc.bInterfaceSubClass ==
1928             UVC_SC_VIDEOCONTROL)
1929                 return uvc_status_suspend(dev);
1930
1931         list_for_each_entry(stream, &dev->streams, list) {
1932                 if (stream->intf == intf)
1933                         return uvc_video_suspend(stream);
1934         }
1935
1936         uvc_trace(UVC_TRACE_SUSPEND, "Suspend: video streaming USB interface "
1937                         "mismatch.\n");
1938         return -EINVAL;
1939 }
1940
1941 static int __uvc_resume(struct usb_interface *intf, int reset)
1942 {
1943         struct uvc_device *dev = usb_get_intfdata(intf);
1944         struct uvc_streaming *stream;
1945
1946         uvc_trace(UVC_TRACE_SUSPEND, "Resuming interface %u\n",
1947                 intf->cur_altsetting->desc.bInterfaceNumber);
1948
1949         if (intf->cur_altsetting->desc.bInterfaceSubClass ==
1950             UVC_SC_VIDEOCONTROL) {
1951                 if (reset) {
1952                         int ret = uvc_ctrl_resume_device(dev);
1953
1954                         if (ret < 0)
1955                                 return ret;
1956                 }
1957
1958                 return uvc_status_resume(dev);
1959         }
1960
1961         list_for_each_entry(stream, &dev->streams, list) {
1962                 if (stream->intf == intf)
1963                         return uvc_video_resume(stream);
1964         }
1965
1966         uvc_trace(UVC_TRACE_SUSPEND, "Resume: video streaming USB interface "
1967                         "mismatch.\n");
1968         return -EINVAL;
1969 }
1970
1971 static int uvc_resume(struct usb_interface *intf)
1972 {
1973         return __uvc_resume(intf, 0);
1974 }
1975
1976 static int uvc_reset_resume(struct usb_interface *intf)
1977 {
1978         return __uvc_resume(intf, 1);
1979 }
1980
1981 /* ------------------------------------------------------------------------
1982  * Module parameters
1983  */
1984
1985 static int uvc_clock_param_get(char *buffer, struct kernel_param *kp)
1986 {
1987         if (uvc_clock_param == CLOCK_MONOTONIC)
1988                 return sprintf(buffer, "CLOCK_MONOTONIC");
1989         else
1990                 return sprintf(buffer, "CLOCK_REALTIME");
1991 }
1992
1993 static int uvc_clock_param_set(const char *val, struct kernel_param *kp)
1994 {
1995         if (strncasecmp(val, "clock_", strlen("clock_")) == 0)
1996                 val += strlen("clock_");
1997
1998         if (strcasecmp(val, "monotonic") == 0)
1999                 uvc_clock_param = CLOCK_MONOTONIC;
2000         else if (strcasecmp(val, "realtime") == 0)
2001                 uvc_clock_param = CLOCK_REALTIME;
2002         else
2003                 return -EINVAL;
2004
2005         return 0;
2006 }
2007
2008 module_param_call(clock, uvc_clock_param_set, uvc_clock_param_get,
2009                   &uvc_clock_param, S_IRUGO|S_IWUSR);
2010 MODULE_PARM_DESC(clock, "Video buffers timestamp clock");
2011 module_param_named(nodrop, uvc_no_drop_param, uint, S_IRUGO|S_IWUSR);
2012 MODULE_PARM_DESC(nodrop, "Don't drop incomplete frames");
2013 module_param_named(quirks, uvc_quirks_param, uint, S_IRUGO|S_IWUSR);
2014 MODULE_PARM_DESC(quirks, "Forced device quirks");
2015 module_param_named(trace, uvc_trace_param, uint, S_IRUGO|S_IWUSR);
2016 MODULE_PARM_DESC(trace, "Trace level bitmask");
2017 module_param_named(timeout, uvc_timeout_param, uint, S_IRUGO|S_IWUSR);
2018 MODULE_PARM_DESC(timeout, "Streaming control requests timeout");
2019
2020 /* ------------------------------------------------------------------------
2021  * Driver initialization and cleanup
2022  */
2023
2024 /*
2025  * The Logitech cameras listed below have their interface class set to
2026  * VENDOR_SPEC because they don't announce themselves as UVC devices, even
2027  * though they are compliant.
2028  */
2029 static struct usb_device_id uvc_ids[] = {
2030         /* Genius eFace 2025 */
2031         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2032                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2033           .idVendor             = 0x0458,
2034           .idProduct            = 0x706e,
2035           .bInterfaceClass      = USB_CLASS_VIDEO,
2036           .bInterfaceSubClass   = 1,
2037           .bInterfaceProtocol   = 0,
2038           .driver_info          = UVC_QUIRK_PROBE_MINMAX },
2039         /* Microsoft Lifecam NX-6000 */
2040         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2041                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2042           .idVendor             = 0x045e,
2043           .idProduct            = 0x00f8,
2044           .bInterfaceClass      = USB_CLASS_VIDEO,
2045           .bInterfaceSubClass   = 1,
2046           .bInterfaceProtocol   = 0,
2047           .driver_info          = UVC_QUIRK_PROBE_MINMAX },
2048         /* Microsoft Lifecam VX-7000 */
2049         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2050                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2051           .idVendor             = 0x045e,
2052           .idProduct            = 0x0723,
2053           .bInterfaceClass      = USB_CLASS_VIDEO,
2054           .bInterfaceSubClass   = 1,
2055           .bInterfaceProtocol   = 0,
2056           .driver_info          = UVC_QUIRK_PROBE_MINMAX },
2057         /* Logitech Quickcam Fusion */
2058         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2059                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2060           .idVendor             = 0x046d,
2061           .idProduct            = 0x08c1,
2062           .bInterfaceClass      = USB_CLASS_VENDOR_SPEC,
2063           .bInterfaceSubClass   = 1,
2064           .bInterfaceProtocol   = 0 },
2065         /* Logitech Quickcam Orbit MP */
2066         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2067                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2068           .idVendor             = 0x046d,
2069           .idProduct            = 0x08c2,
2070           .bInterfaceClass      = USB_CLASS_VENDOR_SPEC,
2071           .bInterfaceSubClass   = 1,
2072           .bInterfaceProtocol   = 0 },
2073         /* Logitech Quickcam Pro for Notebook */
2074         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2075                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2076           .idVendor             = 0x046d,
2077           .idProduct            = 0x08c3,
2078           .bInterfaceClass      = USB_CLASS_VENDOR_SPEC,
2079           .bInterfaceSubClass   = 1,
2080           .bInterfaceProtocol   = 0 },
2081         /* Logitech Quickcam Pro 5000 */
2082         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2083                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2084           .idVendor             = 0x046d,
2085           .idProduct            = 0x08c5,
2086           .bInterfaceClass      = USB_CLASS_VENDOR_SPEC,
2087           .bInterfaceSubClass   = 1,
2088           .bInterfaceProtocol   = 0 },
2089         /* Logitech Quickcam OEM Dell Notebook */
2090         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2091                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2092           .idVendor             = 0x046d,
2093           .idProduct            = 0x08c6,
2094           .bInterfaceClass      = USB_CLASS_VENDOR_SPEC,
2095           .bInterfaceSubClass   = 1,
2096           .bInterfaceProtocol   = 0 },
2097         /* Logitech Quickcam OEM Cisco VT Camera II */
2098         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2099                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2100           .idVendor             = 0x046d,
2101           .idProduct            = 0x08c7,
2102           .bInterfaceClass      = USB_CLASS_VENDOR_SPEC,
2103           .bInterfaceSubClass   = 1,
2104           .bInterfaceProtocol   = 0 },
2105         /* Chicony CNF7129 (Asus EEE 100HE) */
2106         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2107                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2108           .idVendor             = 0x04f2,
2109           .idProduct            = 0xb071,
2110           .bInterfaceClass      = USB_CLASS_VIDEO,
2111           .bInterfaceSubClass   = 1,
2112           .bInterfaceProtocol   = 0,
2113           .driver_info          = UVC_QUIRK_RESTRICT_FRAME_RATE },
2114         /* Alcor Micro AU3820 (Future Boy PC USB Webcam) */
2115         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2116                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2117           .idVendor             = 0x058f,
2118           .idProduct            = 0x3820,
2119           .bInterfaceClass      = USB_CLASS_VIDEO,
2120           .bInterfaceSubClass   = 1,
2121           .bInterfaceProtocol   = 0,
2122           .driver_info          = UVC_QUIRK_PROBE_MINMAX },
2123         /* Apple Built-In iSight */
2124         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2125                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2126           .idVendor             = 0x05ac,
2127           .idProduct            = 0x8501,
2128           .bInterfaceClass      = USB_CLASS_VIDEO,
2129           .bInterfaceSubClass   = 1,
2130           .bInterfaceProtocol   = 0,
2131           .driver_info          = UVC_QUIRK_PROBE_MINMAX
2132                                 | UVC_QUIRK_BUILTIN_ISIGHT },
2133         /* Genesys Logic USB 2.0 PC Camera */
2134         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2135                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2136           .idVendor             = 0x05e3,
2137           .idProduct            = 0x0505,
2138           .bInterfaceClass      = USB_CLASS_VIDEO,
2139           .bInterfaceSubClass   = 1,
2140           .bInterfaceProtocol   = 0,
2141           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2142         /* Hercules Classic Silver */
2143         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2144                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2145           .idVendor             = 0x06f8,
2146           .idProduct            = 0x300c,
2147           .bInterfaceClass      = USB_CLASS_VIDEO,
2148           .bInterfaceSubClass   = 1,
2149           .bInterfaceProtocol   = 0,
2150           .driver_info          = UVC_QUIRK_FIX_BANDWIDTH },
2151         /* ViMicro Vega */
2152         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2153                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2154           .idVendor             = 0x0ac8,
2155           .idProduct            = 0x332d,
2156           .bInterfaceClass      = USB_CLASS_VIDEO,
2157           .bInterfaceSubClass   = 1,
2158           .bInterfaceProtocol   = 0,
2159           .driver_info          = UVC_QUIRK_FIX_BANDWIDTH },
2160         /* ViMicro - Minoru3D */
2161         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2162                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2163           .idVendor             = 0x0ac8,
2164           .idProduct            = 0x3410,
2165           .bInterfaceClass      = USB_CLASS_VIDEO,
2166           .bInterfaceSubClass   = 1,
2167           .bInterfaceProtocol   = 0,
2168           .driver_info          = UVC_QUIRK_FIX_BANDWIDTH },
2169         /* ViMicro Venus - Minoru3D */
2170         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2171                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2172           .idVendor             = 0x0ac8,
2173           .idProduct            = 0x3420,
2174           .bInterfaceClass      = USB_CLASS_VIDEO,
2175           .bInterfaceSubClass   = 1,
2176           .bInterfaceProtocol   = 0,
2177           .driver_info          = UVC_QUIRK_FIX_BANDWIDTH },
2178         /* MT6227 */
2179         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2180                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2181           .idVendor             = 0x0e8d,
2182           .idProduct            = 0x0004,
2183           .bInterfaceClass      = USB_CLASS_VIDEO,
2184           .bInterfaceSubClass   = 1,
2185           .bInterfaceProtocol   = 0,
2186           .driver_info          = UVC_QUIRK_PROBE_MINMAX
2187                                 | UVC_QUIRK_PROBE_DEF },
2188         /* IMC Networks (Medion Akoya) */
2189         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2190                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2191           .idVendor             = 0x13d3,
2192           .idProduct            = 0x5103,
2193           .bInterfaceClass      = USB_CLASS_VIDEO,
2194           .bInterfaceSubClass   = 1,
2195           .bInterfaceProtocol   = 0,
2196           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2197         /* JMicron USB2.0 XGA WebCam */
2198         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2199                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2200           .idVendor             = 0x152d,
2201           .idProduct            = 0x0310,
2202           .bInterfaceClass      = USB_CLASS_VIDEO,
2203           .bInterfaceSubClass   = 1,
2204           .bInterfaceProtocol   = 0,
2205           .driver_info          = UVC_QUIRK_PROBE_MINMAX },
2206         /* Syntek (HP Spartan) */
2207         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2208                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2209           .idVendor             = 0x174f,
2210           .idProduct            = 0x5212,
2211           .bInterfaceClass      = USB_CLASS_VIDEO,
2212           .bInterfaceSubClass   = 1,
2213           .bInterfaceProtocol   = 0,
2214           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2215         /* Syntek (Samsung Q310) */
2216         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2217                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2218           .idVendor             = 0x174f,
2219           .idProduct            = 0x5931,
2220           .bInterfaceClass      = USB_CLASS_VIDEO,
2221           .bInterfaceSubClass   = 1,
2222           .bInterfaceProtocol   = 0,
2223           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2224         /* Syntek (Packard Bell EasyNote MX52 */
2225         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2226                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2227           .idVendor             = 0x174f,
2228           .idProduct            = 0x8a12,
2229           .bInterfaceClass      = USB_CLASS_VIDEO,
2230           .bInterfaceSubClass   = 1,
2231           .bInterfaceProtocol   = 0,
2232           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2233         /* Syntek (Asus F9SG) */
2234         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2235                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2236           .idVendor             = 0x174f,
2237           .idProduct            = 0x8a31,
2238           .bInterfaceClass      = USB_CLASS_VIDEO,
2239           .bInterfaceSubClass   = 1,
2240           .bInterfaceProtocol   = 0,
2241           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2242         /* Syntek (Asus U3S) */
2243         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2244                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2245           .idVendor             = 0x174f,
2246           .idProduct            = 0x8a33,
2247           .bInterfaceClass      = USB_CLASS_VIDEO,
2248           .bInterfaceSubClass   = 1,
2249           .bInterfaceProtocol   = 0,
2250           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2251         /* Syntek (JAOtech Smart Terminal) */
2252         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2253                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2254           .idVendor             = 0x174f,
2255           .idProduct            = 0x8a34,
2256           .bInterfaceClass      = USB_CLASS_VIDEO,
2257           .bInterfaceSubClass   = 1,
2258           .bInterfaceProtocol   = 0,
2259           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2260         /* Miricle 307K */
2261         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2262                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2263           .idVendor             = 0x17dc,
2264           .idProduct            = 0x0202,
2265           .bInterfaceClass      = USB_CLASS_VIDEO,
2266           .bInterfaceSubClass   = 1,
2267           .bInterfaceProtocol   = 0,
2268           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2269         /* Lenovo Thinkpad SL400/SL500 */
2270         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2271                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2272           .idVendor             = 0x17ef,
2273           .idProduct            = 0x480b,
2274           .bInterfaceClass      = USB_CLASS_VIDEO,
2275           .bInterfaceSubClass   = 1,
2276           .bInterfaceProtocol   = 0,
2277           .driver_info          = UVC_QUIRK_STREAM_NO_FID },
2278         /* Aveo Technology USB 2.0 Camera */
2279         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2280                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2281           .idVendor             = 0x1871,
2282           .idProduct            = 0x0306,
2283           .bInterfaceClass      = USB_CLASS_VIDEO,
2284           .bInterfaceSubClass   = 1,
2285           .bInterfaceProtocol   = 0,
2286           .driver_info          = UVC_QUIRK_PROBE_MINMAX
2287                                 | UVC_QUIRK_PROBE_EXTRAFIELDS },
2288         /* Ecamm Pico iMage */
2289         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2290                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2291           .idVendor             = 0x18cd,
2292           .idProduct            = 0xcafe,
2293           .bInterfaceClass      = USB_CLASS_VIDEO,
2294           .bInterfaceSubClass   = 1,
2295           .bInterfaceProtocol   = 0,
2296           .driver_info          = UVC_QUIRK_PROBE_EXTRAFIELDS },
2297         /* Manta MM-353 Plako */
2298         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2299                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2300           .idVendor             = 0x18ec,
2301           .idProduct            = 0x3188,
2302           .bInterfaceClass      = USB_CLASS_VIDEO,
2303           .bInterfaceSubClass   = 1,
2304           .bInterfaceProtocol   = 0,
2305           .driver_info          = UVC_QUIRK_PROBE_MINMAX },
2306         /* FSC WebCam V30S */
2307         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2308                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2309           .idVendor             = 0x18ec,
2310           .idProduct            = 0x3288,
2311           .bInterfaceClass      = USB_CLASS_VIDEO,
2312           .bInterfaceSubClass   = 1,
2313           .bInterfaceProtocol   = 0,
2314           .driver_info          = UVC_QUIRK_PROBE_MINMAX },
2315         /* Arkmicro unbranded */
2316         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2317                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2318           .idVendor             = 0x18ec,
2319           .idProduct            = 0x3290,
2320           .bInterfaceClass      = USB_CLASS_VIDEO,
2321           .bInterfaceSubClass   = 1,
2322           .bInterfaceProtocol   = 0,
2323           .driver_info          = UVC_QUIRK_PROBE_DEF },
2324         /* Bodelin ProScopeHR */
2325         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2326                                 | USB_DEVICE_ID_MATCH_DEV_HI
2327                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2328           .idVendor             = 0x19ab,
2329           .idProduct            = 0x1000,
2330           .bcdDevice_hi         = 0x0126,
2331           .bInterfaceClass      = USB_CLASS_VIDEO,
2332           .bInterfaceSubClass   = 1,
2333           .bInterfaceProtocol   = 0,
2334           .driver_info          = UVC_QUIRK_STATUS_INTERVAL },
2335         /* MSI StarCam 370i */
2336         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2337                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2338           .idVendor             = 0x1b3b,
2339           .idProduct            = 0x2951,
2340           .bInterfaceClass      = USB_CLASS_VIDEO,
2341           .bInterfaceSubClass   = 1,
2342           .bInterfaceProtocol   = 0,
2343           .driver_info          = UVC_QUIRK_PROBE_MINMAX },
2344         /* SiGma Micro USB Web Camera */
2345         { .match_flags          = USB_DEVICE_ID_MATCH_DEVICE
2346                                 | USB_DEVICE_ID_MATCH_INT_INFO,
2347           .idVendor             = 0x1c4f,
2348           .idProduct            = 0x3000,
2349           .bInterfaceClass      = USB_CLASS_VIDEO,
2350           .bInterfaceSubClass   = 1,
2351           .bInterfaceProtocol   = 0,
2352           .driver_info          = UVC_QUIRK_PROBE_MINMAX
2353                                 | UVC_QUIRK_IGNORE_SELECTOR_UNIT },
2354         /* Generic USB Video Class */
2355         { USB_INTERFACE_INFO(USB_CLASS_VIDEO, 1, 0) },
2356         {}
2357 };
2358
2359 MODULE_DEVICE_TABLE(usb, uvc_ids);
2360
2361 struct uvc_driver uvc_driver = {
2362         .driver = {
2363                 .name           = "uvcvideo",
2364                 .probe          = uvc_probe,
2365                 .disconnect     = uvc_disconnect,
2366                 .suspend        = uvc_suspend,
2367                 .resume         = uvc_resume,
2368                 .reset_resume   = uvc_reset_resume,
2369                 .id_table       = uvc_ids,
2370                 .supports_autosuspend = 1,
2371         },
2372 };
2373
2374 static int __init uvc_init(void)
2375 {
2376         int result;
2377
2378         result = usb_register(&uvc_driver.driver);
2379         if (result == 0)
2380                 printk(KERN_INFO DRIVER_DESC " (" DRIVER_VERSION ")\n");
2381         return result;
2382 }
2383
2384 static void __exit uvc_cleanup(void)
2385 {
2386         usb_deregister(&uvc_driver.driver);
2387 }
2388
2389 module_init(uvc_init);
2390 module_exit(uvc_cleanup);
2391
2392 MODULE_AUTHOR(DRIVER_AUTHOR);
2393 MODULE_DESCRIPTION(DRIVER_DESC);
2394 MODULE_LICENSE("GPL");
2395 MODULE_VERSION(DRIVER_VERSION);
2396