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