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