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