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