GNU Linux-libre 4.14.290-gnu1
[releases.git] / drivers / media / usb / uvc / uvc_video.c
1 /*
2  *      uvc_video.c  --  USB Video Class driver - Video handling
3  *
4  *      Copyright (C) 2005-2010
5  *          Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6  *
7  *      This program is free software; you can redistribute it and/or modify
8  *      it under the terms of the GNU General Public License as published by
9  *      the Free Software Foundation; either version 2 of the License, or
10  *      (at your option) any later version.
11  *
12  */
13
14 #include <linux/kernel.h>
15 #include <linux/list.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18 #include <linux/usb.h>
19 #include <linux/videodev2.h>
20 #include <linux/vmalloc.h>
21 #include <linux/wait.h>
22 #include <linux/atomic.h>
23 #include <asm/unaligned.h>
24
25 #include <media/v4l2-common.h>
26
27 #include "uvcvideo.h"
28
29 /* ------------------------------------------------------------------------
30  * UVC Controls
31  */
32
33 static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
34                         __u8 intfnum, __u8 cs, void *data, __u16 size,
35                         int timeout)
36 {
37         __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
38         unsigned int pipe;
39
40         pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
41                               : usb_sndctrlpipe(dev->udev, 0);
42         type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
43
44         return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
45                         unit << 8 | intfnum, data, size, timeout);
46 }
47
48 static const char *uvc_query_name(__u8 query)
49 {
50         switch (query) {
51         case UVC_SET_CUR:
52                 return "SET_CUR";
53         case UVC_GET_CUR:
54                 return "GET_CUR";
55         case UVC_GET_MIN:
56                 return "GET_MIN";
57         case UVC_GET_MAX:
58                 return "GET_MAX";
59         case UVC_GET_RES:
60                 return "GET_RES";
61         case UVC_GET_LEN:
62                 return "GET_LEN";
63         case UVC_GET_INFO:
64                 return "GET_INFO";
65         case UVC_GET_DEF:
66                 return "GET_DEF";
67         default:
68                 return "<invalid>";
69         }
70 }
71
72 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
73                         __u8 intfnum, __u8 cs, void *data, __u16 size)
74 {
75         int ret;
76
77         ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
78                                 UVC_CTRL_CONTROL_TIMEOUT);
79         if (ret != size) {
80                 uvc_printk(KERN_ERR, "Failed to query (%s) UVC control %u on "
81                         "unit %u: %d (exp. %u).\n", uvc_query_name(query), cs,
82                         unit, ret, size);
83                 return -EIO;
84         }
85
86         return 0;
87 }
88
89 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
90         struct uvc_streaming_control *ctrl)
91 {
92         static const struct usb_device_id elgato_cam_link_4k = {
93                 USB_DEVICE(0x0fd9, 0x0066)
94         };
95         struct uvc_format *format = NULL;
96         struct uvc_frame *frame = NULL;
97         unsigned int i;
98
99         /*
100          * The response of the Elgato Cam Link 4K is incorrect: The second byte
101          * contains bFormatIndex (instead of being the second byte of bmHint).
102          * The first byte is always zero. The third byte is always 1.
103          *
104          * The UVC 1.5 class specification defines the first five bits in the
105          * bmHint bitfield. The remaining bits are reserved and should be zero.
106          * Therefore a valid bmHint will be less than 32.
107          *
108          * Latest Elgato Cam Link 4K firmware as of 2021-03-23 needs this fix.
109          * MCU: 20.02.19, FPGA: 67
110          */
111         if (usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k) &&
112             ctrl->bmHint > 255) {
113                 u8 corrected_format_index = ctrl->bmHint >> 8;
114
115                 /* uvc_dbg(stream->dev, VIDEO,
116                         "Correct USB video probe response from {bmHint: 0x%04x, bFormatIndex: %u} to {bmHint: 0x%04x, bFormatIndex: %u}\n",
117                         ctrl->bmHint, ctrl->bFormatIndex,
118                         1, corrected_format_index); */
119                 ctrl->bmHint = 1;
120                 ctrl->bFormatIndex = corrected_format_index;
121         }
122
123         for (i = 0; i < stream->nformats; ++i) {
124                 if (stream->format[i].index == ctrl->bFormatIndex) {
125                         format = &stream->format[i];
126                         break;
127                 }
128         }
129
130         if (format == NULL)
131                 return;
132
133         for (i = 0; i < format->nframes; ++i) {
134                 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
135                         frame = &format->frame[i];
136                         break;
137                 }
138         }
139
140         if (frame == NULL)
141                 return;
142
143         if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
144              (ctrl->dwMaxVideoFrameSize == 0 &&
145               stream->dev->uvc_version < 0x0110))
146                 ctrl->dwMaxVideoFrameSize =
147                         frame->dwMaxVideoFrameBufferSize;
148
149         /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
150          * compute the bandwidth on 16 bits and erroneously sign-extend it to
151          * 32 bits, resulting in a huge bandwidth value. Detect and fix that
152          * condition by setting the 16 MSBs to 0 when they're all equal to 1.
153          */
154         if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
155                 ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
156
157         if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
158             stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
159             stream->intf->num_altsetting > 1) {
160                 u32 interval;
161                 u32 bandwidth;
162
163                 interval = (ctrl->dwFrameInterval > 100000)
164                          ? ctrl->dwFrameInterval
165                          : frame->dwFrameInterval[0];
166
167                 /* Compute a bandwidth estimation by multiplying the frame
168                  * size by the number of video frames per second, divide the
169                  * result by the number of USB frames (or micro-frames for
170                  * high-speed devices) per second and add the UVC header size
171                  * (assumed to be 12 bytes long).
172                  */
173                 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
174                 bandwidth *= 10000000 / interval + 1;
175                 bandwidth /= 1000;
176                 if (stream->dev->udev->speed == USB_SPEED_HIGH)
177                         bandwidth /= 8;
178                 bandwidth += 12;
179
180                 /* The bandwidth estimate is too low for many cameras. Don't use
181                  * maximum packet sizes lower than 1024 bytes to try and work
182                  * around the problem. According to measurements done on two
183                  * different camera models, the value is high enough to get most
184                  * resolutions working while not preventing two simultaneous
185                  * VGA streams at 15 fps.
186                  */
187                 bandwidth = max_t(u32, bandwidth, 1024);
188
189                 ctrl->dwMaxPayloadTransferSize = bandwidth;
190         }
191 }
192
193 static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
194 {
195         /*
196          * Return the size of the video probe and commit controls, which depends
197          * on the protocol version.
198          */
199         if (stream->dev->uvc_version < 0x0110)
200                 return 26;
201         else if (stream->dev->uvc_version < 0x0150)
202                 return 34;
203         else
204                 return 48;
205 }
206
207 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
208         struct uvc_streaming_control *ctrl, int probe, __u8 query)
209 {
210         __u16 size = uvc_video_ctrl_size(stream);
211         __u8 *data;
212         int ret;
213
214         if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
215                         query == UVC_GET_DEF)
216                 return -EIO;
217
218         data = kmalloc(size, GFP_KERNEL);
219         if (data == NULL)
220                 return -ENOMEM;
221
222         ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
223                 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
224                 size, uvc_timeout_param);
225
226         if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
227                 /* Some cameras, mostly based on Bison Electronics chipsets,
228                  * answer a GET_MIN or GET_MAX request with the wCompQuality
229                  * field only.
230                  */
231                 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
232                         "compliance - GET_MIN/MAX(PROBE) incorrectly "
233                         "supported. Enabling workaround.\n");
234                 memset(ctrl, 0, sizeof *ctrl);
235                 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
236                 ret = 0;
237                 goto out;
238         } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
239                 /* Many cameras don't support the GET_DEF request on their
240                  * video probe control. Warn once and return, the caller will
241                  * fall back to GET_CUR.
242                  */
243                 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
244                         "compliance - GET_DEF(PROBE) not supported. "
245                         "Enabling workaround.\n");
246                 ret = -EIO;
247                 goto out;
248         } else if (ret != size) {
249                 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
250                         "%d (exp. %u).\n", query, probe ? "probe" : "commit",
251                         ret, size);
252                 ret = -EIO;
253                 goto out;
254         }
255
256         ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
257         ctrl->bFormatIndex = data[2];
258         ctrl->bFrameIndex = data[3];
259         ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
260         ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
261         ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
262         ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
263         ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
264         ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
265         ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
266         ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
267
268         if (size >= 34) {
269                 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
270                 ctrl->bmFramingInfo = data[30];
271                 ctrl->bPreferedVersion = data[31];
272                 ctrl->bMinVersion = data[32];
273                 ctrl->bMaxVersion = data[33];
274         } else {
275                 ctrl->dwClockFrequency = stream->dev->clock_frequency;
276                 ctrl->bmFramingInfo = 0;
277                 ctrl->bPreferedVersion = 0;
278                 ctrl->bMinVersion = 0;
279                 ctrl->bMaxVersion = 0;
280         }
281
282         /* Some broken devices return null or wrong dwMaxVideoFrameSize and
283          * dwMaxPayloadTransferSize fields. Try to get the value from the
284          * format and frame descriptors.
285          */
286         uvc_fixup_video_ctrl(stream, ctrl);
287         ret = 0;
288
289 out:
290         kfree(data);
291         return ret;
292 }
293
294 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
295         struct uvc_streaming_control *ctrl, int probe)
296 {
297         __u16 size = uvc_video_ctrl_size(stream);
298         __u8 *data;
299         int ret;
300
301         data = kzalloc(size, GFP_KERNEL);
302         if (data == NULL)
303                 return -ENOMEM;
304
305         *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
306         data[2] = ctrl->bFormatIndex;
307         data[3] = ctrl->bFrameIndex;
308         *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
309         *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
310         *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
311         *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
312         *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
313         *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
314         put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
315         put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
316
317         if (size >= 34) {
318                 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
319                 data[30] = ctrl->bmFramingInfo;
320                 data[31] = ctrl->bPreferedVersion;
321                 data[32] = ctrl->bMinVersion;
322                 data[33] = ctrl->bMaxVersion;
323         }
324
325         ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
326                 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
327                 size, uvc_timeout_param);
328         if (ret != size) {
329                 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
330                         "%d (exp. %u).\n", probe ? "probe" : "commit",
331                         ret, size);
332                 ret = -EIO;
333         }
334
335         kfree(data);
336         return ret;
337 }
338
339 int uvc_probe_video(struct uvc_streaming *stream,
340         struct uvc_streaming_control *probe)
341 {
342         struct uvc_streaming_control probe_min, probe_max;
343         __u16 bandwidth;
344         unsigned int i;
345         int ret;
346
347         /* Perform probing. The device should adjust the requested values
348          * according to its capabilities. However, some devices, namely the
349          * first generation UVC Logitech webcams, don't implement the Video
350          * Probe control properly, and just return the needed bandwidth. For
351          * that reason, if the needed bandwidth exceeds the maximum available
352          * bandwidth, try to lower the quality.
353          */
354         ret = uvc_set_video_ctrl(stream, probe, 1);
355         if (ret < 0)
356                 goto done;
357
358         /* Get the minimum and maximum values for compression settings. */
359         if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
360                 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
361                 if (ret < 0)
362                         goto done;
363                 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
364                 if (ret < 0)
365                         goto done;
366
367                 probe->wCompQuality = probe_max.wCompQuality;
368         }
369
370         for (i = 0; i < 2; ++i) {
371                 ret = uvc_set_video_ctrl(stream, probe, 1);
372                 if (ret < 0)
373                         goto done;
374                 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
375                 if (ret < 0)
376                         goto done;
377
378                 if (stream->intf->num_altsetting == 1)
379                         break;
380
381                 bandwidth = probe->dwMaxPayloadTransferSize;
382                 if (bandwidth <= stream->maxpsize)
383                         break;
384
385                 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
386                         ret = -ENOSPC;
387                         goto done;
388                 }
389
390                 /* TODO: negotiate compression parameters */
391                 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
392                 probe->wPFrameRate = probe_min.wPFrameRate;
393                 probe->wCompQuality = probe_max.wCompQuality;
394                 probe->wCompWindowSize = probe_min.wCompWindowSize;
395         }
396
397 done:
398         return ret;
399 }
400
401 static int uvc_commit_video(struct uvc_streaming *stream,
402                             struct uvc_streaming_control *probe)
403 {
404         return uvc_set_video_ctrl(stream, probe, 0);
405 }
406
407 /* -----------------------------------------------------------------------------
408  * Clocks and timestamps
409  */
410
411 static inline void uvc_video_get_ts(struct timespec *ts)
412 {
413         if (uvc_clock_param == CLOCK_MONOTONIC)
414                 ktime_get_ts(ts);
415         else
416                 ktime_get_real_ts(ts);
417 }
418
419 static void
420 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
421                        const __u8 *data, int len)
422 {
423         struct uvc_clock_sample *sample;
424         unsigned int header_size;
425         bool has_pts = false;
426         bool has_scr = false;
427         unsigned long flags;
428         struct timespec ts;
429         u16 host_sof;
430         u16 dev_sof;
431
432         switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
433         case UVC_STREAM_PTS | UVC_STREAM_SCR:
434                 header_size = 12;
435                 has_pts = true;
436                 has_scr = true;
437                 break;
438         case UVC_STREAM_PTS:
439                 header_size = 6;
440                 has_pts = true;
441                 break;
442         case UVC_STREAM_SCR:
443                 header_size = 8;
444                 has_scr = true;
445                 break;
446         default:
447                 header_size = 2;
448                 break;
449         }
450
451         /* Check for invalid headers. */
452         if (len < header_size)
453                 return;
454
455         /* Extract the timestamps:
456          *
457          * - store the frame PTS in the buffer structure
458          * - if the SCR field is present, retrieve the host SOF counter and
459          *   kernel timestamps and store them with the SCR STC and SOF fields
460          *   in the ring buffer
461          */
462         if (has_pts && buf != NULL)
463                 buf->pts = get_unaligned_le32(&data[2]);
464
465         if (!has_scr)
466                 return;
467
468         /* To limit the amount of data, drop SCRs with an SOF identical to the
469          * previous one.
470          */
471         dev_sof = get_unaligned_le16(&data[header_size - 2]);
472         if (dev_sof == stream->clock.last_sof)
473                 return;
474
475         stream->clock.last_sof = dev_sof;
476
477         host_sof = usb_get_current_frame_number(stream->dev->udev);
478         uvc_video_get_ts(&ts);
479
480         /* The UVC specification allows device implementations that can't obtain
481          * the USB frame number to keep their own frame counters as long as they
482          * match the size and frequency of the frame number associated with USB
483          * SOF tokens. The SOF values sent by such devices differ from the USB
484          * SOF tokens by a fixed offset that needs to be estimated and accounted
485          * for to make timestamp recovery as accurate as possible.
486          *
487          * The offset is estimated the first time a device SOF value is received
488          * as the difference between the host and device SOF values. As the two
489          * SOF values can differ slightly due to transmission delays, consider
490          * that the offset is null if the difference is not higher than 10 ms
491          * (negative differences can not happen and are thus considered as an
492          * offset). The video commit control wDelay field should be used to
493          * compute a dynamic threshold instead of using a fixed 10 ms value, but
494          * devices don't report reliable wDelay values.
495          *
496          * See uvc_video_clock_host_sof() for an explanation regarding why only
497          * the 8 LSBs of the delta are kept.
498          */
499         if (stream->clock.sof_offset == (u16)-1) {
500                 u16 delta_sof = (host_sof - dev_sof) & 255;
501                 if (delta_sof >= 10)
502                         stream->clock.sof_offset = delta_sof;
503                 else
504                         stream->clock.sof_offset = 0;
505         }
506
507         dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
508
509         spin_lock_irqsave(&stream->clock.lock, flags);
510
511         sample = &stream->clock.samples[stream->clock.head];
512         sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
513         sample->dev_sof = dev_sof;
514         sample->host_sof = host_sof;
515         sample->host_ts = ts;
516
517         /* Update the sliding window head and count. */
518         stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
519
520         if (stream->clock.count < stream->clock.size)
521                 stream->clock.count++;
522
523         spin_unlock_irqrestore(&stream->clock.lock, flags);
524 }
525
526 static void uvc_video_clock_reset(struct uvc_streaming *stream)
527 {
528         struct uvc_clock *clock = &stream->clock;
529
530         clock->head = 0;
531         clock->count = 0;
532         clock->last_sof = -1;
533         clock->sof_offset = -1;
534 }
535
536 static int uvc_video_clock_init(struct uvc_streaming *stream)
537 {
538         struct uvc_clock *clock = &stream->clock;
539
540         spin_lock_init(&clock->lock);
541         clock->size = 32;
542
543         clock->samples = kmalloc(clock->size * sizeof(*clock->samples),
544                                  GFP_KERNEL);
545         if (clock->samples == NULL)
546                 return -ENOMEM;
547
548         uvc_video_clock_reset(stream);
549
550         return 0;
551 }
552
553 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
554 {
555         kfree(stream->clock.samples);
556         stream->clock.samples = NULL;
557 }
558
559 /*
560  * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
561  *
562  * Host SOF counters reported by usb_get_current_frame_number() usually don't
563  * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
564  * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
565  * controller and its configuration.
566  *
567  * We thus need to recover the SOF value corresponding to the host frame number.
568  * As the device and host frame numbers are sampled in a short interval, the
569  * difference between their values should be equal to a small delta plus an
570  * integer multiple of 256 caused by the host frame number limited precision.
571  *
572  * To obtain the recovered host SOF value, compute the small delta by masking
573  * the high bits of the host frame counter and device SOF difference and add it
574  * to the device SOF value.
575  */
576 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
577 {
578         /* The delta value can be negative. */
579         s8 delta_sof;
580
581         delta_sof = (sample->host_sof - sample->dev_sof) & 255;
582
583         return (sample->dev_sof + delta_sof) & 2047;
584 }
585
586 /*
587  * uvc_video_clock_update - Update the buffer timestamp
588  *
589  * This function converts the buffer PTS timestamp to the host clock domain by
590  * going through the USB SOF clock domain and stores the result in the V4L2
591  * buffer timestamp field.
592  *
593  * The relationship between the device clock and the host clock isn't known.
594  * However, the device and the host share the common USB SOF clock which can be
595  * used to recover that relationship.
596  *
597  * The relationship between the device clock and the USB SOF clock is considered
598  * to be linear over the clock samples sliding window and is given by
599  *
600  * SOF = m * PTS + p
601  *
602  * Several methods to compute the slope (m) and intercept (p) can be used. As
603  * the clock drift should be small compared to the sliding window size, we
604  * assume that the line that goes through the points at both ends of the window
605  * is a good approximation. Naming those points P1 and P2, we get
606  *
607  * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
608  *     + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
609  *
610  * or
611  *
612  * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)   (1)
613  *
614  * to avoid losing precision in the division. Similarly, the host timestamp is
615  * computed with
616  *
617  * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1)        (2)
618  *
619  * SOF values are coded on 11 bits by USB. We extend their precision with 16
620  * decimal bits, leading to a 11.16 coding.
621  *
622  * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
623  * be normalized using the nominal device clock frequency reported through the
624  * UVC descriptors.
625  *
626  * Both the PTS/STC and SOF counters roll over, after a fixed but device
627  * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
628  * sliding window size is smaller than the rollover period, differences computed
629  * on unsigned integers will produce the correct result. However, the p term in
630  * the linear relations will be miscomputed.
631  *
632  * To fix the issue, we subtract a constant from the PTS and STC values to bring
633  * PTS to half the 32 bit STC range. The sliding window STC values then fit into
634  * the 32 bit range without any rollover.
635  *
636  * Similarly, we add 2048 to the device SOF values to make sure that the SOF
637  * computed by (1) will never be smaller than 0. This offset is then compensated
638  * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
639  * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
640  * lower than 4096, and the host SOF counters can have rolled over to 2048. This
641  * case is handled by subtracting 2048 from the SOF value if it exceeds the host
642  * SOF value at the end of the sliding window.
643  *
644  * Finally we subtract a constant from the host timestamps to bring the first
645  * timestamp of the sliding window to 1s.
646  */
647 void uvc_video_clock_update(struct uvc_streaming *stream,
648                             struct vb2_v4l2_buffer *vbuf,
649                             struct uvc_buffer *buf)
650 {
651         struct uvc_clock *clock = &stream->clock;
652         struct uvc_clock_sample *first;
653         struct uvc_clock_sample *last;
654         unsigned long flags;
655         struct timespec ts;
656         u32 delta_stc;
657         u32 y1, y2;
658         u32 x1, x2;
659         u32 mean;
660         u32 sof;
661         u32 div;
662         u32 rem;
663         u64 y;
664
665         if (!uvc_hw_timestamps_param)
666                 return;
667
668         /*
669          * We will get called from __vb2_queue_cancel() if there are buffers
670          * done but not dequeued by the user, but the sample array has already
671          * been released at that time. Just bail out in that case.
672          */
673         if (!clock->samples)
674                 return;
675
676         spin_lock_irqsave(&clock->lock, flags);
677
678         if (clock->count < clock->size)
679                 goto done;
680
681         first = &clock->samples[clock->head];
682         last = &clock->samples[(clock->head - 1) % clock->size];
683
684         /* First step, PTS to SOF conversion. */
685         delta_stc = buf->pts - (1UL << 31);
686         x1 = first->dev_stc - delta_stc;
687         x2 = last->dev_stc - delta_stc;
688         if (x1 == x2)
689                 goto done;
690
691         y1 = (first->dev_sof + 2048) << 16;
692         y2 = (last->dev_sof + 2048) << 16;
693         if (y2 < y1)
694                 y2 += 2048 << 16;
695
696         y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
697           - (u64)y2 * (u64)x1;
698         y = div_u64(y, x2 - x1);
699
700         sof = y;
701
702         uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
703                   "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
704                   stream->dev->name, buf->pts,
705                   y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
706                   sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
707                   x1, x2, y1, y2, clock->sof_offset);
708
709         /* Second step, SOF to host clock conversion. */
710         x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
711         x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
712         if (x2 < x1)
713                 x2 += 2048 << 16;
714         if (x1 == x2)
715                 goto done;
716
717         ts = timespec_sub(last->host_ts, first->host_ts);
718         y1 = NSEC_PER_SEC;
719         y2 = (ts.tv_sec + 1) * NSEC_PER_SEC + ts.tv_nsec;
720
721         /* Interpolated and host SOF timestamps can wrap around at slightly
722          * different times. Handle this by adding or removing 2048 to or from
723          * the computed SOF value to keep it close to the SOF samples mean
724          * value.
725          */
726         mean = (x1 + x2) / 2;
727         if (mean - (1024 << 16) > sof)
728                 sof += 2048 << 16;
729         else if (sof > mean + (1024 << 16))
730                 sof -= 2048 << 16;
731
732         y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
733           - (u64)y2 * (u64)x1;
734         y = div_u64(y, x2 - x1);
735
736         div = div_u64_rem(y, NSEC_PER_SEC, &rem);
737         ts.tv_sec = first->host_ts.tv_sec - 1 + div;
738         ts.tv_nsec = first->host_ts.tv_nsec + rem;
739         if (ts.tv_nsec >= NSEC_PER_SEC) {
740                 ts.tv_sec++;
741                 ts.tv_nsec -= NSEC_PER_SEC;
742         }
743
744         uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %llu "
745                   "buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
746                   stream->dev->name,
747                   sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
748                   y, timespec_to_ns(&ts), vbuf->vb2_buf.timestamp,
749                   x1, first->host_sof, first->dev_sof,
750                   x2, last->host_sof, last->dev_sof, y1, y2);
751
752         /* Update the V4L2 buffer. */
753         vbuf->vb2_buf.timestamp = timespec_to_ns(&ts);
754
755 done:
756         spin_unlock_irqrestore(&clock->lock, flags);
757 }
758
759 /* ------------------------------------------------------------------------
760  * Stream statistics
761  */
762
763 static void uvc_video_stats_decode(struct uvc_streaming *stream,
764                 const __u8 *data, int len)
765 {
766         unsigned int header_size;
767         bool has_pts = false;
768         bool has_scr = false;
769         u16 uninitialized_var(scr_sof);
770         u32 uninitialized_var(scr_stc);
771         u32 uninitialized_var(pts);
772
773         if (stream->stats.stream.nb_frames == 0 &&
774             stream->stats.frame.nb_packets == 0)
775                 ktime_get_ts(&stream->stats.stream.start_ts);
776
777         switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
778         case UVC_STREAM_PTS | UVC_STREAM_SCR:
779                 header_size = 12;
780                 has_pts = true;
781                 has_scr = true;
782                 break;
783         case UVC_STREAM_PTS:
784                 header_size = 6;
785                 has_pts = true;
786                 break;
787         case UVC_STREAM_SCR:
788                 header_size = 8;
789                 has_scr = true;
790                 break;
791         default:
792                 header_size = 2;
793                 break;
794         }
795
796         /* Check for invalid headers. */
797         if (len < header_size || data[0] < header_size) {
798                 stream->stats.frame.nb_invalid++;
799                 return;
800         }
801
802         /* Extract the timestamps. */
803         if (has_pts)
804                 pts = get_unaligned_le32(&data[2]);
805
806         if (has_scr) {
807                 scr_stc = get_unaligned_le32(&data[header_size - 6]);
808                 scr_sof = get_unaligned_le16(&data[header_size - 2]);
809         }
810
811         /* Is PTS constant through the whole frame ? */
812         if (has_pts && stream->stats.frame.nb_pts) {
813                 if (stream->stats.frame.pts != pts) {
814                         stream->stats.frame.nb_pts_diffs++;
815                         stream->stats.frame.last_pts_diff =
816                                 stream->stats.frame.nb_packets;
817                 }
818         }
819
820         if (has_pts) {
821                 stream->stats.frame.nb_pts++;
822                 stream->stats.frame.pts = pts;
823         }
824
825         /* Do all frames have a PTS in their first non-empty packet, or before
826          * their first empty packet ?
827          */
828         if (stream->stats.frame.size == 0) {
829                 if (len > header_size)
830                         stream->stats.frame.has_initial_pts = has_pts;
831                 if (len == header_size && has_pts)
832                         stream->stats.frame.has_early_pts = true;
833         }
834
835         /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
836         if (has_scr && stream->stats.frame.nb_scr) {
837                 if (stream->stats.frame.scr_stc != scr_stc)
838                         stream->stats.frame.nb_scr_diffs++;
839         }
840
841         if (has_scr) {
842                 /* Expand the SOF counter to 32 bits and store its value. */
843                 if (stream->stats.stream.nb_frames > 0 ||
844                     stream->stats.frame.nb_scr > 0)
845                         stream->stats.stream.scr_sof_count +=
846                                 (scr_sof - stream->stats.stream.scr_sof) % 2048;
847                 stream->stats.stream.scr_sof = scr_sof;
848
849                 stream->stats.frame.nb_scr++;
850                 stream->stats.frame.scr_stc = scr_stc;
851                 stream->stats.frame.scr_sof = scr_sof;
852
853                 if (scr_sof < stream->stats.stream.min_sof)
854                         stream->stats.stream.min_sof = scr_sof;
855                 if (scr_sof > stream->stats.stream.max_sof)
856                         stream->stats.stream.max_sof = scr_sof;
857         }
858
859         /* Record the first non-empty packet number. */
860         if (stream->stats.frame.size == 0 && len > header_size)
861                 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
862
863         /* Update the frame size. */
864         stream->stats.frame.size += len - header_size;
865
866         /* Update the packets counters. */
867         stream->stats.frame.nb_packets++;
868         if (len <= header_size)
869                 stream->stats.frame.nb_empty++;
870
871         if (data[1] & UVC_STREAM_ERR)
872                 stream->stats.frame.nb_errors++;
873 }
874
875 static void uvc_video_stats_update(struct uvc_streaming *stream)
876 {
877         struct uvc_stats_frame *frame = &stream->stats.frame;
878
879         uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
880                   "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
881                   "last pts/stc/sof %u/%u/%u\n",
882                   stream->sequence, frame->first_data,
883                   frame->nb_packets - frame->nb_empty, frame->nb_packets,
884                   frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
885                   frame->has_early_pts ? "" : "!",
886                   frame->has_initial_pts ? "" : "!",
887                   frame->nb_scr_diffs, frame->nb_scr,
888                   frame->pts, frame->scr_stc, frame->scr_sof);
889
890         stream->stats.stream.nb_frames++;
891         stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
892         stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
893         stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
894         stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
895
896         if (frame->has_early_pts)
897                 stream->stats.stream.nb_pts_early++;
898         if (frame->has_initial_pts)
899                 stream->stats.stream.nb_pts_initial++;
900         if (frame->last_pts_diff <= frame->first_data)
901                 stream->stats.stream.nb_pts_constant++;
902         if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
903                 stream->stats.stream.nb_scr_count_ok++;
904         if (frame->nb_scr_diffs + 1 == frame->nb_scr)
905                 stream->stats.stream.nb_scr_diffs_ok++;
906
907         memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
908 }
909
910 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
911                             size_t size)
912 {
913         unsigned int scr_sof_freq;
914         unsigned int duration;
915         struct timespec ts;
916         size_t count = 0;
917
918         ts = timespec_sub(stream->stats.stream.stop_ts,
919                           stream->stats.stream.start_ts);
920
921         /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
922          * frequency this will not overflow before more than 1h.
923          */
924         duration = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
925         if (duration != 0)
926                 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
927                              / duration;
928         else
929                 scr_sof_freq = 0;
930
931         count += scnprintf(buf + count, size - count,
932                            "frames:  %u\npackets: %u\nempty:   %u\n"
933                            "errors:  %u\ninvalid: %u\n",
934                            stream->stats.stream.nb_frames,
935                            stream->stats.stream.nb_packets,
936                            stream->stats.stream.nb_empty,
937                            stream->stats.stream.nb_errors,
938                            stream->stats.stream.nb_invalid);
939         count += scnprintf(buf + count, size - count,
940                            "pts: %u early, %u initial, %u ok\n",
941                            stream->stats.stream.nb_pts_early,
942                            stream->stats.stream.nb_pts_initial,
943                            stream->stats.stream.nb_pts_constant);
944         count += scnprintf(buf + count, size - count,
945                            "scr: %u count ok, %u diff ok\n",
946                            stream->stats.stream.nb_scr_count_ok,
947                            stream->stats.stream.nb_scr_diffs_ok);
948         count += scnprintf(buf + count, size - count,
949                            "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
950                            stream->stats.stream.min_sof,
951                            stream->stats.stream.max_sof,
952                            scr_sof_freq / 1000, scr_sof_freq % 1000);
953
954         return count;
955 }
956
957 static void uvc_video_stats_start(struct uvc_streaming *stream)
958 {
959         memset(&stream->stats, 0, sizeof(stream->stats));
960         stream->stats.stream.min_sof = 2048;
961 }
962
963 static void uvc_video_stats_stop(struct uvc_streaming *stream)
964 {
965         ktime_get_ts(&stream->stats.stream.stop_ts);
966 }
967
968 /* ------------------------------------------------------------------------
969  * Video codecs
970  */
971
972 /* Video payload decoding is handled by uvc_video_decode_start(),
973  * uvc_video_decode_data() and uvc_video_decode_end().
974  *
975  * uvc_video_decode_start is called with URB data at the start of a bulk or
976  * isochronous payload. It processes header data and returns the header size
977  * in bytes if successful. If an error occurs, it returns a negative error
978  * code. The following error codes have special meanings.
979  *
980  * - EAGAIN informs the caller that the current video buffer should be marked
981  *   as done, and that the function should be called again with the same data
982  *   and a new video buffer. This is used when end of frame conditions can be
983  *   reliably detected at the beginning of the next frame only.
984  *
985  * If an error other than -EAGAIN is returned, the caller will drop the current
986  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
987  * made until the next payload. -ENODATA can be used to drop the current
988  * payload if no other error code is appropriate.
989  *
990  * uvc_video_decode_data is called for every URB with URB data. It copies the
991  * data to the video buffer.
992  *
993  * uvc_video_decode_end is called with header data at the end of a bulk or
994  * isochronous payload. It performs any additional header data processing and
995  * returns 0 or a negative error code if an error occurred. As header data have
996  * already been processed by uvc_video_decode_start, this functions isn't
997  * required to perform sanity checks a second time.
998  *
999  * For isochronous transfers where a payload is always transferred in a single
1000  * URB, the three functions will be called in a row.
1001  *
1002  * To let the decoder process header data and update its internal state even
1003  * when no video buffer is available, uvc_video_decode_start must be prepared
1004  * to be called with a NULL buf parameter. uvc_video_decode_data and
1005  * uvc_video_decode_end will never be called with a NULL buffer.
1006  */
1007 static int uvc_video_decode_start(struct uvc_streaming *stream,
1008                 struct uvc_buffer *buf, const __u8 *data, int len)
1009 {
1010         __u8 fid;
1011
1012         /* Sanity checks:
1013          * - packet must be at least 2 bytes long
1014          * - bHeaderLength value must be at least 2 bytes (see above)
1015          * - bHeaderLength value can't be larger than the packet size.
1016          */
1017         if (len < 2 || data[0] < 2 || data[0] > len) {
1018                 stream->stats.frame.nb_invalid++;
1019                 return -EINVAL;
1020         }
1021
1022         fid = data[1] & UVC_STREAM_FID;
1023
1024         /* Increase the sequence number regardless of any buffer states, so
1025          * that discontinuous sequence numbers always indicate lost frames.
1026          */
1027         if (stream->last_fid != fid) {
1028                 stream->sequence++;
1029                 if (stream->sequence)
1030                         uvc_video_stats_update(stream);
1031         }
1032
1033         uvc_video_clock_decode(stream, buf, data, len);
1034         uvc_video_stats_decode(stream, data, len);
1035
1036         /* Store the payload FID bit and return immediately when the buffer is
1037          * NULL.
1038          */
1039         if (buf == NULL) {
1040                 stream->last_fid = fid;
1041                 return -ENODATA;
1042         }
1043
1044         /* Mark the buffer as bad if the error bit is set. */
1045         if (data[1] & UVC_STREAM_ERR) {
1046                 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1047                           "set).\n");
1048                 buf->error = 1;
1049         }
1050
1051         /* Synchronize to the input stream by waiting for the FID bit to be
1052          * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1053          * stream->last_fid is initialized to -1, so the first isochronous
1054          * frame will always be in sync.
1055          *
1056          * If the device doesn't toggle the FID bit, invert stream->last_fid
1057          * when the EOF bit is set to force synchronisation on the next packet.
1058          */
1059         if (buf->state != UVC_BUF_STATE_ACTIVE) {
1060                 struct timespec ts;
1061
1062                 if (fid == stream->last_fid) {
1063                         uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1064                                 "sync).\n");
1065                         if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1066                             (data[1] & UVC_STREAM_EOF))
1067                                 stream->last_fid ^= UVC_STREAM_FID;
1068                         return -ENODATA;
1069                 }
1070
1071                 uvc_video_get_ts(&ts);
1072
1073                 buf->buf.field = V4L2_FIELD_NONE;
1074                 buf->buf.sequence = stream->sequence;
1075                 buf->buf.vb2_buf.timestamp = timespec_to_ns(&ts);
1076
1077                 /* TODO: Handle PTS and SCR. */
1078                 buf->state = UVC_BUF_STATE_ACTIVE;
1079         }
1080
1081         /* Mark the buffer as done if we're at the beginning of a new frame.
1082          * End of frame detection is better implemented by checking the EOF
1083          * bit (FID bit toggling is delayed by one frame compared to the EOF
1084          * bit), but some devices don't set the bit at end of frame (and the
1085          * last payload can be lost anyway). We thus must check if the FID has
1086          * been toggled.
1087          *
1088          * stream->last_fid is initialized to -1, so the first isochronous
1089          * frame will never trigger an end of frame detection.
1090          *
1091          * Empty buffers (bytesused == 0) don't trigger end of frame detection
1092          * as it doesn't make sense to return an empty buffer. This also
1093          * avoids detecting end of frame conditions at FID toggling if the
1094          * previous payload had the EOF bit set.
1095          */
1096         if (fid != stream->last_fid && buf->bytesused != 0) {
1097                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1098                                 "toggled).\n");
1099                 buf->state = UVC_BUF_STATE_READY;
1100                 return -EAGAIN;
1101         }
1102
1103         stream->last_fid = fid;
1104
1105         return data[0];
1106 }
1107
1108 static void uvc_video_decode_data(struct uvc_streaming *stream,
1109                 struct uvc_buffer *buf, const __u8 *data, int len)
1110 {
1111         unsigned int maxlen, nbytes;
1112         void *mem;
1113
1114         if (len <= 0)
1115                 return;
1116
1117         /* Copy the video data to the buffer. */
1118         maxlen = buf->length - buf->bytesused;
1119         mem = buf->mem + buf->bytesused;
1120         nbytes = min((unsigned int)len, maxlen);
1121         memcpy(mem, data, nbytes);
1122         buf->bytesused += nbytes;
1123
1124         /* Complete the current frame if the buffer size was exceeded. */
1125         if (len > maxlen) {
1126                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1127                 buf->state = UVC_BUF_STATE_READY;
1128         }
1129 }
1130
1131 static void uvc_video_decode_end(struct uvc_streaming *stream,
1132                 struct uvc_buffer *buf, const __u8 *data, int len)
1133 {
1134         /* Mark the buffer as done if the EOF marker is set. */
1135         if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1136                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1137                 if (data[0] == len)
1138                         uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1139                 buf->state = UVC_BUF_STATE_READY;
1140                 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1141                         stream->last_fid ^= UVC_STREAM_FID;
1142         }
1143 }
1144
1145 /* Video payload encoding is handled by uvc_video_encode_header() and
1146  * uvc_video_encode_data(). Only bulk transfers are currently supported.
1147  *
1148  * uvc_video_encode_header is called at the start of a payload. It adds header
1149  * data to the transfer buffer and returns the header size. As the only known
1150  * UVC output device transfers a whole frame in a single payload, the EOF bit
1151  * is always set in the header.
1152  *
1153  * uvc_video_encode_data is called for every URB and copies the data from the
1154  * video buffer to the transfer buffer.
1155  */
1156 static int uvc_video_encode_header(struct uvc_streaming *stream,
1157                 struct uvc_buffer *buf, __u8 *data, int len)
1158 {
1159         data[0] = 2;    /* Header length */
1160         data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1161                 | (stream->last_fid & UVC_STREAM_FID);
1162         return 2;
1163 }
1164
1165 static int uvc_video_encode_data(struct uvc_streaming *stream,
1166                 struct uvc_buffer *buf, __u8 *data, int len)
1167 {
1168         struct uvc_video_queue *queue = &stream->queue;
1169         unsigned int nbytes;
1170         void *mem;
1171
1172         /* Copy video data to the URB buffer. */
1173         mem = buf->mem + queue->buf_used;
1174         nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1175         nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1176                         nbytes);
1177         memcpy(data, mem, nbytes);
1178
1179         queue->buf_used += nbytes;
1180
1181         return nbytes;
1182 }
1183
1184 /* ------------------------------------------------------------------------
1185  * URB handling
1186  */
1187
1188 /*
1189  * Set error flag for incomplete buffer.
1190  */
1191 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1192                                       struct uvc_buffer *buf)
1193 {
1194         if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1195             !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1196                 buf->error = 1;
1197 }
1198
1199 /*
1200  * Completion handler for video URBs.
1201  */
1202 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1203         struct uvc_buffer *buf)
1204 {
1205         u8 *mem;
1206         int ret, i;
1207
1208         for (i = 0; i < urb->number_of_packets; ++i) {
1209                 if (urb->iso_frame_desc[i].status < 0) {
1210                         uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1211                                 "lost (%d).\n", urb->iso_frame_desc[i].status);
1212                         /* Mark the buffer as faulty. */
1213                         if (buf != NULL)
1214                                 buf->error = 1;
1215                         continue;
1216                 }
1217
1218                 /* Decode the payload header. */
1219                 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1220                 do {
1221                         ret = uvc_video_decode_start(stream, buf, mem,
1222                                 urb->iso_frame_desc[i].actual_length);
1223                         if (ret == -EAGAIN) {
1224                                 uvc_video_validate_buffer(stream, buf);
1225                                 buf = uvc_queue_next_buffer(&stream->queue,
1226                                                             buf);
1227                         }
1228                 } while (ret == -EAGAIN);
1229
1230                 if (ret < 0)
1231                         continue;
1232
1233                 /* Decode the payload data. */
1234                 uvc_video_decode_data(stream, buf, mem + ret,
1235                         urb->iso_frame_desc[i].actual_length - ret);
1236
1237                 /* Process the header again. */
1238                 uvc_video_decode_end(stream, buf, mem,
1239                         urb->iso_frame_desc[i].actual_length);
1240
1241                 if (buf->state == UVC_BUF_STATE_READY) {
1242                         uvc_video_validate_buffer(stream, buf);
1243                         buf = uvc_queue_next_buffer(&stream->queue, buf);
1244                 }
1245         }
1246 }
1247
1248 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1249         struct uvc_buffer *buf)
1250 {
1251         u8 *mem;
1252         int len, ret;
1253
1254         /*
1255          * Ignore ZLPs if they're not part of a frame, otherwise process them
1256          * to trigger the end of payload detection.
1257          */
1258         if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1259                 return;
1260
1261         mem = urb->transfer_buffer;
1262         len = urb->actual_length;
1263         stream->bulk.payload_size += len;
1264
1265         /* If the URB is the first of its payload, decode and save the
1266          * header.
1267          */
1268         if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1269                 do {
1270                         ret = uvc_video_decode_start(stream, buf, mem, len);
1271                         if (ret == -EAGAIN)
1272                                 buf = uvc_queue_next_buffer(&stream->queue,
1273                                                             buf);
1274                 } while (ret == -EAGAIN);
1275
1276                 /* If an error occurred skip the rest of the payload. */
1277                 if (ret < 0 || buf == NULL) {
1278                         stream->bulk.skip_payload = 1;
1279                 } else {
1280                         memcpy(stream->bulk.header, mem, ret);
1281                         stream->bulk.header_size = ret;
1282
1283                         mem += ret;
1284                         len -= ret;
1285                 }
1286         }
1287
1288         /* The buffer queue might have been cancelled while a bulk transfer
1289          * was in progress, so we can reach here with buf equal to NULL. Make
1290          * sure buf is never dereferenced if NULL.
1291          */
1292
1293         /* Process video data. */
1294         if (!stream->bulk.skip_payload && buf != NULL)
1295                 uvc_video_decode_data(stream, buf, mem, len);
1296
1297         /* Detect the payload end by a URB smaller than the maximum size (or
1298          * a payload size equal to the maximum) and process the header again.
1299          */
1300         if (urb->actual_length < urb->transfer_buffer_length ||
1301             stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1302                 if (!stream->bulk.skip_payload && buf != NULL) {
1303                         uvc_video_decode_end(stream, buf, stream->bulk.header,
1304                                 stream->bulk.payload_size);
1305                         if (buf->state == UVC_BUF_STATE_READY)
1306                                 uvc_queue_next_buffer(&stream->queue, buf);
1307                 }
1308
1309                 stream->bulk.header_size = 0;
1310                 stream->bulk.skip_payload = 0;
1311                 stream->bulk.payload_size = 0;
1312         }
1313 }
1314
1315 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1316         struct uvc_buffer *buf)
1317 {
1318         u8 *mem = urb->transfer_buffer;
1319         int len = stream->urb_size, ret;
1320
1321         if (buf == NULL) {
1322                 urb->transfer_buffer_length = 0;
1323                 return;
1324         }
1325
1326         /* If the URB is the first of its payload, add the header. */
1327         if (stream->bulk.header_size == 0) {
1328                 ret = uvc_video_encode_header(stream, buf, mem, len);
1329                 stream->bulk.header_size = ret;
1330                 stream->bulk.payload_size += ret;
1331                 mem += ret;
1332                 len -= ret;
1333         }
1334
1335         /* Process video data. */
1336         ret = uvc_video_encode_data(stream, buf, mem, len);
1337
1338         stream->bulk.payload_size += ret;
1339         len -= ret;
1340
1341         if (buf->bytesused == stream->queue.buf_used ||
1342             stream->bulk.payload_size == stream->bulk.max_payload_size) {
1343                 if (buf->bytesused == stream->queue.buf_used) {
1344                         stream->queue.buf_used = 0;
1345                         buf->state = UVC_BUF_STATE_READY;
1346                         buf->buf.sequence = ++stream->sequence;
1347                         uvc_queue_next_buffer(&stream->queue, buf);
1348                         stream->last_fid ^= UVC_STREAM_FID;
1349                 }
1350
1351                 stream->bulk.header_size = 0;
1352                 stream->bulk.payload_size = 0;
1353         }
1354
1355         urb->transfer_buffer_length = stream->urb_size - len;
1356 }
1357
1358 static void uvc_video_complete(struct urb *urb)
1359 {
1360         struct uvc_streaming *stream = urb->context;
1361         struct uvc_video_queue *queue = &stream->queue;
1362         struct uvc_buffer *buf = NULL;
1363         unsigned long flags;
1364         int ret;
1365
1366         switch (urb->status) {
1367         case 0:
1368                 break;
1369
1370         default:
1371                 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1372                         "completion handler.\n", urb->status);
1373                 /* fall through */
1374         case -ENOENT:           /* usb_kill_urb() called. */
1375                 if (stream->frozen)
1376                         return;
1377                 /* fall through */
1378         case -ECONNRESET:       /* usb_unlink_urb() called. */
1379         case -ESHUTDOWN:        /* The endpoint is being disabled. */
1380                 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1381                 return;
1382         }
1383
1384         spin_lock_irqsave(&queue->irqlock, flags);
1385         if (!list_empty(&queue->irqqueue))
1386                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
1387                                        queue);
1388         spin_unlock_irqrestore(&queue->irqlock, flags);
1389
1390         stream->decode(urb, stream, buf);
1391
1392         if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
1393                 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1394                         ret);
1395         }
1396 }
1397
1398 /*
1399  * Free transfer buffers.
1400  */
1401 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1402 {
1403         unsigned int i;
1404
1405         for (i = 0; i < UVC_URBS; ++i) {
1406                 if (stream->urb_buffer[i]) {
1407 #ifndef CONFIG_DMA_NONCOHERENT
1408                         usb_free_coherent(stream->dev->udev, stream->urb_size,
1409                                 stream->urb_buffer[i], stream->urb_dma[i]);
1410 #else
1411                         kfree(stream->urb_buffer[i]);
1412 #endif
1413                         stream->urb_buffer[i] = NULL;
1414                 }
1415         }
1416
1417         stream->urb_size = 0;
1418 }
1419
1420 /*
1421  * Allocate transfer buffers. This function can be called with buffers
1422  * already allocated when resuming from suspend, in which case it will
1423  * return without touching the buffers.
1424  *
1425  * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1426  * system is too low on memory try successively smaller numbers of packets
1427  * until allocation succeeds.
1428  *
1429  * Return the number of allocated packets on success or 0 when out of memory.
1430  */
1431 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1432         unsigned int size, unsigned int psize, gfp_t gfp_flags)
1433 {
1434         unsigned int npackets;
1435         unsigned int i;
1436
1437         /* Buffers are already allocated, bail out. */
1438         if (stream->urb_size)
1439                 return stream->urb_size / psize;
1440
1441         /* Compute the number of packets. Bulk endpoints might transfer UVC
1442          * payloads across multiple URBs.
1443          */
1444         npackets = DIV_ROUND_UP(size, psize);
1445         if (npackets > UVC_MAX_PACKETS)
1446                 npackets = UVC_MAX_PACKETS;
1447
1448         /* Retry allocations until one succeed. */
1449         for (; npackets > 1; npackets /= 2) {
1450                 for (i = 0; i < UVC_URBS; ++i) {
1451                         stream->urb_size = psize * npackets;
1452 #ifndef CONFIG_DMA_NONCOHERENT
1453                         stream->urb_buffer[i] = usb_alloc_coherent(
1454                                 stream->dev->udev, stream->urb_size,
1455                                 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1456 #else
1457                         stream->urb_buffer[i] =
1458                             kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1459 #endif
1460                         if (!stream->urb_buffer[i]) {
1461                                 uvc_free_urb_buffers(stream);
1462                                 break;
1463                         }
1464                 }
1465
1466                 if (i == UVC_URBS) {
1467                         uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1468                                 "of %ux%u bytes each.\n", UVC_URBS, npackets,
1469                                 psize);
1470                         return npackets;
1471                 }
1472         }
1473
1474         uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1475                 "per packet).\n", psize);
1476         return 0;
1477 }
1478
1479 /*
1480  * Uninitialize isochronous/bulk URBs and free transfer buffers.
1481  */
1482 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1483 {
1484         struct urb *urb;
1485         unsigned int i;
1486
1487         uvc_video_stats_stop(stream);
1488
1489         for (i = 0; i < UVC_URBS; ++i) {
1490                 urb = stream->urb[i];
1491                 if (urb == NULL)
1492                         continue;
1493
1494                 usb_kill_urb(urb);
1495                 usb_free_urb(urb);
1496                 stream->urb[i] = NULL;
1497         }
1498
1499         if (free_buffers)
1500                 uvc_free_urb_buffers(stream);
1501 }
1502
1503 /*
1504  * Compute the maximum number of bytes per interval for an endpoint.
1505  */
1506 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1507                                          struct usb_host_endpoint *ep)
1508 {
1509         u16 psize;
1510         u16 mult;
1511
1512         switch (dev->speed) {
1513         case USB_SPEED_SUPER:
1514         case USB_SPEED_SUPER_PLUS:
1515                 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1516         case USB_SPEED_HIGH:
1517                 psize = usb_endpoint_maxp(&ep->desc);
1518                 mult = usb_endpoint_maxp_mult(&ep->desc);
1519                 return (psize & 0x07ff) * mult;
1520         case USB_SPEED_WIRELESS:
1521                 psize = usb_endpoint_maxp(&ep->desc);
1522                 return psize;
1523         default:
1524                 psize = usb_endpoint_maxp(&ep->desc);
1525                 return psize & 0x07ff;
1526         }
1527 }
1528
1529 /*
1530  * Initialize isochronous URBs and allocate transfer buffers. The packet size
1531  * is given by the endpoint.
1532  */
1533 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1534         struct usb_host_endpoint *ep, gfp_t gfp_flags)
1535 {
1536         struct urb *urb;
1537         unsigned int npackets, i, j;
1538         u16 psize;
1539         u32 size;
1540
1541         psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1542         size = stream->ctrl.dwMaxVideoFrameSize;
1543
1544         npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1545         if (npackets == 0)
1546                 return -ENOMEM;
1547
1548         size = npackets * psize;
1549
1550         for (i = 0; i < UVC_URBS; ++i) {
1551                 urb = usb_alloc_urb(npackets, gfp_flags);
1552                 if (urb == NULL) {
1553                         uvc_uninit_video(stream, 1);
1554                         return -ENOMEM;
1555                 }
1556
1557                 urb->dev = stream->dev->udev;
1558                 urb->context = stream;
1559                 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1560                                 ep->desc.bEndpointAddress);
1561 #ifndef CONFIG_DMA_NONCOHERENT
1562                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1563                 urb->transfer_dma = stream->urb_dma[i];
1564 #else
1565                 urb->transfer_flags = URB_ISO_ASAP;
1566 #endif
1567                 urb->interval = ep->desc.bInterval;
1568                 urb->transfer_buffer = stream->urb_buffer[i];
1569                 urb->complete = uvc_video_complete;
1570                 urb->number_of_packets = npackets;
1571                 urb->transfer_buffer_length = size;
1572
1573                 for (j = 0; j < npackets; ++j) {
1574                         urb->iso_frame_desc[j].offset = j * psize;
1575                         urb->iso_frame_desc[j].length = psize;
1576                 }
1577
1578                 stream->urb[i] = urb;
1579         }
1580
1581         return 0;
1582 }
1583
1584 /*
1585  * Initialize bulk URBs and allocate transfer buffers. The packet size is
1586  * given by the endpoint.
1587  */
1588 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1589         struct usb_host_endpoint *ep, gfp_t gfp_flags)
1590 {
1591         struct urb *urb;
1592         unsigned int npackets, pipe, i;
1593         u16 psize;
1594         u32 size;
1595
1596         psize = usb_endpoint_maxp(&ep->desc);
1597         size = stream->ctrl.dwMaxPayloadTransferSize;
1598         stream->bulk.max_payload_size = size;
1599
1600         npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1601         if (npackets == 0)
1602                 return -ENOMEM;
1603
1604         size = npackets * psize;
1605
1606         if (usb_endpoint_dir_in(&ep->desc))
1607                 pipe = usb_rcvbulkpipe(stream->dev->udev,
1608                                        ep->desc.bEndpointAddress);
1609         else
1610                 pipe = usb_sndbulkpipe(stream->dev->udev,
1611                                        ep->desc.bEndpointAddress);
1612
1613         if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1614                 size = 0;
1615
1616         for (i = 0; i < UVC_URBS; ++i) {
1617                 urb = usb_alloc_urb(0, gfp_flags);
1618                 if (urb == NULL) {
1619                         uvc_uninit_video(stream, 1);
1620                         return -ENOMEM;
1621                 }
1622
1623                 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1624                         stream->urb_buffer[i], size, uvc_video_complete,
1625                         stream);
1626 #ifndef CONFIG_DMA_NONCOHERENT
1627                 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1628                 urb->transfer_dma = stream->urb_dma[i];
1629 #endif
1630
1631                 stream->urb[i] = urb;
1632         }
1633
1634         return 0;
1635 }
1636
1637 /*
1638  * Initialize isochronous/bulk URBs and allocate transfer buffers.
1639  */
1640 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1641 {
1642         struct usb_interface *intf = stream->intf;
1643         struct usb_host_endpoint *ep;
1644         unsigned int i;
1645         int ret;
1646
1647         stream->sequence = -1;
1648         stream->last_fid = -1;
1649         stream->bulk.header_size = 0;
1650         stream->bulk.skip_payload = 0;
1651         stream->bulk.payload_size = 0;
1652
1653         uvc_video_stats_start(stream);
1654
1655         if (intf->num_altsetting > 1) {
1656                 struct usb_host_endpoint *best_ep = NULL;
1657                 unsigned int best_psize = UINT_MAX;
1658                 unsigned int bandwidth;
1659                 unsigned int uninitialized_var(altsetting);
1660                 int intfnum = stream->intfnum;
1661
1662                 /* Isochronous endpoint, select the alternate setting. */
1663                 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1664
1665                 if (bandwidth == 0) {
1666                         uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1667                                 "bandwidth, defaulting to lowest.\n");
1668                         bandwidth = 1;
1669                 } else {
1670                         uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1671                                 "B/frame bandwidth.\n", bandwidth);
1672                 }
1673
1674                 for (i = 0; i < intf->num_altsetting; ++i) {
1675                         struct usb_host_interface *alts;
1676                         unsigned int psize;
1677
1678                         alts = &intf->altsetting[i];
1679                         ep = uvc_find_endpoint(alts,
1680                                 stream->header.bEndpointAddress);
1681                         if (ep == NULL)
1682                                 continue;
1683
1684                         /* Check if the bandwidth is high enough. */
1685                         psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1686                         if (psize >= bandwidth && psize <= best_psize) {
1687                                 altsetting = alts->desc.bAlternateSetting;
1688                                 best_psize = psize;
1689                                 best_ep = ep;
1690                         }
1691                 }
1692
1693                 if (best_ep == NULL) {
1694                         uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1695                                 "for requested bandwidth.\n");
1696                         return -EIO;
1697                 }
1698
1699                 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1700                         "(%u B/frame bandwidth).\n", altsetting, best_psize);
1701
1702                 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1703                 if (ret < 0)
1704                         return ret;
1705
1706                 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1707         } else {
1708                 /* Bulk endpoint, proceed to URB initialization. */
1709                 ep = uvc_find_endpoint(&intf->altsetting[0],
1710                                 stream->header.bEndpointAddress);
1711                 if (ep == NULL)
1712                         return -EIO;
1713
1714                 /* Reject broken descriptors. */
1715                 if (usb_endpoint_maxp(&ep->desc) == 0)
1716                         return -EIO;
1717
1718                 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1719         }
1720
1721         if (ret < 0)
1722                 return ret;
1723
1724         /* Submit the URBs. */
1725         for (i = 0; i < UVC_URBS; ++i) {
1726                 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1727                 if (ret < 0) {
1728                         uvc_printk(KERN_ERR, "Failed to submit URB %u "
1729                                         "(%d).\n", i, ret);
1730                         uvc_uninit_video(stream, 1);
1731                         return ret;
1732                 }
1733         }
1734
1735         /* The Logitech C920 temporarily forgets that it should not be adjusting
1736          * Exposure Absolute during init so restore controls to stored values.
1737          */
1738         if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1739                 uvc_ctrl_restore_values(stream->dev);
1740
1741         return 0;
1742 }
1743
1744 /* --------------------------------------------------------------------------
1745  * Suspend/resume
1746  */
1747
1748 /*
1749  * Stop streaming without disabling the video queue.
1750  *
1751  * To let userspace applications resume without trouble, we must not touch the
1752  * video buffers in any way. We mark the device as frozen to make sure the URB
1753  * completion handler won't try to cancel the queue when we kill the URBs.
1754  */
1755 int uvc_video_suspend(struct uvc_streaming *stream)
1756 {
1757         if (!uvc_queue_streaming(&stream->queue))
1758                 return 0;
1759
1760         stream->frozen = 1;
1761         uvc_uninit_video(stream, 0);
1762         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1763         return 0;
1764 }
1765
1766 /*
1767  * Reconfigure the video interface and restart streaming if it was enabled
1768  * before suspend.
1769  *
1770  * If an error occurs, disable the video queue. This will wake all pending
1771  * buffers, making sure userspace applications are notified of the problem
1772  * instead of waiting forever.
1773  */
1774 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1775 {
1776         int ret;
1777
1778         /* If the bus has been reset on resume, set the alternate setting to 0.
1779          * This should be the default value, but some devices crash or otherwise
1780          * misbehave if they don't receive a SET_INTERFACE request before any
1781          * other video control request.
1782          */
1783         if (reset)
1784                 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1785
1786         stream->frozen = 0;
1787
1788         uvc_video_clock_reset(stream);
1789
1790         if (!uvc_queue_streaming(&stream->queue))
1791                 return 0;
1792
1793         ret = uvc_commit_video(stream, &stream->ctrl);
1794         if (ret < 0)
1795                 return ret;
1796
1797         return uvc_init_video(stream, GFP_NOIO);
1798 }
1799
1800 /* ------------------------------------------------------------------------
1801  * Video device
1802  */
1803
1804 /*
1805  * Initialize the UVC video device by switching to alternate setting 0 and
1806  * retrieve the default format.
1807  *
1808  * Some cameras (namely the Fuji Finepix) set the format and frame
1809  * indexes to zero. The UVC standard doesn't clearly make this a spec
1810  * violation, so try to silently fix the values if possible.
1811  *
1812  * This function is called before registering the device with V4L.
1813  */
1814 int uvc_video_init(struct uvc_streaming *stream)
1815 {
1816         struct uvc_streaming_control *probe = &stream->ctrl;
1817         struct uvc_format *format = NULL;
1818         struct uvc_frame *frame = NULL;
1819         unsigned int i;
1820         int ret;
1821
1822         if (stream->nformats == 0) {
1823                 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1824                 return -EINVAL;
1825         }
1826
1827         atomic_set(&stream->active, 0);
1828
1829         /* Alternate setting 0 should be the default, yet the XBox Live Vision
1830          * Cam (and possibly other devices) crash or otherwise misbehave if
1831          * they don't receive a SET_INTERFACE request before any other video
1832          * control request.
1833          */
1834         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1835
1836         /* Set the streaming probe control with default streaming parameters
1837          * retrieved from the device. Webcams that don't suport GET_DEF
1838          * requests on the probe control will just keep their current streaming
1839          * parameters.
1840          */
1841         if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1842                 uvc_set_video_ctrl(stream, probe, 1);
1843
1844         /* Initialize the streaming parameters with the probe control current
1845          * value. This makes sure SET_CUR requests on the streaming commit
1846          * control will always use values retrieved from a successful GET_CUR
1847          * request on the probe control, as required by the UVC specification.
1848          */
1849         ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1850         if (ret < 0)
1851                 return ret;
1852
1853         /* Check if the default format descriptor exists. Use the first
1854          * available format otherwise.
1855          */
1856         for (i = stream->nformats; i > 0; --i) {
1857                 format = &stream->format[i-1];
1858                 if (format->index == probe->bFormatIndex)
1859                         break;
1860         }
1861
1862         if (format->nframes == 0) {
1863                 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1864                         "default format.\n");
1865                 return -EINVAL;
1866         }
1867
1868         /* Zero bFrameIndex might be correct. Stream-based formats (including
1869          * MPEG-2 TS and DV) do not support frames but have a dummy frame
1870          * descriptor with bFrameIndex set to zero. If the default frame
1871          * descriptor is not found, use the first available frame.
1872          */
1873         for (i = format->nframes; i > 0; --i) {
1874                 frame = &format->frame[i-1];
1875                 if (frame->bFrameIndex == probe->bFrameIndex)
1876                         break;
1877         }
1878
1879         probe->bFormatIndex = format->index;
1880         probe->bFrameIndex = frame->bFrameIndex;
1881
1882         stream->def_format = format;
1883         stream->cur_format = format;
1884         stream->cur_frame = frame;
1885
1886         /* Select the video decoding function */
1887         if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1888                 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1889                         stream->decode = uvc_video_decode_isight;
1890                 else if (stream->intf->num_altsetting > 1)
1891                         stream->decode = uvc_video_decode_isoc;
1892                 else
1893                         stream->decode = uvc_video_decode_bulk;
1894         } else {
1895                 if (stream->intf->num_altsetting == 1)
1896                         stream->decode = uvc_video_encode_bulk;
1897                 else {
1898                         uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1899                                 "supported for video output devices.\n");
1900                         return -EINVAL;
1901                 }
1902         }
1903
1904         return 0;
1905 }
1906
1907 /*
1908  * Enable or disable the video stream.
1909  */
1910 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1911 {
1912         int ret;
1913
1914         if (!enable) {
1915                 uvc_uninit_video(stream, 1);
1916                 if (stream->intf->num_altsetting > 1) {
1917                         usb_set_interface(stream->dev->udev,
1918                                           stream->intfnum, 0);
1919                 } else {
1920                         /* UVC doesn't specify how to inform a bulk-based device
1921                          * when the video stream is stopped. Windows sends a
1922                          * CLEAR_FEATURE(HALT) request to the video streaming
1923                          * bulk endpoint, mimic the same behaviour.
1924                          */
1925                         unsigned int epnum = stream->header.bEndpointAddress
1926                                            & USB_ENDPOINT_NUMBER_MASK;
1927                         unsigned int dir = stream->header.bEndpointAddress
1928                                          & USB_ENDPOINT_DIR_MASK;
1929                         unsigned int pipe;
1930
1931                         pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
1932                         usb_clear_halt(stream->dev->udev, pipe);
1933                 }
1934
1935                 uvc_video_clock_cleanup(stream);
1936                 return 0;
1937         }
1938
1939         ret = uvc_video_clock_init(stream);
1940         if (ret < 0)
1941                 return ret;
1942
1943         /* Commit the streaming parameters. */
1944         ret = uvc_commit_video(stream, &stream->ctrl);
1945         if (ret < 0)
1946                 goto error_commit;
1947
1948         ret = uvc_init_video(stream, GFP_KERNEL);
1949         if (ret < 0)
1950                 goto error_video;
1951
1952         return 0;
1953
1954 error_video:
1955         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1956 error_commit:
1957         uvc_video_clock_cleanup(stream);
1958
1959         return ret;
1960 }