GNU Linux-libre 4.9.309-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.tv_sec = stream->stats.stream.stop_ts.tv_sec
919                   - stream->stats.stream.start_ts.tv_sec;
920         ts.tv_nsec = stream->stats.stream.stop_ts.tv_nsec
921                    - stream->stats.stream.start_ts.tv_nsec;
922         if (ts.tv_nsec < 0) {
923                 ts.tv_sec--;
924                 ts.tv_nsec += 1000000000;
925         }
926
927         /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
928          * frequency this will not overflow before more than 1h.
929          */
930         duration = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
931         if (duration != 0)
932                 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
933                              / duration;
934         else
935                 scr_sof_freq = 0;
936
937         count += scnprintf(buf + count, size - count,
938                            "frames:  %u\npackets: %u\nempty:   %u\n"
939                            "errors:  %u\ninvalid: %u\n",
940                            stream->stats.stream.nb_frames,
941                            stream->stats.stream.nb_packets,
942                            stream->stats.stream.nb_empty,
943                            stream->stats.stream.nb_errors,
944                            stream->stats.stream.nb_invalid);
945         count += scnprintf(buf + count, size - count,
946                            "pts: %u early, %u initial, %u ok\n",
947                            stream->stats.stream.nb_pts_early,
948                            stream->stats.stream.nb_pts_initial,
949                            stream->stats.stream.nb_pts_constant);
950         count += scnprintf(buf + count, size - count,
951                            "scr: %u count ok, %u diff ok\n",
952                            stream->stats.stream.nb_scr_count_ok,
953                            stream->stats.stream.nb_scr_diffs_ok);
954         count += scnprintf(buf + count, size - count,
955                            "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
956                            stream->stats.stream.min_sof,
957                            stream->stats.stream.max_sof,
958                            scr_sof_freq / 1000, scr_sof_freq % 1000);
959
960         return count;
961 }
962
963 static void uvc_video_stats_start(struct uvc_streaming *stream)
964 {
965         memset(&stream->stats, 0, sizeof(stream->stats));
966         stream->stats.stream.min_sof = 2048;
967 }
968
969 static void uvc_video_stats_stop(struct uvc_streaming *stream)
970 {
971         ktime_get_ts(&stream->stats.stream.stop_ts);
972 }
973
974 /* ------------------------------------------------------------------------
975  * Video codecs
976  */
977
978 /* Video payload decoding is handled by uvc_video_decode_start(),
979  * uvc_video_decode_data() and uvc_video_decode_end().
980  *
981  * uvc_video_decode_start is called with URB data at the start of a bulk or
982  * isochronous payload. It processes header data and returns the header size
983  * in bytes if successful. If an error occurs, it returns a negative error
984  * code. The following error codes have special meanings.
985  *
986  * - EAGAIN informs the caller that the current video buffer should be marked
987  *   as done, and that the function should be called again with the same data
988  *   and a new video buffer. This is used when end of frame conditions can be
989  *   reliably detected at the beginning of the next frame only.
990  *
991  * If an error other than -EAGAIN is returned, the caller will drop the current
992  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
993  * made until the next payload. -ENODATA can be used to drop the current
994  * payload if no other error code is appropriate.
995  *
996  * uvc_video_decode_data is called for every URB with URB data. It copies the
997  * data to the video buffer.
998  *
999  * uvc_video_decode_end is called with header data at the end of a bulk or
1000  * isochronous payload. It performs any additional header data processing and
1001  * returns 0 or a negative error code if an error occurred. As header data have
1002  * already been processed by uvc_video_decode_start, this functions isn't
1003  * required to perform sanity checks a second time.
1004  *
1005  * For isochronous transfers where a payload is always transferred in a single
1006  * URB, the three functions will be called in a row.
1007  *
1008  * To let the decoder process header data and update its internal state even
1009  * when no video buffer is available, uvc_video_decode_start must be prepared
1010  * to be called with a NULL buf parameter. uvc_video_decode_data and
1011  * uvc_video_decode_end will never be called with a NULL buffer.
1012  */
1013 static int uvc_video_decode_start(struct uvc_streaming *stream,
1014                 struct uvc_buffer *buf, const __u8 *data, int len)
1015 {
1016         __u8 fid;
1017
1018         /* Sanity checks:
1019          * - packet must be at least 2 bytes long
1020          * - bHeaderLength value must be at least 2 bytes (see above)
1021          * - bHeaderLength value can't be larger than the packet size.
1022          */
1023         if (len < 2 || data[0] < 2 || data[0] > len) {
1024                 stream->stats.frame.nb_invalid++;
1025                 return -EINVAL;
1026         }
1027
1028         fid = data[1] & UVC_STREAM_FID;
1029
1030         /* Increase the sequence number regardless of any buffer states, so
1031          * that discontinuous sequence numbers always indicate lost frames.
1032          */
1033         if (stream->last_fid != fid) {
1034                 stream->sequence++;
1035                 if (stream->sequence)
1036                         uvc_video_stats_update(stream);
1037         }
1038
1039         uvc_video_clock_decode(stream, buf, data, len);
1040         uvc_video_stats_decode(stream, data, len);
1041
1042         /* Store the payload FID bit and return immediately when the buffer is
1043          * NULL.
1044          */
1045         if (buf == NULL) {
1046                 stream->last_fid = fid;
1047                 return -ENODATA;
1048         }
1049
1050         /* Mark the buffer as bad if the error bit is set. */
1051         if (data[1] & UVC_STREAM_ERR) {
1052                 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1053                           "set).\n");
1054                 buf->error = 1;
1055         }
1056
1057         /* Synchronize to the input stream by waiting for the FID bit to be
1058          * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1059          * stream->last_fid is initialized to -1, so the first isochronous
1060          * frame will always be in sync.
1061          *
1062          * If the device doesn't toggle the FID bit, invert stream->last_fid
1063          * when the EOF bit is set to force synchronisation on the next packet.
1064          */
1065         if (buf->state != UVC_BUF_STATE_ACTIVE) {
1066                 struct timespec ts;
1067
1068                 if (fid == stream->last_fid) {
1069                         uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1070                                 "sync).\n");
1071                         if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1072                             (data[1] & UVC_STREAM_EOF))
1073                                 stream->last_fid ^= UVC_STREAM_FID;
1074                         return -ENODATA;
1075                 }
1076
1077                 uvc_video_get_ts(&ts);
1078
1079                 buf->buf.field = V4L2_FIELD_NONE;
1080                 buf->buf.sequence = stream->sequence;
1081                 buf->buf.vb2_buf.timestamp = timespec_to_ns(&ts);
1082
1083                 /* TODO: Handle PTS and SCR. */
1084                 buf->state = UVC_BUF_STATE_ACTIVE;
1085         }
1086
1087         /* Mark the buffer as done if we're at the beginning of a new frame.
1088          * End of frame detection is better implemented by checking the EOF
1089          * bit (FID bit toggling is delayed by one frame compared to the EOF
1090          * bit), but some devices don't set the bit at end of frame (and the
1091          * last payload can be lost anyway). We thus must check if the FID has
1092          * been toggled.
1093          *
1094          * stream->last_fid is initialized to -1, so the first isochronous
1095          * frame will never trigger an end of frame detection.
1096          *
1097          * Empty buffers (bytesused == 0) don't trigger end of frame detection
1098          * as it doesn't make sense to return an empty buffer. This also
1099          * avoids detecting end of frame conditions at FID toggling if the
1100          * previous payload had the EOF bit set.
1101          */
1102         if (fid != stream->last_fid && buf->bytesused != 0) {
1103                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1104                                 "toggled).\n");
1105                 buf->state = UVC_BUF_STATE_READY;
1106                 return -EAGAIN;
1107         }
1108
1109         stream->last_fid = fid;
1110
1111         return data[0];
1112 }
1113
1114 static void uvc_video_decode_data(struct uvc_streaming *stream,
1115                 struct uvc_buffer *buf, const __u8 *data, int len)
1116 {
1117         unsigned int maxlen, nbytes;
1118         void *mem;
1119
1120         if (len <= 0)
1121                 return;
1122
1123         /* Copy the video data to the buffer. */
1124         maxlen = buf->length - buf->bytesused;
1125         mem = buf->mem + buf->bytesused;
1126         nbytes = min((unsigned int)len, maxlen);
1127         memcpy(mem, data, nbytes);
1128         buf->bytesused += nbytes;
1129
1130         /* Complete the current frame if the buffer size was exceeded. */
1131         if (len > maxlen) {
1132                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1133                 buf->state = UVC_BUF_STATE_READY;
1134         }
1135 }
1136
1137 static void uvc_video_decode_end(struct uvc_streaming *stream,
1138                 struct uvc_buffer *buf, const __u8 *data, int len)
1139 {
1140         /* Mark the buffer as done if the EOF marker is set. */
1141         if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1142                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1143                 if (data[0] == len)
1144                         uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1145                 buf->state = UVC_BUF_STATE_READY;
1146                 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1147                         stream->last_fid ^= UVC_STREAM_FID;
1148         }
1149 }
1150
1151 /* Video payload encoding is handled by uvc_video_encode_header() and
1152  * uvc_video_encode_data(). Only bulk transfers are currently supported.
1153  *
1154  * uvc_video_encode_header is called at the start of a payload. It adds header
1155  * data to the transfer buffer and returns the header size. As the only known
1156  * UVC output device transfers a whole frame in a single payload, the EOF bit
1157  * is always set in the header.
1158  *
1159  * uvc_video_encode_data is called for every URB and copies the data from the
1160  * video buffer to the transfer buffer.
1161  */
1162 static int uvc_video_encode_header(struct uvc_streaming *stream,
1163                 struct uvc_buffer *buf, __u8 *data, int len)
1164 {
1165         data[0] = 2;    /* Header length */
1166         data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1167                 | (stream->last_fid & UVC_STREAM_FID);
1168         return 2;
1169 }
1170
1171 static int uvc_video_encode_data(struct uvc_streaming *stream,
1172                 struct uvc_buffer *buf, __u8 *data, int len)
1173 {
1174         struct uvc_video_queue *queue = &stream->queue;
1175         unsigned int nbytes;
1176         void *mem;
1177
1178         /* Copy video data to the URB buffer. */
1179         mem = buf->mem + queue->buf_used;
1180         nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1181         nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1182                         nbytes);
1183         memcpy(data, mem, nbytes);
1184
1185         queue->buf_used += nbytes;
1186
1187         return nbytes;
1188 }
1189
1190 /* ------------------------------------------------------------------------
1191  * URB handling
1192  */
1193
1194 /*
1195  * Set error flag for incomplete buffer.
1196  */
1197 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1198                                       struct uvc_buffer *buf)
1199 {
1200         if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1201             !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1202                 buf->error = 1;
1203 }
1204
1205 /*
1206  * Completion handler for video URBs.
1207  */
1208 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1209         struct uvc_buffer *buf)
1210 {
1211         u8 *mem;
1212         int ret, i;
1213
1214         for (i = 0; i < urb->number_of_packets; ++i) {
1215                 if (urb->iso_frame_desc[i].status < 0) {
1216                         uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1217                                 "lost (%d).\n", urb->iso_frame_desc[i].status);
1218                         /* Mark the buffer as faulty. */
1219                         if (buf != NULL)
1220                                 buf->error = 1;
1221                         continue;
1222                 }
1223
1224                 /* Decode the payload header. */
1225                 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1226                 do {
1227                         ret = uvc_video_decode_start(stream, buf, mem,
1228                                 urb->iso_frame_desc[i].actual_length);
1229                         if (ret == -EAGAIN) {
1230                                 uvc_video_validate_buffer(stream, buf);
1231                                 buf = uvc_queue_next_buffer(&stream->queue,
1232                                                             buf);
1233                         }
1234                 } while (ret == -EAGAIN);
1235
1236                 if (ret < 0)
1237                         continue;
1238
1239                 /* Decode the payload data. */
1240                 uvc_video_decode_data(stream, buf, mem + ret,
1241                         urb->iso_frame_desc[i].actual_length - ret);
1242
1243                 /* Process the header again. */
1244                 uvc_video_decode_end(stream, buf, mem,
1245                         urb->iso_frame_desc[i].actual_length);
1246
1247                 if (buf->state == UVC_BUF_STATE_READY) {
1248                         uvc_video_validate_buffer(stream, buf);
1249                         buf = uvc_queue_next_buffer(&stream->queue, buf);
1250                 }
1251         }
1252 }
1253
1254 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1255         struct uvc_buffer *buf)
1256 {
1257         u8 *mem;
1258         int len, ret;
1259
1260         /*
1261          * Ignore ZLPs if they're not part of a frame, otherwise process them
1262          * to trigger the end of payload detection.
1263          */
1264         if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1265                 return;
1266
1267         mem = urb->transfer_buffer;
1268         len = urb->actual_length;
1269         stream->bulk.payload_size += len;
1270
1271         /* If the URB is the first of its payload, decode and save the
1272          * header.
1273          */
1274         if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1275                 do {
1276                         ret = uvc_video_decode_start(stream, buf, mem, len);
1277                         if (ret == -EAGAIN)
1278                                 buf = uvc_queue_next_buffer(&stream->queue,
1279                                                             buf);
1280                 } while (ret == -EAGAIN);
1281
1282                 /* If an error occurred skip the rest of the payload. */
1283                 if (ret < 0 || buf == NULL) {
1284                         stream->bulk.skip_payload = 1;
1285                 } else {
1286                         memcpy(stream->bulk.header, mem, ret);
1287                         stream->bulk.header_size = ret;
1288
1289                         mem += ret;
1290                         len -= ret;
1291                 }
1292         }
1293
1294         /* The buffer queue might have been cancelled while a bulk transfer
1295          * was in progress, so we can reach here with buf equal to NULL. Make
1296          * sure buf is never dereferenced if NULL.
1297          */
1298
1299         /* Process video data. */
1300         if (!stream->bulk.skip_payload && buf != NULL)
1301                 uvc_video_decode_data(stream, buf, mem, len);
1302
1303         /* Detect the payload end by a URB smaller than the maximum size (or
1304          * a payload size equal to the maximum) and process the header again.
1305          */
1306         if (urb->actual_length < urb->transfer_buffer_length ||
1307             stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1308                 if (!stream->bulk.skip_payload && buf != NULL) {
1309                         uvc_video_decode_end(stream, buf, stream->bulk.header,
1310                                 stream->bulk.payload_size);
1311                         if (buf->state == UVC_BUF_STATE_READY)
1312                                 buf = uvc_queue_next_buffer(&stream->queue,
1313                                                             buf);
1314                 }
1315
1316                 stream->bulk.header_size = 0;
1317                 stream->bulk.skip_payload = 0;
1318                 stream->bulk.payload_size = 0;
1319         }
1320 }
1321
1322 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1323         struct uvc_buffer *buf)
1324 {
1325         u8 *mem = urb->transfer_buffer;
1326         int len = stream->urb_size, ret;
1327
1328         if (buf == NULL) {
1329                 urb->transfer_buffer_length = 0;
1330                 return;
1331         }
1332
1333         /* If the URB is the first of its payload, add the header. */
1334         if (stream->bulk.header_size == 0) {
1335                 ret = uvc_video_encode_header(stream, buf, mem, len);
1336                 stream->bulk.header_size = ret;
1337                 stream->bulk.payload_size += ret;
1338                 mem += ret;
1339                 len -= ret;
1340         }
1341
1342         /* Process video data. */
1343         ret = uvc_video_encode_data(stream, buf, mem, len);
1344
1345         stream->bulk.payload_size += ret;
1346         len -= ret;
1347
1348         if (buf->bytesused == stream->queue.buf_used ||
1349             stream->bulk.payload_size == stream->bulk.max_payload_size) {
1350                 if (buf->bytesused == stream->queue.buf_used) {
1351                         stream->queue.buf_used = 0;
1352                         buf->state = UVC_BUF_STATE_READY;
1353                         buf->buf.sequence = ++stream->sequence;
1354                         uvc_queue_next_buffer(&stream->queue, buf);
1355                         stream->last_fid ^= UVC_STREAM_FID;
1356                 }
1357
1358                 stream->bulk.header_size = 0;
1359                 stream->bulk.payload_size = 0;
1360         }
1361
1362         urb->transfer_buffer_length = stream->urb_size - len;
1363 }
1364
1365 static void uvc_video_complete(struct urb *urb)
1366 {
1367         struct uvc_streaming *stream = urb->context;
1368         struct uvc_video_queue *queue = &stream->queue;
1369         struct uvc_buffer *buf = NULL;
1370         unsigned long flags;
1371         int ret;
1372
1373         switch (urb->status) {
1374         case 0:
1375                 break;
1376
1377         default:
1378                 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1379                         "completion handler.\n", urb->status);
1380
1381         case -ENOENT:           /* usb_kill_urb() called. */
1382                 if (stream->frozen)
1383                         return;
1384
1385         case -ECONNRESET:       /* usb_unlink_urb() called. */
1386         case -ESHUTDOWN:        /* The endpoint is being disabled. */
1387                 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1388                 return;
1389         }
1390
1391         spin_lock_irqsave(&queue->irqlock, flags);
1392         if (!list_empty(&queue->irqqueue))
1393                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
1394                                        queue);
1395         spin_unlock_irqrestore(&queue->irqlock, flags);
1396
1397         stream->decode(urb, stream, buf);
1398
1399         if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
1400                 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1401                         ret);
1402         }
1403 }
1404
1405 /*
1406  * Free transfer buffers.
1407  */
1408 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1409 {
1410         unsigned int i;
1411
1412         for (i = 0; i < UVC_URBS; ++i) {
1413                 if (stream->urb_buffer[i]) {
1414 #ifndef CONFIG_DMA_NONCOHERENT
1415                         usb_free_coherent(stream->dev->udev, stream->urb_size,
1416                                 stream->urb_buffer[i], stream->urb_dma[i]);
1417 #else
1418                         kfree(stream->urb_buffer[i]);
1419 #endif
1420                         stream->urb_buffer[i] = NULL;
1421                 }
1422         }
1423
1424         stream->urb_size = 0;
1425 }
1426
1427 /*
1428  * Allocate transfer buffers. This function can be called with buffers
1429  * already allocated when resuming from suspend, in which case it will
1430  * return without touching the buffers.
1431  *
1432  * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1433  * system is too low on memory try successively smaller numbers of packets
1434  * until allocation succeeds.
1435  *
1436  * Return the number of allocated packets on success or 0 when out of memory.
1437  */
1438 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1439         unsigned int size, unsigned int psize, gfp_t gfp_flags)
1440 {
1441         unsigned int npackets;
1442         unsigned int i;
1443
1444         /* Buffers are already allocated, bail out. */
1445         if (stream->urb_size)
1446                 return stream->urb_size / psize;
1447
1448         /* Compute the number of packets. Bulk endpoints might transfer UVC
1449          * payloads across multiple URBs.
1450          */
1451         npackets = DIV_ROUND_UP(size, psize);
1452         if (npackets > UVC_MAX_PACKETS)
1453                 npackets = UVC_MAX_PACKETS;
1454
1455         /* Retry allocations until one succeed. */
1456         for (; npackets > 1; npackets /= 2) {
1457                 for (i = 0; i < UVC_URBS; ++i) {
1458                         stream->urb_size = psize * npackets;
1459 #ifndef CONFIG_DMA_NONCOHERENT
1460                         stream->urb_buffer[i] = usb_alloc_coherent(
1461                                 stream->dev->udev, stream->urb_size,
1462                                 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1463 #else
1464                         stream->urb_buffer[i] =
1465                             kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1466 #endif
1467                         if (!stream->urb_buffer[i]) {
1468                                 uvc_free_urb_buffers(stream);
1469                                 break;
1470                         }
1471                 }
1472
1473                 if (i == UVC_URBS) {
1474                         uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1475                                 "of %ux%u bytes each.\n", UVC_URBS, npackets,
1476                                 psize);
1477                         return npackets;
1478                 }
1479         }
1480
1481         uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1482                 "per packet).\n", psize);
1483         return 0;
1484 }
1485
1486 /*
1487  * Uninitialize isochronous/bulk URBs and free transfer buffers.
1488  */
1489 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1490 {
1491         struct urb *urb;
1492         unsigned int i;
1493
1494         uvc_video_stats_stop(stream);
1495
1496         for (i = 0; i < UVC_URBS; ++i) {
1497                 urb = stream->urb[i];
1498                 if (urb == NULL)
1499                         continue;
1500
1501                 usb_kill_urb(urb);
1502                 usb_free_urb(urb);
1503                 stream->urb[i] = NULL;
1504         }
1505
1506         if (free_buffers)
1507                 uvc_free_urb_buffers(stream);
1508 }
1509
1510 /*
1511  * Compute the maximum number of bytes per interval for an endpoint.
1512  */
1513 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1514                                          struct usb_host_endpoint *ep)
1515 {
1516         u16 psize;
1517
1518         switch (dev->speed) {
1519         case USB_SPEED_SUPER:
1520         case USB_SPEED_SUPER_PLUS:
1521                 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1522         case USB_SPEED_HIGH:
1523                 psize = usb_endpoint_maxp(&ep->desc);
1524                 return (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1525         case USB_SPEED_WIRELESS:
1526                 psize = usb_endpoint_maxp(&ep->desc);
1527                 return psize;
1528         default:
1529                 psize = usb_endpoint_maxp(&ep->desc);
1530                 return psize & 0x07ff;
1531         }
1532 }
1533
1534 /*
1535  * Initialize isochronous URBs and allocate transfer buffers. The packet size
1536  * is given by the endpoint.
1537  */
1538 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1539         struct usb_host_endpoint *ep, gfp_t gfp_flags)
1540 {
1541         struct urb *urb;
1542         unsigned int npackets, i, j;
1543         u16 psize;
1544         u32 size;
1545
1546         psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1547         size = stream->ctrl.dwMaxVideoFrameSize;
1548
1549         npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1550         if (npackets == 0)
1551                 return -ENOMEM;
1552
1553         size = npackets * psize;
1554
1555         for (i = 0; i < UVC_URBS; ++i) {
1556                 urb = usb_alloc_urb(npackets, gfp_flags);
1557                 if (urb == NULL) {
1558                         uvc_uninit_video(stream, 1);
1559                         return -ENOMEM;
1560                 }
1561
1562                 urb->dev = stream->dev->udev;
1563                 urb->context = stream;
1564                 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1565                                 ep->desc.bEndpointAddress);
1566 #ifndef CONFIG_DMA_NONCOHERENT
1567                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1568                 urb->transfer_dma = stream->urb_dma[i];
1569 #else
1570                 urb->transfer_flags = URB_ISO_ASAP;
1571 #endif
1572                 urb->interval = ep->desc.bInterval;
1573                 urb->transfer_buffer = stream->urb_buffer[i];
1574                 urb->complete = uvc_video_complete;
1575                 urb->number_of_packets = npackets;
1576                 urb->transfer_buffer_length = size;
1577
1578                 for (j = 0; j < npackets; ++j) {
1579                         urb->iso_frame_desc[j].offset = j * psize;
1580                         urb->iso_frame_desc[j].length = psize;
1581                 }
1582
1583                 stream->urb[i] = urb;
1584         }
1585
1586         return 0;
1587 }
1588
1589 /*
1590  * Initialize bulk URBs and allocate transfer buffers. The packet size is
1591  * given by the endpoint.
1592  */
1593 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1594         struct usb_host_endpoint *ep, gfp_t gfp_flags)
1595 {
1596         struct urb *urb;
1597         unsigned int npackets, pipe, i;
1598         u16 psize;
1599         u32 size;
1600
1601         psize = usb_endpoint_maxp(&ep->desc) & 0x7ff;
1602         size = stream->ctrl.dwMaxPayloadTransferSize;
1603         stream->bulk.max_payload_size = size;
1604
1605         npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1606         if (npackets == 0)
1607                 return -ENOMEM;
1608
1609         size = npackets * psize;
1610
1611         if (usb_endpoint_dir_in(&ep->desc))
1612                 pipe = usb_rcvbulkpipe(stream->dev->udev,
1613                                        ep->desc.bEndpointAddress);
1614         else
1615                 pipe = usb_sndbulkpipe(stream->dev->udev,
1616                                        ep->desc.bEndpointAddress);
1617
1618         if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1619                 size = 0;
1620
1621         for (i = 0; i < UVC_URBS; ++i) {
1622                 urb = usb_alloc_urb(0, gfp_flags);
1623                 if (urb == NULL) {
1624                         uvc_uninit_video(stream, 1);
1625                         return -ENOMEM;
1626                 }
1627
1628                 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1629                         stream->urb_buffer[i], size, uvc_video_complete,
1630                         stream);
1631 #ifndef CONFIG_DMA_NONCOHERENT
1632                 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1633                 urb->transfer_dma = stream->urb_dma[i];
1634 #endif
1635
1636                 stream->urb[i] = urb;
1637         }
1638
1639         return 0;
1640 }
1641
1642 /*
1643  * Initialize isochronous/bulk URBs and allocate transfer buffers.
1644  */
1645 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1646 {
1647         struct usb_interface *intf = stream->intf;
1648         struct usb_host_endpoint *ep;
1649         unsigned int i;
1650         int ret;
1651
1652         stream->sequence = -1;
1653         stream->last_fid = -1;
1654         stream->bulk.header_size = 0;
1655         stream->bulk.skip_payload = 0;
1656         stream->bulk.payload_size = 0;
1657
1658         uvc_video_stats_start(stream);
1659
1660         if (intf->num_altsetting > 1) {
1661                 struct usb_host_endpoint *best_ep = NULL;
1662                 unsigned int best_psize = UINT_MAX;
1663                 unsigned int bandwidth;
1664                 unsigned int uninitialized_var(altsetting);
1665                 int intfnum = stream->intfnum;
1666
1667                 /* Isochronous endpoint, select the alternate setting. */
1668                 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1669
1670                 if (bandwidth == 0) {
1671                         uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1672                                 "bandwidth, defaulting to lowest.\n");
1673                         bandwidth = 1;
1674                 } else {
1675                         uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1676                                 "B/frame bandwidth.\n", bandwidth);
1677                 }
1678
1679                 for (i = 0; i < intf->num_altsetting; ++i) {
1680                         struct usb_host_interface *alts;
1681                         unsigned int psize;
1682
1683                         alts = &intf->altsetting[i];
1684                         ep = uvc_find_endpoint(alts,
1685                                 stream->header.bEndpointAddress);
1686                         if (ep == NULL)
1687                                 continue;
1688
1689                         /* Check if the bandwidth is high enough. */
1690                         psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1691                         if (psize >= bandwidth && psize <= best_psize) {
1692                                 altsetting = alts->desc.bAlternateSetting;
1693                                 best_psize = psize;
1694                                 best_ep = ep;
1695                         }
1696                 }
1697
1698                 if (best_ep == NULL) {
1699                         uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1700                                 "for requested bandwidth.\n");
1701                         return -EIO;
1702                 }
1703
1704                 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1705                         "(%u B/frame bandwidth).\n", altsetting, best_psize);
1706
1707                 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1708                 if (ret < 0)
1709                         return ret;
1710
1711                 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1712         } else {
1713                 /* Bulk endpoint, proceed to URB initialization. */
1714                 ep = uvc_find_endpoint(&intf->altsetting[0],
1715                                 stream->header.bEndpointAddress);
1716                 if (ep == NULL)
1717                         return -EIO;
1718
1719                 /* Reject broken descriptors. */
1720                 if (usb_endpoint_maxp(&ep->desc) == 0)
1721                         return -EIO;
1722
1723                 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1724         }
1725
1726         if (ret < 0)
1727                 return ret;
1728
1729         /* Submit the URBs. */
1730         for (i = 0; i < UVC_URBS; ++i) {
1731                 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1732                 if (ret < 0) {
1733                         uvc_printk(KERN_ERR, "Failed to submit URB %u "
1734                                         "(%d).\n", i, ret);
1735                         uvc_uninit_video(stream, 1);
1736                         return ret;
1737                 }
1738         }
1739
1740         /* The Logitech C920 temporarily forgets that it should not be adjusting
1741          * Exposure Absolute during init so restore controls to stored values.
1742          */
1743         if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1744                 uvc_ctrl_restore_values(stream->dev);
1745
1746         return 0;
1747 }
1748
1749 /* --------------------------------------------------------------------------
1750  * Suspend/resume
1751  */
1752
1753 /*
1754  * Stop streaming without disabling the video queue.
1755  *
1756  * To let userspace applications resume without trouble, we must not touch the
1757  * video buffers in any way. We mark the device as frozen to make sure the URB
1758  * completion handler won't try to cancel the queue when we kill the URBs.
1759  */
1760 int uvc_video_suspend(struct uvc_streaming *stream)
1761 {
1762         if (!uvc_queue_streaming(&stream->queue))
1763                 return 0;
1764
1765         stream->frozen = 1;
1766         uvc_uninit_video(stream, 0);
1767         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1768         return 0;
1769 }
1770
1771 /*
1772  * Reconfigure the video interface and restart streaming if it was enabled
1773  * before suspend.
1774  *
1775  * If an error occurs, disable the video queue. This will wake all pending
1776  * buffers, making sure userspace applications are notified of the problem
1777  * instead of waiting forever.
1778  */
1779 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1780 {
1781         int ret;
1782
1783         /* If the bus has been reset on resume, set the alternate setting to 0.
1784          * This should be the default value, but some devices crash or otherwise
1785          * misbehave if they don't receive a SET_INTERFACE request before any
1786          * other video control request.
1787          */
1788         if (reset)
1789                 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1790
1791         stream->frozen = 0;
1792
1793         uvc_video_clock_reset(stream);
1794
1795         if (!uvc_queue_streaming(&stream->queue))
1796                 return 0;
1797
1798         ret = uvc_commit_video(stream, &stream->ctrl);
1799         if (ret < 0)
1800                 return ret;
1801
1802         return uvc_init_video(stream, GFP_NOIO);
1803 }
1804
1805 /* ------------------------------------------------------------------------
1806  * Video device
1807  */
1808
1809 /*
1810  * Initialize the UVC video device by switching to alternate setting 0 and
1811  * retrieve the default format.
1812  *
1813  * Some cameras (namely the Fuji Finepix) set the format and frame
1814  * indexes to zero. The UVC standard doesn't clearly make this a spec
1815  * violation, so try to silently fix the values if possible.
1816  *
1817  * This function is called before registering the device with V4L.
1818  */
1819 int uvc_video_init(struct uvc_streaming *stream)
1820 {
1821         struct uvc_streaming_control *probe = &stream->ctrl;
1822         struct uvc_format *format = NULL;
1823         struct uvc_frame *frame = NULL;
1824         unsigned int i;
1825         int ret;
1826
1827         if (stream->nformats == 0) {
1828                 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1829                 return -EINVAL;
1830         }
1831
1832         atomic_set(&stream->active, 0);
1833
1834         /* Alternate setting 0 should be the default, yet the XBox Live Vision
1835          * Cam (and possibly other devices) crash or otherwise misbehave if
1836          * they don't receive a SET_INTERFACE request before any other video
1837          * control request.
1838          */
1839         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1840
1841         /* Set the streaming probe control with default streaming parameters
1842          * retrieved from the device. Webcams that don't suport GET_DEF
1843          * requests on the probe control will just keep their current streaming
1844          * parameters.
1845          */
1846         if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1847                 uvc_set_video_ctrl(stream, probe, 1);
1848
1849         /* Initialize the streaming parameters with the probe control current
1850          * value. This makes sure SET_CUR requests on the streaming commit
1851          * control will always use values retrieved from a successful GET_CUR
1852          * request on the probe control, as required by the UVC specification.
1853          */
1854         ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1855         if (ret < 0)
1856                 return ret;
1857
1858         /* Check if the default format descriptor exists. Use the first
1859          * available format otherwise.
1860          */
1861         for (i = stream->nformats; i > 0; --i) {
1862                 format = &stream->format[i-1];
1863                 if (format->index == probe->bFormatIndex)
1864                         break;
1865         }
1866
1867         if (format->nframes == 0) {
1868                 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1869                         "default format.\n");
1870                 return -EINVAL;
1871         }
1872
1873         /* Zero bFrameIndex might be correct. Stream-based formats (including
1874          * MPEG-2 TS and DV) do not support frames but have a dummy frame
1875          * descriptor with bFrameIndex set to zero. If the default frame
1876          * descriptor is not found, use the first available frame.
1877          */
1878         for (i = format->nframes; i > 0; --i) {
1879                 frame = &format->frame[i-1];
1880                 if (frame->bFrameIndex == probe->bFrameIndex)
1881                         break;
1882         }
1883
1884         probe->bFormatIndex = format->index;
1885         probe->bFrameIndex = frame->bFrameIndex;
1886
1887         stream->def_format = format;
1888         stream->cur_format = format;
1889         stream->cur_frame = frame;
1890
1891         /* Select the video decoding function */
1892         if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1893                 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1894                         stream->decode = uvc_video_decode_isight;
1895                 else if (stream->intf->num_altsetting > 1)
1896                         stream->decode = uvc_video_decode_isoc;
1897                 else
1898                         stream->decode = uvc_video_decode_bulk;
1899         } else {
1900                 if (stream->intf->num_altsetting == 1)
1901                         stream->decode = uvc_video_encode_bulk;
1902                 else {
1903                         uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1904                                 "supported for video output devices.\n");
1905                         return -EINVAL;
1906                 }
1907         }
1908
1909         return 0;
1910 }
1911
1912 /*
1913  * Enable or disable the video stream.
1914  */
1915 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1916 {
1917         int ret;
1918
1919         if (!enable) {
1920                 uvc_uninit_video(stream, 1);
1921                 if (stream->intf->num_altsetting > 1) {
1922                         usb_set_interface(stream->dev->udev,
1923                                           stream->intfnum, 0);
1924                 } else {
1925                         /* UVC doesn't specify how to inform a bulk-based device
1926                          * when the video stream is stopped. Windows sends a
1927                          * CLEAR_FEATURE(HALT) request to the video streaming
1928                          * bulk endpoint, mimic the same behaviour.
1929                          */
1930                         unsigned int epnum = stream->header.bEndpointAddress
1931                                            & USB_ENDPOINT_NUMBER_MASK;
1932                         unsigned int dir = stream->header.bEndpointAddress
1933                                          & USB_ENDPOINT_DIR_MASK;
1934                         unsigned int pipe;
1935
1936                         pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
1937                         usb_clear_halt(stream->dev->udev, pipe);
1938                 }
1939
1940                 uvc_video_clock_cleanup(stream);
1941                 return 0;
1942         }
1943
1944         ret = uvc_video_clock_init(stream);
1945         if (ret < 0)
1946                 return ret;
1947
1948         /* Commit the streaming parameters. */
1949         ret = uvc_commit_video(stream, &stream->ctrl);
1950         if (ret < 0)
1951                 goto error_commit;
1952
1953         ret = uvc_init_video(stream, GFP_KERNEL);
1954         if (ret < 0)
1955                 goto error_video;
1956
1957         return 0;
1958
1959 error_video:
1960         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1961 error_commit:
1962         uvc_video_clock_cleanup(stream);
1963
1964         return ret;
1965 }