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