Linux 4.19.133
[linux/fpc-iii.git] / drivers / media / usb / uvc / uvc_video.c
blobffffb66d51a00415b16dfc8e6094b25ff5da3868
1 /*
2 * uvc_video.c -- USB Video Class driver - Video handling
4 * Copyright (C) 2005-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
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.
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>
25 #include <media/v4l2-common.h>
27 #include "uvcvideo.h"
29 /* ------------------------------------------------------------------------
30 * UVC Controls
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)
37 u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
38 unsigned int pipe;
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;
44 return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
45 unit << 8 | intfnum, data, size, timeout);
48 static const char *uvc_query_name(u8 query)
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>";
72 int uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
73 u8 intfnum, u8 cs, void *data, u16 size)
75 int ret;
76 u8 error;
77 u8 tmp;
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;
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);
88 if (ret != -EPIPE)
89 return ret;
91 tmp = *(u8 *)data;
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);
97 error = *(u8 *)data;
98 *(u8 *)data = tmp;
100 if (ret != 1)
101 return ret < 0 ? ret : -EPIPE;
103 uvc_trace(UVC_TRACE_CONTROL, "Control error %u\n", error);
105 switch (error) {
106 case 0:
107 /* Cannot happen - we received a STALL */
108 return -EPIPE;
109 case 1: /* Not ready */
110 return -EBUSY;
111 case 2: /* Wrong state */
112 return -EILSEQ;
113 case 3: /* Power */
114 return -EREMOTE;
115 case 4: /* Out of range */
116 return -ERANGE;
117 case 5: /* Invalid unit */
118 case 6: /* Invalid control */
119 case 7: /* Invalid Request */
120 case 8: /* Invalid value within range */
121 return -EINVAL;
122 default: /* reserved or unknown */
123 break;
126 return -EPIPE;
129 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
130 struct uvc_streaming_control *ctrl)
132 struct uvc_format *format = NULL;
133 struct uvc_frame *frame = NULL;
134 unsigned int i;
136 for (i = 0; i < stream->nformats; ++i) {
137 if (stream->format[i].index == ctrl->bFormatIndex) {
138 format = &stream->format[i];
139 break;
143 if (format == NULL)
144 return;
146 for (i = 0; i < format->nframes; ++i) {
147 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
148 frame = &format->frame[i];
149 break;
153 if (frame == NULL)
154 return;
156 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
157 (ctrl->dwMaxVideoFrameSize == 0 &&
158 stream->dev->uvc_version < 0x0110))
159 ctrl->dwMaxVideoFrameSize =
160 frame->dwMaxVideoFrameBufferSize;
162 /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
163 * compute the bandwidth on 16 bits and erroneously sign-extend it to
164 * 32 bits, resulting in a huge bandwidth value. Detect and fix that
165 * condition by setting the 16 MSBs to 0 when they're all equal to 1.
167 if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
168 ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
170 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
171 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
172 stream->intf->num_altsetting > 1) {
173 u32 interval;
174 u32 bandwidth;
176 interval = (ctrl->dwFrameInterval > 100000)
177 ? ctrl->dwFrameInterval
178 : frame->dwFrameInterval[0];
180 /* Compute a bandwidth estimation by multiplying the frame
181 * size by the number of video frames per second, divide the
182 * result by the number of USB frames (or micro-frames for
183 * high-speed devices) per second and add the UVC header size
184 * (assumed to be 12 bytes long).
186 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
187 bandwidth *= 10000000 / interval + 1;
188 bandwidth /= 1000;
189 if (stream->dev->udev->speed == USB_SPEED_HIGH)
190 bandwidth /= 8;
191 bandwidth += 12;
193 /* The bandwidth estimate is too low for many cameras. Don't use
194 * maximum packet sizes lower than 1024 bytes to try and work
195 * around the problem. According to measurements done on two
196 * different camera models, the value is high enough to get most
197 * resolutions working while not preventing two simultaneous
198 * VGA streams at 15 fps.
200 bandwidth = max_t(u32, bandwidth, 1024);
202 ctrl->dwMaxPayloadTransferSize = bandwidth;
206 static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
209 * Return the size of the video probe and commit controls, which depends
210 * on the protocol version.
212 if (stream->dev->uvc_version < 0x0110)
213 return 26;
214 else if (stream->dev->uvc_version < 0x0150)
215 return 34;
216 else
217 return 48;
220 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
221 struct uvc_streaming_control *ctrl, int probe, u8 query)
223 u16 size = uvc_video_ctrl_size(stream);
224 u8 *data;
225 int ret;
227 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
228 query == UVC_GET_DEF)
229 return -EIO;
231 data = kmalloc(size, GFP_KERNEL);
232 if (data == NULL)
233 return -ENOMEM;
235 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
236 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
237 size, uvc_timeout_param);
239 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
240 /* Some cameras, mostly based on Bison Electronics chipsets,
241 * answer a GET_MIN or GET_MAX request with the wCompQuality
242 * field only.
244 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
245 "compliance - GET_MIN/MAX(PROBE) incorrectly "
246 "supported. Enabling workaround.\n");
247 memset(ctrl, 0, sizeof(*ctrl));
248 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
249 ret = 0;
250 goto out;
251 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
252 /* Many cameras don't support the GET_DEF request on their
253 * video probe control. Warn once and return, the caller will
254 * fall back to GET_CUR.
256 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
257 "compliance - GET_DEF(PROBE) not supported. "
258 "Enabling workaround.\n");
259 ret = -EIO;
260 goto out;
261 } else if (ret != size) {
262 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
263 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
264 ret, size);
265 ret = -EIO;
266 goto out;
269 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
270 ctrl->bFormatIndex = data[2];
271 ctrl->bFrameIndex = data[3];
272 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
273 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
274 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
275 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
276 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
277 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
278 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
279 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
281 if (size >= 34) {
282 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
283 ctrl->bmFramingInfo = data[30];
284 ctrl->bPreferedVersion = data[31];
285 ctrl->bMinVersion = data[32];
286 ctrl->bMaxVersion = data[33];
287 } else {
288 ctrl->dwClockFrequency = stream->dev->clock_frequency;
289 ctrl->bmFramingInfo = 0;
290 ctrl->bPreferedVersion = 0;
291 ctrl->bMinVersion = 0;
292 ctrl->bMaxVersion = 0;
295 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
296 * dwMaxPayloadTransferSize fields. Try to get the value from the
297 * format and frame descriptors.
299 uvc_fixup_video_ctrl(stream, ctrl);
300 ret = 0;
302 out:
303 kfree(data);
304 return ret;
307 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
308 struct uvc_streaming_control *ctrl, int probe)
310 u16 size = uvc_video_ctrl_size(stream);
311 u8 *data;
312 int ret;
314 data = kzalloc(size, GFP_KERNEL);
315 if (data == NULL)
316 return -ENOMEM;
318 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
319 data[2] = ctrl->bFormatIndex;
320 data[3] = ctrl->bFrameIndex;
321 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
322 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
323 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
324 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
325 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
326 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
327 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
328 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
330 if (size >= 34) {
331 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
332 data[30] = ctrl->bmFramingInfo;
333 data[31] = ctrl->bPreferedVersion;
334 data[32] = ctrl->bMinVersion;
335 data[33] = ctrl->bMaxVersion;
338 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
339 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
340 size, uvc_timeout_param);
341 if (ret != size) {
342 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
343 "%d (exp. %u).\n", probe ? "probe" : "commit",
344 ret, size);
345 ret = -EIO;
348 kfree(data);
349 return ret;
352 int uvc_probe_video(struct uvc_streaming *stream,
353 struct uvc_streaming_control *probe)
355 struct uvc_streaming_control probe_min, probe_max;
356 u16 bandwidth;
357 unsigned int i;
358 int ret;
360 /* Perform probing. The device should adjust the requested values
361 * according to its capabilities. However, some devices, namely the
362 * first generation UVC Logitech webcams, don't implement the Video
363 * Probe control properly, and just return the needed bandwidth. For
364 * that reason, if the needed bandwidth exceeds the maximum available
365 * bandwidth, try to lower the quality.
367 ret = uvc_set_video_ctrl(stream, probe, 1);
368 if (ret < 0)
369 goto done;
371 /* Get the minimum and maximum values for compression settings. */
372 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
373 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
374 if (ret < 0)
375 goto done;
376 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
377 if (ret < 0)
378 goto done;
380 probe->wCompQuality = probe_max.wCompQuality;
383 for (i = 0; i < 2; ++i) {
384 ret = uvc_set_video_ctrl(stream, probe, 1);
385 if (ret < 0)
386 goto done;
387 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
388 if (ret < 0)
389 goto done;
391 if (stream->intf->num_altsetting == 1)
392 break;
394 bandwidth = probe->dwMaxPayloadTransferSize;
395 if (bandwidth <= stream->maxpsize)
396 break;
398 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
399 ret = -ENOSPC;
400 goto done;
403 /* TODO: negotiate compression parameters */
404 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
405 probe->wPFrameRate = probe_min.wPFrameRate;
406 probe->wCompQuality = probe_max.wCompQuality;
407 probe->wCompWindowSize = probe_min.wCompWindowSize;
410 done:
411 return ret;
414 static int uvc_commit_video(struct uvc_streaming *stream,
415 struct uvc_streaming_control *probe)
417 return uvc_set_video_ctrl(stream, probe, 0);
420 /* -----------------------------------------------------------------------------
421 * Clocks and timestamps
424 static inline ktime_t uvc_video_get_time(void)
426 if (uvc_clock_param == CLOCK_MONOTONIC)
427 return ktime_get();
428 else
429 return ktime_get_real();
432 static void
433 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
434 const u8 *data, int len)
436 struct uvc_clock_sample *sample;
437 unsigned int header_size;
438 bool has_pts = false;
439 bool has_scr = false;
440 unsigned long flags;
441 ktime_t time;
442 u16 host_sof;
443 u16 dev_sof;
445 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
446 case UVC_STREAM_PTS | UVC_STREAM_SCR:
447 header_size = 12;
448 has_pts = true;
449 has_scr = true;
450 break;
451 case UVC_STREAM_PTS:
452 header_size = 6;
453 has_pts = true;
454 break;
455 case UVC_STREAM_SCR:
456 header_size = 8;
457 has_scr = true;
458 break;
459 default:
460 header_size = 2;
461 break;
464 /* Check for invalid headers. */
465 if (len < header_size)
466 return;
468 /* Extract the timestamps:
470 * - store the frame PTS in the buffer structure
471 * - if the SCR field is present, retrieve the host SOF counter and
472 * kernel timestamps and store them with the SCR STC and SOF fields
473 * in the ring buffer
475 if (has_pts && buf != NULL)
476 buf->pts = get_unaligned_le32(&data[2]);
478 if (!has_scr)
479 return;
481 /* To limit the amount of data, drop SCRs with an SOF identical to the
482 * previous one.
484 dev_sof = get_unaligned_le16(&data[header_size - 2]);
485 if (dev_sof == stream->clock.last_sof)
486 return;
488 stream->clock.last_sof = dev_sof;
490 host_sof = usb_get_current_frame_number(stream->dev->udev);
491 time = uvc_video_get_time();
493 /* The UVC specification allows device implementations that can't obtain
494 * the USB frame number to keep their own frame counters as long as they
495 * match the size and frequency of the frame number associated with USB
496 * SOF tokens. The SOF values sent by such devices differ from the USB
497 * SOF tokens by a fixed offset that needs to be estimated and accounted
498 * for to make timestamp recovery as accurate as possible.
500 * The offset is estimated the first time a device SOF value is received
501 * as the difference between the host and device SOF values. As the two
502 * SOF values can differ slightly due to transmission delays, consider
503 * that the offset is null if the difference is not higher than 10 ms
504 * (negative differences can not happen and are thus considered as an
505 * offset). The video commit control wDelay field should be used to
506 * compute a dynamic threshold instead of using a fixed 10 ms value, but
507 * devices don't report reliable wDelay values.
509 * See uvc_video_clock_host_sof() for an explanation regarding why only
510 * the 8 LSBs of the delta are kept.
512 if (stream->clock.sof_offset == (u16)-1) {
513 u16 delta_sof = (host_sof - dev_sof) & 255;
514 if (delta_sof >= 10)
515 stream->clock.sof_offset = delta_sof;
516 else
517 stream->clock.sof_offset = 0;
520 dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
522 spin_lock_irqsave(&stream->clock.lock, flags);
524 sample = &stream->clock.samples[stream->clock.head];
525 sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
526 sample->dev_sof = dev_sof;
527 sample->host_sof = host_sof;
528 sample->host_time = time;
530 /* Update the sliding window head and count. */
531 stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
533 if (stream->clock.count < stream->clock.size)
534 stream->clock.count++;
536 spin_unlock_irqrestore(&stream->clock.lock, flags);
539 static void uvc_video_clock_reset(struct uvc_streaming *stream)
541 struct uvc_clock *clock = &stream->clock;
543 clock->head = 0;
544 clock->count = 0;
545 clock->last_sof = -1;
546 clock->sof_offset = -1;
549 static int uvc_video_clock_init(struct uvc_streaming *stream)
551 struct uvc_clock *clock = &stream->clock;
553 spin_lock_init(&clock->lock);
554 clock->size = 32;
556 clock->samples = kmalloc_array(clock->size, sizeof(*clock->samples),
557 GFP_KERNEL);
558 if (clock->samples == NULL)
559 return -ENOMEM;
561 uvc_video_clock_reset(stream);
563 return 0;
566 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
568 kfree(stream->clock.samples);
569 stream->clock.samples = NULL;
573 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
575 * Host SOF counters reported by usb_get_current_frame_number() usually don't
576 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
577 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
578 * controller and its configuration.
580 * We thus need to recover the SOF value corresponding to the host frame number.
581 * As the device and host frame numbers are sampled in a short interval, the
582 * difference between their values should be equal to a small delta plus an
583 * integer multiple of 256 caused by the host frame number limited precision.
585 * To obtain the recovered host SOF value, compute the small delta by masking
586 * the high bits of the host frame counter and device SOF difference and add it
587 * to the device SOF value.
589 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
591 /* The delta value can be negative. */
592 s8 delta_sof;
594 delta_sof = (sample->host_sof - sample->dev_sof) & 255;
596 return (sample->dev_sof + delta_sof) & 2047;
600 * uvc_video_clock_update - Update the buffer timestamp
602 * This function converts the buffer PTS timestamp to the host clock domain by
603 * going through the USB SOF clock domain and stores the result in the V4L2
604 * buffer timestamp field.
606 * The relationship between the device clock and the host clock isn't known.
607 * However, the device and the host share the common USB SOF clock which can be
608 * used to recover that relationship.
610 * The relationship between the device clock and the USB SOF clock is considered
611 * to be linear over the clock samples sliding window and is given by
613 * SOF = m * PTS + p
615 * Several methods to compute the slope (m) and intercept (p) can be used. As
616 * the clock drift should be small compared to the sliding window size, we
617 * assume that the line that goes through the points at both ends of the window
618 * is a good approximation. Naming those points P1 and P2, we get
620 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
621 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
623 * or
625 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
627 * to avoid losing precision in the division. Similarly, the host timestamp is
628 * computed with
630 * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
632 * SOF values are coded on 11 bits by USB. We extend their precision with 16
633 * decimal bits, leading to a 11.16 coding.
635 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
636 * be normalized using the nominal device clock frequency reported through the
637 * UVC descriptors.
639 * Both the PTS/STC and SOF counters roll over, after a fixed but device
640 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
641 * sliding window size is smaller than the rollover period, differences computed
642 * on unsigned integers will produce the correct result. However, the p term in
643 * the linear relations will be miscomputed.
645 * To fix the issue, we subtract a constant from the PTS and STC values to bring
646 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
647 * the 32 bit range without any rollover.
649 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
650 * computed by (1) will never be smaller than 0. This offset is then compensated
651 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
652 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
653 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
654 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
655 * SOF value at the end of the sliding window.
657 * Finally we subtract a constant from the host timestamps to bring the first
658 * timestamp of the sliding window to 1s.
660 void uvc_video_clock_update(struct uvc_streaming *stream,
661 struct vb2_v4l2_buffer *vbuf,
662 struct uvc_buffer *buf)
664 struct uvc_clock *clock = &stream->clock;
665 struct uvc_clock_sample *first;
666 struct uvc_clock_sample *last;
667 unsigned long flags;
668 u64 timestamp;
669 u32 delta_stc;
670 u32 y1, y2;
671 u32 x1, x2;
672 u32 mean;
673 u32 sof;
674 u64 y;
676 if (!uvc_hw_timestamps_param)
677 return;
680 * We will get called from __vb2_queue_cancel() if there are buffers
681 * done but not dequeued by the user, but the sample array has already
682 * been released at that time. Just bail out in that case.
684 if (!clock->samples)
685 return;
687 spin_lock_irqsave(&clock->lock, flags);
689 if (clock->count < clock->size)
690 goto done;
692 first = &clock->samples[clock->head];
693 last = &clock->samples[(clock->head - 1) % clock->size];
695 /* First step, PTS to SOF conversion. */
696 delta_stc = buf->pts - (1UL << 31);
697 x1 = first->dev_stc - delta_stc;
698 x2 = last->dev_stc - delta_stc;
699 if (x1 == x2)
700 goto done;
702 y1 = (first->dev_sof + 2048) << 16;
703 y2 = (last->dev_sof + 2048) << 16;
704 if (y2 < y1)
705 y2 += 2048 << 16;
707 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
708 - (u64)y2 * (u64)x1;
709 y = div_u64(y, x2 - x1);
711 sof = y;
713 uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
714 "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
715 stream->dev->name, buf->pts,
716 y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
717 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
718 x1, x2, y1, y2, clock->sof_offset);
720 /* Second step, SOF to host clock conversion. */
721 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
722 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
723 if (x2 < x1)
724 x2 += 2048 << 16;
725 if (x1 == x2)
726 goto done;
728 y1 = NSEC_PER_SEC;
729 y2 = (u32)ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
731 /* Interpolated and host SOF timestamps can wrap around at slightly
732 * different times. Handle this by adding or removing 2048 to or from
733 * the computed SOF value to keep it close to the SOF samples mean
734 * value.
736 mean = (x1 + x2) / 2;
737 if (mean - (1024 << 16) > sof)
738 sof += 2048 << 16;
739 else if (sof > mean + (1024 << 16))
740 sof -= 2048 << 16;
742 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
743 - (u64)y2 * (u64)x1;
744 y = div_u64(y, x2 - x1);
746 timestamp = ktime_to_ns(first->host_time) + y - y1;
748 uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %llu "
749 "buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
750 stream->dev->name,
751 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
752 y, timestamp, vbuf->vb2_buf.timestamp,
753 x1, first->host_sof, first->dev_sof,
754 x2, last->host_sof, last->dev_sof, y1, y2);
756 /* Update the V4L2 buffer. */
757 vbuf->vb2_buf.timestamp = timestamp;
759 done:
760 spin_unlock_irqrestore(&clock->lock, flags);
763 /* ------------------------------------------------------------------------
764 * Stream statistics
767 static void uvc_video_stats_decode(struct uvc_streaming *stream,
768 const u8 *data, int len)
770 unsigned int header_size;
771 bool has_pts = false;
772 bool has_scr = false;
773 u16 uninitialized_var(scr_sof);
774 u32 uninitialized_var(scr_stc);
775 u32 uninitialized_var(pts);
777 if (stream->stats.stream.nb_frames == 0 &&
778 stream->stats.frame.nb_packets == 0)
779 stream->stats.stream.start_ts = ktime_get();
781 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
782 case UVC_STREAM_PTS | UVC_STREAM_SCR:
783 header_size = 12;
784 has_pts = true;
785 has_scr = true;
786 break;
787 case UVC_STREAM_PTS:
788 header_size = 6;
789 has_pts = true;
790 break;
791 case UVC_STREAM_SCR:
792 header_size = 8;
793 has_scr = true;
794 break;
795 default:
796 header_size = 2;
797 break;
800 /* Check for invalid headers. */
801 if (len < header_size || data[0] < header_size) {
802 stream->stats.frame.nb_invalid++;
803 return;
806 /* Extract the timestamps. */
807 if (has_pts)
808 pts = get_unaligned_le32(&data[2]);
810 if (has_scr) {
811 scr_stc = get_unaligned_le32(&data[header_size - 6]);
812 scr_sof = get_unaligned_le16(&data[header_size - 2]);
815 /* Is PTS constant through the whole frame ? */
816 if (has_pts && stream->stats.frame.nb_pts) {
817 if (stream->stats.frame.pts != pts) {
818 stream->stats.frame.nb_pts_diffs++;
819 stream->stats.frame.last_pts_diff =
820 stream->stats.frame.nb_packets;
824 if (has_pts) {
825 stream->stats.frame.nb_pts++;
826 stream->stats.frame.pts = pts;
829 /* Do all frames have a PTS in their first non-empty packet, or before
830 * their first empty packet ?
832 if (stream->stats.frame.size == 0) {
833 if (len > header_size)
834 stream->stats.frame.has_initial_pts = has_pts;
835 if (len == header_size && has_pts)
836 stream->stats.frame.has_early_pts = true;
839 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
840 if (has_scr && stream->stats.frame.nb_scr) {
841 if (stream->stats.frame.scr_stc != scr_stc)
842 stream->stats.frame.nb_scr_diffs++;
845 if (has_scr) {
846 /* Expand the SOF counter to 32 bits and store its value. */
847 if (stream->stats.stream.nb_frames > 0 ||
848 stream->stats.frame.nb_scr > 0)
849 stream->stats.stream.scr_sof_count +=
850 (scr_sof - stream->stats.stream.scr_sof) % 2048;
851 stream->stats.stream.scr_sof = scr_sof;
853 stream->stats.frame.nb_scr++;
854 stream->stats.frame.scr_stc = scr_stc;
855 stream->stats.frame.scr_sof = scr_sof;
857 if (scr_sof < stream->stats.stream.min_sof)
858 stream->stats.stream.min_sof = scr_sof;
859 if (scr_sof > stream->stats.stream.max_sof)
860 stream->stats.stream.max_sof = scr_sof;
863 /* Record the first non-empty packet number. */
864 if (stream->stats.frame.size == 0 && len > header_size)
865 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
867 /* Update the frame size. */
868 stream->stats.frame.size += len - header_size;
870 /* Update the packets counters. */
871 stream->stats.frame.nb_packets++;
872 if (len <= header_size)
873 stream->stats.frame.nb_empty++;
875 if (data[1] & UVC_STREAM_ERR)
876 stream->stats.frame.nb_errors++;
879 static void uvc_video_stats_update(struct uvc_streaming *stream)
881 struct uvc_stats_frame *frame = &stream->stats.frame;
883 uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
884 "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
885 "last pts/stc/sof %u/%u/%u\n",
886 stream->sequence, frame->first_data,
887 frame->nb_packets - frame->nb_empty, frame->nb_packets,
888 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
889 frame->has_early_pts ? "" : "!",
890 frame->has_initial_pts ? "" : "!",
891 frame->nb_scr_diffs, frame->nb_scr,
892 frame->pts, frame->scr_stc, frame->scr_sof);
894 stream->stats.stream.nb_frames++;
895 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
896 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
897 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
898 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
900 if (frame->has_early_pts)
901 stream->stats.stream.nb_pts_early++;
902 if (frame->has_initial_pts)
903 stream->stats.stream.nb_pts_initial++;
904 if (frame->last_pts_diff <= frame->first_data)
905 stream->stats.stream.nb_pts_constant++;
906 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
907 stream->stats.stream.nb_scr_count_ok++;
908 if (frame->nb_scr_diffs + 1 == frame->nb_scr)
909 stream->stats.stream.nb_scr_diffs_ok++;
911 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
914 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
915 size_t size)
917 unsigned int scr_sof_freq;
918 unsigned int duration;
919 size_t count = 0;
921 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
922 * frequency this will not overflow before more than 1h.
924 duration = ktime_ms_delta(stream->stats.stream.stop_ts,
925 stream->stats.stream.start_ts);
926 if (duration != 0)
927 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
928 / duration;
929 else
930 scr_sof_freq = 0;
932 count += scnprintf(buf + count, size - count,
933 "frames: %u\npackets: %u\nempty: %u\n"
934 "errors: %u\ninvalid: %u\n",
935 stream->stats.stream.nb_frames,
936 stream->stats.stream.nb_packets,
937 stream->stats.stream.nb_empty,
938 stream->stats.stream.nb_errors,
939 stream->stats.stream.nb_invalid);
940 count += scnprintf(buf + count, size - count,
941 "pts: %u early, %u initial, %u ok\n",
942 stream->stats.stream.nb_pts_early,
943 stream->stats.stream.nb_pts_initial,
944 stream->stats.stream.nb_pts_constant);
945 count += scnprintf(buf + count, size - count,
946 "scr: %u count ok, %u diff ok\n",
947 stream->stats.stream.nb_scr_count_ok,
948 stream->stats.stream.nb_scr_diffs_ok);
949 count += scnprintf(buf + count, size - count,
950 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
951 stream->stats.stream.min_sof,
952 stream->stats.stream.max_sof,
953 scr_sof_freq / 1000, scr_sof_freq % 1000);
955 return count;
958 static void uvc_video_stats_start(struct uvc_streaming *stream)
960 memset(&stream->stats, 0, sizeof(stream->stats));
961 stream->stats.stream.min_sof = 2048;
964 static void uvc_video_stats_stop(struct uvc_streaming *stream)
966 stream->stats.stream.stop_ts = ktime_get();
969 /* ------------------------------------------------------------------------
970 * Video codecs
973 /* Video payload decoding is handled by uvc_video_decode_start(),
974 * uvc_video_decode_data() and uvc_video_decode_end().
976 * uvc_video_decode_start is called with URB data at the start of a bulk or
977 * isochronous payload. It processes header data and returns the header size
978 * in bytes if successful. If an error occurs, it returns a negative error
979 * code. The following error codes have special meanings.
981 * - EAGAIN informs the caller that the current video buffer should be marked
982 * as done, and that the function should be called again with the same data
983 * and a new video buffer. This is used when end of frame conditions can be
984 * reliably detected at the beginning of the next frame only.
986 * If an error other than -EAGAIN is returned, the caller will drop the current
987 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
988 * made until the next payload. -ENODATA can be used to drop the current
989 * payload if no other error code is appropriate.
991 * uvc_video_decode_data is called for every URB with URB data. It copies the
992 * data to the video buffer.
994 * uvc_video_decode_end is called with header data at the end of a bulk or
995 * isochronous payload. It performs any additional header data processing and
996 * returns 0 or a negative error code if an error occurred. As header data have
997 * already been processed by uvc_video_decode_start, this functions isn't
998 * required to perform sanity checks a second time.
1000 * For isochronous transfers where a payload is always transferred in a single
1001 * URB, the three functions will be called in a row.
1003 * To let the decoder process header data and update its internal state even
1004 * when no video buffer is available, uvc_video_decode_start must be prepared
1005 * to be called with a NULL buf parameter. uvc_video_decode_data and
1006 * uvc_video_decode_end will never be called with a NULL buffer.
1008 static int uvc_video_decode_start(struct uvc_streaming *stream,
1009 struct uvc_buffer *buf, const u8 *data, int len)
1011 u8 fid;
1013 /* Sanity checks:
1014 * - packet must be at least 2 bytes long
1015 * - bHeaderLength value must be at least 2 bytes (see above)
1016 * - bHeaderLength value can't be larger than the packet size.
1018 if (len < 2 || data[0] < 2 || data[0] > len) {
1019 stream->stats.frame.nb_invalid++;
1020 return -EINVAL;
1023 fid = data[1] & UVC_STREAM_FID;
1025 /* Increase the sequence number regardless of any buffer states, so
1026 * that discontinuous sequence numbers always indicate lost frames.
1028 if (stream->last_fid != fid) {
1029 stream->sequence++;
1030 if (stream->sequence)
1031 uvc_video_stats_update(stream);
1034 uvc_video_clock_decode(stream, buf, data, len);
1035 uvc_video_stats_decode(stream, data, len);
1037 /* Store the payload FID bit and return immediately when the buffer is
1038 * NULL.
1040 if (buf == NULL) {
1041 stream->last_fid = fid;
1042 return -ENODATA;
1045 /* Mark the buffer as bad if the error bit is set. */
1046 if (data[1] & UVC_STREAM_ERR) {
1047 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1048 "set).\n");
1049 buf->error = 1;
1052 /* Synchronize to the input stream by waiting for the FID bit to be
1053 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1054 * stream->last_fid is initialized to -1, so the first isochronous
1055 * frame will always be in sync.
1057 * If the device doesn't toggle the FID bit, invert stream->last_fid
1058 * when the EOF bit is set to force synchronisation on the next packet.
1060 if (buf->state != UVC_BUF_STATE_ACTIVE) {
1061 if (fid == stream->last_fid) {
1062 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1063 "sync).\n");
1064 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1065 (data[1] & UVC_STREAM_EOF))
1066 stream->last_fid ^= UVC_STREAM_FID;
1067 return -ENODATA;
1070 buf->buf.field = V4L2_FIELD_NONE;
1071 buf->buf.sequence = stream->sequence;
1072 buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time());
1074 /* TODO: Handle PTS and SCR. */
1075 buf->state = UVC_BUF_STATE_ACTIVE;
1078 /* Mark the buffer as done if we're at the beginning of a new frame.
1079 * End of frame detection is better implemented by checking the EOF
1080 * bit (FID bit toggling is delayed by one frame compared to the EOF
1081 * bit), but some devices don't set the bit at end of frame (and the
1082 * last payload can be lost anyway). We thus must check if the FID has
1083 * been toggled.
1085 * stream->last_fid is initialized to -1, so the first isochronous
1086 * frame will never trigger an end of frame detection.
1088 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1089 * as it doesn't make sense to return an empty buffer. This also
1090 * avoids detecting end of frame conditions at FID toggling if the
1091 * previous payload had the EOF bit set.
1093 if (fid != stream->last_fid && buf->bytesused != 0) {
1094 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1095 "toggled).\n");
1096 buf->state = UVC_BUF_STATE_READY;
1097 return -EAGAIN;
1100 stream->last_fid = fid;
1102 return data[0];
1105 static void uvc_video_decode_data(struct uvc_streaming *stream,
1106 struct uvc_buffer *buf, const u8 *data, int len)
1108 unsigned int maxlen, nbytes;
1109 void *mem;
1111 if (len <= 0)
1112 return;
1114 /* Copy the video data to the buffer. */
1115 maxlen = buf->length - buf->bytesused;
1116 mem = buf->mem + buf->bytesused;
1117 nbytes = min((unsigned int)len, maxlen);
1118 memcpy(mem, data, nbytes);
1119 buf->bytesused += nbytes;
1121 /* Complete the current frame if the buffer size was exceeded. */
1122 if (len > maxlen) {
1123 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1124 buf->error = 1;
1125 buf->state = UVC_BUF_STATE_READY;
1129 static void uvc_video_decode_end(struct uvc_streaming *stream,
1130 struct uvc_buffer *buf, const u8 *data, int len)
1132 /* Mark the buffer as done if the EOF marker is set. */
1133 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1134 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1135 if (data[0] == len)
1136 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1137 buf->state = UVC_BUF_STATE_READY;
1138 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1139 stream->last_fid ^= UVC_STREAM_FID;
1143 /* Video payload encoding is handled by uvc_video_encode_header() and
1144 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1146 * uvc_video_encode_header is called at the start of a payload. It adds header
1147 * data to the transfer buffer and returns the header size. As the only known
1148 * UVC output device transfers a whole frame in a single payload, the EOF bit
1149 * is always set in the header.
1151 * uvc_video_encode_data is called for every URB and copies the data from the
1152 * video buffer to the transfer buffer.
1154 static int uvc_video_encode_header(struct uvc_streaming *stream,
1155 struct uvc_buffer *buf, u8 *data, int len)
1157 data[0] = 2; /* Header length */
1158 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1159 | (stream->last_fid & UVC_STREAM_FID);
1160 return 2;
1163 static int uvc_video_encode_data(struct uvc_streaming *stream,
1164 struct uvc_buffer *buf, u8 *data, int len)
1166 struct uvc_video_queue *queue = &stream->queue;
1167 unsigned int nbytes;
1168 void *mem;
1170 /* Copy video data to the URB buffer. */
1171 mem = buf->mem + queue->buf_used;
1172 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1173 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1174 nbytes);
1175 memcpy(data, mem, nbytes);
1177 queue->buf_used += nbytes;
1179 return nbytes;
1182 /* ------------------------------------------------------------------------
1183 * Metadata
1187 * Additionally to the payload headers we also want to provide the user with USB
1188 * Frame Numbers and system time values. The resulting buffer is thus composed
1189 * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame
1190 * Number, and a copy of the payload header.
1192 * Ideally we want to capture all payload headers for each frame. However, their
1193 * number is unknown and unbound. We thus drop headers that contain no vendor
1194 * data and that either contain no SCR value or an SCR value identical to the
1195 * previous header.
1197 static void uvc_video_decode_meta(struct uvc_streaming *stream,
1198 struct uvc_buffer *meta_buf,
1199 const u8 *mem, unsigned int length)
1201 struct uvc_meta_buf *meta;
1202 size_t len_std = 2;
1203 bool has_pts, has_scr;
1204 unsigned long flags;
1205 unsigned int sof;
1206 ktime_t time;
1207 const u8 *scr;
1209 if (!meta_buf || length == 2)
1210 return;
1212 if (meta_buf->length - meta_buf->bytesused <
1213 length + sizeof(meta->ns) + sizeof(meta->sof)) {
1214 meta_buf->error = 1;
1215 return;
1218 has_pts = mem[1] & UVC_STREAM_PTS;
1219 has_scr = mem[1] & UVC_STREAM_SCR;
1221 if (has_pts) {
1222 len_std += 4;
1223 scr = mem + 6;
1224 } else {
1225 scr = mem + 2;
1228 if (has_scr)
1229 len_std += 6;
1231 if (stream->meta.format == V4L2_META_FMT_UVC)
1232 length = len_std;
1234 if (length == len_std && (!has_scr ||
1235 !memcmp(scr, stream->clock.last_scr, 6)))
1236 return;
1238 meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
1239 local_irq_save(flags);
1240 time = uvc_video_get_time();
1241 sof = usb_get_current_frame_number(stream->dev->udev);
1242 local_irq_restore(flags);
1243 put_unaligned(ktime_to_ns(time), &meta->ns);
1244 put_unaligned(sof, &meta->sof);
1246 if (has_scr)
1247 memcpy(stream->clock.last_scr, scr, 6);
1249 memcpy(&meta->length, mem, length);
1250 meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);
1252 uvc_trace(UVC_TRACE_FRAME,
1253 "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
1254 __func__, ktime_to_ns(time), meta->sof, meta->length,
1255 meta->flags,
1256 has_pts ? *(u32 *)meta->buf : 0,
1257 has_scr ? *(u32 *)scr : 0,
1258 has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
1261 /* ------------------------------------------------------------------------
1262 * URB handling
1266 * Set error flag for incomplete buffer.
1268 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1269 struct uvc_buffer *buf)
1271 if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1272 !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1273 buf->error = 1;
1277 * Completion handler for video URBs.
1280 static void uvc_video_next_buffers(struct uvc_streaming *stream,
1281 struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
1283 uvc_video_validate_buffer(stream, *video_buf);
1285 if (*meta_buf) {
1286 struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
1287 const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;
1289 vb2_meta->sequence = vb2_video->sequence;
1290 vb2_meta->field = vb2_video->field;
1291 vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;
1293 (*meta_buf)->state = UVC_BUF_STATE_READY;
1294 if (!(*meta_buf)->error)
1295 (*meta_buf)->error = (*video_buf)->error;
1296 *meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
1297 *meta_buf);
1299 *video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
1302 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1303 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1305 u8 *mem;
1306 int ret, i;
1308 for (i = 0; i < urb->number_of_packets; ++i) {
1309 if (urb->iso_frame_desc[i].status < 0) {
1310 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1311 "lost (%d).\n", urb->iso_frame_desc[i].status);
1312 /* Mark the buffer as faulty. */
1313 if (buf != NULL)
1314 buf->error = 1;
1315 continue;
1318 /* Decode the payload header. */
1319 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1320 do {
1321 ret = uvc_video_decode_start(stream, buf, mem,
1322 urb->iso_frame_desc[i].actual_length);
1323 if (ret == -EAGAIN)
1324 uvc_video_next_buffers(stream, &buf, &meta_buf);
1325 } while (ret == -EAGAIN);
1327 if (ret < 0)
1328 continue;
1330 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1332 /* Decode the payload data. */
1333 uvc_video_decode_data(stream, buf, mem + ret,
1334 urb->iso_frame_desc[i].actual_length - ret);
1336 /* Process the header again. */
1337 uvc_video_decode_end(stream, buf, mem,
1338 urb->iso_frame_desc[i].actual_length);
1340 if (buf->state == UVC_BUF_STATE_READY)
1341 uvc_video_next_buffers(stream, &buf, &meta_buf);
1345 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1346 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1348 u8 *mem;
1349 int len, ret;
1352 * Ignore ZLPs if they're not part of a frame, otherwise process them
1353 * to trigger the end of payload detection.
1355 if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1356 return;
1358 mem = urb->transfer_buffer;
1359 len = urb->actual_length;
1360 stream->bulk.payload_size += len;
1362 /* If the URB is the first of its payload, decode and save the
1363 * header.
1365 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1366 do {
1367 ret = uvc_video_decode_start(stream, buf, mem, len);
1368 if (ret == -EAGAIN)
1369 uvc_video_next_buffers(stream, &buf, &meta_buf);
1370 } while (ret == -EAGAIN);
1372 /* If an error occurred skip the rest of the payload. */
1373 if (ret < 0 || buf == NULL) {
1374 stream->bulk.skip_payload = 1;
1375 } else {
1376 memcpy(stream->bulk.header, mem, ret);
1377 stream->bulk.header_size = ret;
1379 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1381 mem += ret;
1382 len -= ret;
1386 /* The buffer queue might have been cancelled while a bulk transfer
1387 * was in progress, so we can reach here with buf equal to NULL. Make
1388 * sure buf is never dereferenced if NULL.
1391 /* Process video data. */
1392 if (!stream->bulk.skip_payload && buf != NULL)
1393 uvc_video_decode_data(stream, buf, mem, len);
1395 /* Detect the payload end by a URB smaller than the maximum size (or
1396 * a payload size equal to the maximum) and process the header again.
1398 if (urb->actual_length < urb->transfer_buffer_length ||
1399 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1400 if (!stream->bulk.skip_payload && buf != NULL) {
1401 uvc_video_decode_end(stream, buf, stream->bulk.header,
1402 stream->bulk.payload_size);
1403 if (buf->state == UVC_BUF_STATE_READY)
1404 uvc_video_next_buffers(stream, &buf, &meta_buf);
1407 stream->bulk.header_size = 0;
1408 stream->bulk.skip_payload = 0;
1409 stream->bulk.payload_size = 0;
1413 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1414 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1416 u8 *mem = urb->transfer_buffer;
1417 int len = stream->urb_size, ret;
1419 if (buf == NULL) {
1420 urb->transfer_buffer_length = 0;
1421 return;
1424 /* If the URB is the first of its payload, add the header. */
1425 if (stream->bulk.header_size == 0) {
1426 ret = uvc_video_encode_header(stream, buf, mem, len);
1427 stream->bulk.header_size = ret;
1428 stream->bulk.payload_size += ret;
1429 mem += ret;
1430 len -= ret;
1433 /* Process video data. */
1434 ret = uvc_video_encode_data(stream, buf, mem, len);
1436 stream->bulk.payload_size += ret;
1437 len -= ret;
1439 if (buf->bytesused == stream->queue.buf_used ||
1440 stream->bulk.payload_size == stream->bulk.max_payload_size) {
1441 if (buf->bytesused == stream->queue.buf_used) {
1442 stream->queue.buf_used = 0;
1443 buf->state = UVC_BUF_STATE_READY;
1444 buf->buf.sequence = ++stream->sequence;
1445 uvc_queue_next_buffer(&stream->queue, buf);
1446 stream->last_fid ^= UVC_STREAM_FID;
1449 stream->bulk.header_size = 0;
1450 stream->bulk.payload_size = 0;
1453 urb->transfer_buffer_length = stream->urb_size - len;
1456 static void uvc_video_complete(struct urb *urb)
1458 struct uvc_streaming *stream = urb->context;
1459 struct uvc_video_queue *queue = &stream->queue;
1460 struct uvc_video_queue *qmeta = &stream->meta.queue;
1461 struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
1462 struct uvc_buffer *buf = NULL;
1463 struct uvc_buffer *buf_meta = NULL;
1464 unsigned long flags;
1465 int ret;
1467 switch (urb->status) {
1468 case 0:
1469 break;
1471 default:
1472 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1473 "completion handler.\n", urb->status);
1474 /* fall through */
1475 case -ENOENT: /* usb_kill_urb() called. */
1476 if (stream->frozen)
1477 return;
1478 /* fall through */
1479 case -ECONNRESET: /* usb_unlink_urb() called. */
1480 case -ESHUTDOWN: /* The endpoint is being disabled. */
1481 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1482 if (vb2_qmeta)
1483 uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
1484 return;
1487 spin_lock_irqsave(&queue->irqlock, flags);
1488 if (!list_empty(&queue->irqqueue))
1489 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
1490 queue);
1491 spin_unlock_irqrestore(&queue->irqlock, flags);
1493 if (vb2_qmeta) {
1494 spin_lock_irqsave(&qmeta->irqlock, flags);
1495 if (!list_empty(&qmeta->irqqueue))
1496 buf_meta = list_first_entry(&qmeta->irqqueue,
1497 struct uvc_buffer, queue);
1498 spin_unlock_irqrestore(&qmeta->irqlock, flags);
1501 stream->decode(urb, stream, buf, buf_meta);
1503 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
1504 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1505 ret);
1510 * Free transfer buffers.
1512 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1514 unsigned int i;
1516 for (i = 0; i < UVC_URBS; ++i) {
1517 if (stream->urb_buffer[i]) {
1518 #ifndef CONFIG_DMA_NONCOHERENT
1519 usb_free_coherent(stream->dev->udev, stream->urb_size,
1520 stream->urb_buffer[i], stream->urb_dma[i]);
1521 #else
1522 kfree(stream->urb_buffer[i]);
1523 #endif
1524 stream->urb_buffer[i] = NULL;
1528 stream->urb_size = 0;
1532 * Allocate transfer buffers. This function can be called with buffers
1533 * already allocated when resuming from suspend, in which case it will
1534 * return without touching the buffers.
1536 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1537 * system is too low on memory try successively smaller numbers of packets
1538 * until allocation succeeds.
1540 * Return the number of allocated packets on success or 0 when out of memory.
1542 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1543 unsigned int size, unsigned int psize, gfp_t gfp_flags)
1545 unsigned int npackets;
1546 unsigned int i;
1548 /* Buffers are already allocated, bail out. */
1549 if (stream->urb_size)
1550 return stream->urb_size / psize;
1552 /* Compute the number of packets. Bulk endpoints might transfer UVC
1553 * payloads across multiple URBs.
1555 npackets = DIV_ROUND_UP(size, psize);
1556 if (npackets > UVC_MAX_PACKETS)
1557 npackets = UVC_MAX_PACKETS;
1559 /* Retry allocations until one succeed. */
1560 for (; npackets > 1; npackets /= 2) {
1561 for (i = 0; i < UVC_URBS; ++i) {
1562 stream->urb_size = psize * npackets;
1563 #ifndef CONFIG_DMA_NONCOHERENT
1564 stream->urb_buffer[i] = usb_alloc_coherent(
1565 stream->dev->udev, stream->urb_size,
1566 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1567 #else
1568 stream->urb_buffer[i] =
1569 kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1570 #endif
1571 if (!stream->urb_buffer[i]) {
1572 uvc_free_urb_buffers(stream);
1573 break;
1577 if (i == UVC_URBS) {
1578 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1579 "of %ux%u bytes each.\n", UVC_URBS, npackets,
1580 psize);
1581 return npackets;
1585 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1586 "per packet).\n", psize);
1587 return 0;
1591 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1593 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1595 struct urb *urb;
1596 unsigned int i;
1598 uvc_video_stats_stop(stream);
1600 for (i = 0; i < UVC_URBS; ++i) {
1601 urb = stream->urb[i];
1602 if (urb == NULL)
1603 continue;
1605 usb_kill_urb(urb);
1606 usb_free_urb(urb);
1607 stream->urb[i] = NULL;
1610 if (free_buffers)
1611 uvc_free_urb_buffers(stream);
1615 * Compute the maximum number of bytes per interval for an endpoint.
1617 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1618 struct usb_host_endpoint *ep)
1620 u16 psize;
1621 u16 mult;
1623 switch (dev->speed) {
1624 case USB_SPEED_SUPER:
1625 case USB_SPEED_SUPER_PLUS:
1626 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1627 case USB_SPEED_HIGH:
1628 psize = usb_endpoint_maxp(&ep->desc);
1629 mult = usb_endpoint_maxp_mult(&ep->desc);
1630 return psize * mult;
1631 case USB_SPEED_WIRELESS:
1632 psize = usb_endpoint_maxp(&ep->desc);
1633 return psize;
1634 default:
1635 psize = usb_endpoint_maxp(&ep->desc);
1636 return psize;
1641 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1642 * is given by the endpoint.
1644 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1645 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1647 struct urb *urb;
1648 unsigned int npackets, i, j;
1649 u16 psize;
1650 u32 size;
1652 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1653 size = stream->ctrl.dwMaxVideoFrameSize;
1655 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1656 if (npackets == 0)
1657 return -ENOMEM;
1659 size = npackets * psize;
1661 for (i = 0; i < UVC_URBS; ++i) {
1662 urb = usb_alloc_urb(npackets, gfp_flags);
1663 if (urb == NULL) {
1664 uvc_uninit_video(stream, 1);
1665 return -ENOMEM;
1668 urb->dev = stream->dev->udev;
1669 urb->context = stream;
1670 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1671 ep->desc.bEndpointAddress);
1672 #ifndef CONFIG_DMA_NONCOHERENT
1673 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1674 urb->transfer_dma = stream->urb_dma[i];
1675 #else
1676 urb->transfer_flags = URB_ISO_ASAP;
1677 #endif
1678 urb->interval = ep->desc.bInterval;
1679 urb->transfer_buffer = stream->urb_buffer[i];
1680 urb->complete = uvc_video_complete;
1681 urb->number_of_packets = npackets;
1682 urb->transfer_buffer_length = size;
1684 for (j = 0; j < npackets; ++j) {
1685 urb->iso_frame_desc[j].offset = j * psize;
1686 urb->iso_frame_desc[j].length = psize;
1689 stream->urb[i] = urb;
1692 return 0;
1696 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1697 * given by the endpoint.
1699 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1700 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1702 struct urb *urb;
1703 unsigned int npackets, pipe, i;
1704 u16 psize;
1705 u32 size;
1707 psize = usb_endpoint_maxp(&ep->desc);
1708 size = stream->ctrl.dwMaxPayloadTransferSize;
1709 stream->bulk.max_payload_size = size;
1711 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1712 if (npackets == 0)
1713 return -ENOMEM;
1715 size = npackets * psize;
1717 if (usb_endpoint_dir_in(&ep->desc))
1718 pipe = usb_rcvbulkpipe(stream->dev->udev,
1719 ep->desc.bEndpointAddress);
1720 else
1721 pipe = usb_sndbulkpipe(stream->dev->udev,
1722 ep->desc.bEndpointAddress);
1724 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1725 size = 0;
1727 for (i = 0; i < UVC_URBS; ++i) {
1728 urb = usb_alloc_urb(0, gfp_flags);
1729 if (urb == NULL) {
1730 uvc_uninit_video(stream, 1);
1731 return -ENOMEM;
1734 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1735 stream->urb_buffer[i], size, uvc_video_complete,
1736 stream);
1737 #ifndef CONFIG_DMA_NONCOHERENT
1738 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1739 urb->transfer_dma = stream->urb_dma[i];
1740 #endif
1742 stream->urb[i] = urb;
1745 return 0;
1749 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1751 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1753 struct usb_interface *intf = stream->intf;
1754 struct usb_host_endpoint *ep;
1755 unsigned int i;
1756 int ret;
1758 stream->sequence = -1;
1759 stream->last_fid = -1;
1760 stream->bulk.header_size = 0;
1761 stream->bulk.skip_payload = 0;
1762 stream->bulk.payload_size = 0;
1764 uvc_video_stats_start(stream);
1766 if (intf->num_altsetting > 1) {
1767 struct usb_host_endpoint *best_ep = NULL;
1768 unsigned int best_psize = UINT_MAX;
1769 unsigned int bandwidth;
1770 unsigned int uninitialized_var(altsetting);
1771 int intfnum = stream->intfnum;
1773 /* Isochronous endpoint, select the alternate setting. */
1774 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1776 if (bandwidth == 0) {
1777 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1778 "bandwidth, defaulting to lowest.\n");
1779 bandwidth = 1;
1780 } else {
1781 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1782 "B/frame bandwidth.\n", bandwidth);
1785 for (i = 0; i < intf->num_altsetting; ++i) {
1786 struct usb_host_interface *alts;
1787 unsigned int psize;
1789 alts = &intf->altsetting[i];
1790 ep = uvc_find_endpoint(alts,
1791 stream->header.bEndpointAddress);
1792 if (ep == NULL)
1793 continue;
1795 /* Check if the bandwidth is high enough. */
1796 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1797 if (psize >= bandwidth && psize <= best_psize) {
1798 altsetting = alts->desc.bAlternateSetting;
1799 best_psize = psize;
1800 best_ep = ep;
1804 if (best_ep == NULL) {
1805 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1806 "for requested bandwidth.\n");
1807 return -EIO;
1810 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1811 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1813 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1814 if (ret < 0)
1815 return ret;
1817 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1818 } else {
1819 /* Bulk endpoint, proceed to URB initialization. */
1820 ep = uvc_find_endpoint(&intf->altsetting[0],
1821 stream->header.bEndpointAddress);
1822 if (ep == NULL)
1823 return -EIO;
1825 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1828 if (ret < 0)
1829 return ret;
1831 /* Submit the URBs. */
1832 for (i = 0; i < UVC_URBS; ++i) {
1833 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1834 if (ret < 0) {
1835 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1836 "(%d).\n", i, ret);
1837 uvc_uninit_video(stream, 1);
1838 return ret;
1842 /* The Logitech C920 temporarily forgets that it should not be adjusting
1843 * Exposure Absolute during init so restore controls to stored values.
1845 if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1846 uvc_ctrl_restore_values(stream->dev);
1848 return 0;
1851 /* --------------------------------------------------------------------------
1852 * Suspend/resume
1856 * Stop streaming without disabling the video queue.
1858 * To let userspace applications resume without trouble, we must not touch the
1859 * video buffers in any way. We mark the device as frozen to make sure the URB
1860 * completion handler won't try to cancel the queue when we kill the URBs.
1862 int uvc_video_suspend(struct uvc_streaming *stream)
1864 if (!uvc_queue_streaming(&stream->queue))
1865 return 0;
1867 stream->frozen = 1;
1868 uvc_uninit_video(stream, 0);
1869 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1870 return 0;
1874 * Reconfigure the video interface and restart streaming if it was enabled
1875 * before suspend.
1877 * If an error occurs, disable the video queue. This will wake all pending
1878 * buffers, making sure userspace applications are notified of the problem
1879 * instead of waiting forever.
1881 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1883 int ret;
1885 /* If the bus has been reset on resume, set the alternate setting to 0.
1886 * This should be the default value, but some devices crash or otherwise
1887 * misbehave if they don't receive a SET_INTERFACE request before any
1888 * other video control request.
1890 if (reset)
1891 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1893 stream->frozen = 0;
1895 uvc_video_clock_reset(stream);
1897 if (!uvc_queue_streaming(&stream->queue))
1898 return 0;
1900 ret = uvc_commit_video(stream, &stream->ctrl);
1901 if (ret < 0)
1902 return ret;
1904 return uvc_init_video(stream, GFP_NOIO);
1907 /* ------------------------------------------------------------------------
1908 * Video device
1912 * Initialize the UVC video device by switching to alternate setting 0 and
1913 * retrieve the default format.
1915 * Some cameras (namely the Fuji Finepix) set the format and frame
1916 * indexes to zero. The UVC standard doesn't clearly make this a spec
1917 * violation, so try to silently fix the values if possible.
1919 * This function is called before registering the device with V4L.
1921 int uvc_video_init(struct uvc_streaming *stream)
1923 struct uvc_streaming_control *probe = &stream->ctrl;
1924 struct uvc_format *format = NULL;
1925 struct uvc_frame *frame = NULL;
1926 unsigned int i;
1927 int ret;
1929 if (stream->nformats == 0) {
1930 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1931 return -EINVAL;
1934 atomic_set(&stream->active, 0);
1936 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1937 * Cam (and possibly other devices) crash or otherwise misbehave if
1938 * they don't receive a SET_INTERFACE request before any other video
1939 * control request.
1941 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1943 /* Set the streaming probe control with default streaming parameters
1944 * retrieved from the device. Webcams that don't suport GET_DEF
1945 * requests on the probe control will just keep their current streaming
1946 * parameters.
1948 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1949 uvc_set_video_ctrl(stream, probe, 1);
1951 /* Initialize the streaming parameters with the probe control current
1952 * value. This makes sure SET_CUR requests on the streaming commit
1953 * control will always use values retrieved from a successful GET_CUR
1954 * request on the probe control, as required by the UVC specification.
1956 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1957 if (ret < 0)
1958 return ret;
1960 /* Check if the default format descriptor exists. Use the first
1961 * available format otherwise.
1963 for (i = stream->nformats; i > 0; --i) {
1964 format = &stream->format[i-1];
1965 if (format->index == probe->bFormatIndex)
1966 break;
1969 if (format->nframes == 0) {
1970 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1971 "default format.\n");
1972 return -EINVAL;
1975 /* Zero bFrameIndex might be correct. Stream-based formats (including
1976 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1977 * descriptor with bFrameIndex set to zero. If the default frame
1978 * descriptor is not found, use the first available frame.
1980 for (i = format->nframes; i > 0; --i) {
1981 frame = &format->frame[i-1];
1982 if (frame->bFrameIndex == probe->bFrameIndex)
1983 break;
1986 probe->bFormatIndex = format->index;
1987 probe->bFrameIndex = frame->bFrameIndex;
1989 stream->def_format = format;
1990 stream->cur_format = format;
1991 stream->cur_frame = frame;
1993 /* Select the video decoding function */
1994 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1995 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1996 stream->decode = uvc_video_decode_isight;
1997 else if (stream->intf->num_altsetting > 1)
1998 stream->decode = uvc_video_decode_isoc;
1999 else
2000 stream->decode = uvc_video_decode_bulk;
2001 } else {
2002 if (stream->intf->num_altsetting == 1)
2003 stream->decode = uvc_video_encode_bulk;
2004 else {
2005 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
2006 "supported for video output devices.\n");
2007 return -EINVAL;
2011 return 0;
2015 * Enable or disable the video stream.
2017 int uvc_video_enable(struct uvc_streaming *stream, int enable)
2019 int ret;
2021 if (!enable) {
2022 uvc_uninit_video(stream, 1);
2023 if (stream->intf->num_altsetting > 1) {
2024 usb_set_interface(stream->dev->udev,
2025 stream->intfnum, 0);
2026 } else {
2027 /* UVC doesn't specify how to inform a bulk-based device
2028 * when the video stream is stopped. Windows sends a
2029 * CLEAR_FEATURE(HALT) request to the video streaming
2030 * bulk endpoint, mimic the same behaviour.
2032 unsigned int epnum = stream->header.bEndpointAddress
2033 & USB_ENDPOINT_NUMBER_MASK;
2034 unsigned int dir = stream->header.bEndpointAddress
2035 & USB_ENDPOINT_DIR_MASK;
2036 unsigned int pipe;
2038 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
2039 usb_clear_halt(stream->dev->udev, pipe);
2042 uvc_video_clock_cleanup(stream);
2043 return 0;
2046 ret = uvc_video_clock_init(stream);
2047 if (ret < 0)
2048 return ret;
2050 /* Commit the streaming parameters. */
2051 ret = uvc_commit_video(stream, &stream->ctrl);
2052 if (ret < 0)
2053 goto error_commit;
2055 ret = uvc_init_video(stream, GFP_KERNEL);
2056 if (ret < 0)
2057 goto error_video;
2059 return 0;
2061 error_video:
2062 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2063 error_commit:
2064 uvc_video_clock_cleanup(stream);
2066 return ret;