1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * uvc_video.c -- USB Video Class driver - Video handling
5 * Copyright (C) 2005-2010
6 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
9 #include <linux/dma-mapping.h>
10 #include <linux/highmem.h>
11 #include <linux/kernel.h>
12 #include <linux/list.h>
13 #include <linux/module.h>
14 #include <linux/slab.h>
15 #include <linux/usb.h>
16 #include <linux/usb/hcd.h>
17 #include <linux/videodev2.h>
18 #include <linux/vmalloc.h>
19 #include <linux/wait.h>
20 #include <linux/atomic.h>
21 #include <asm/unaligned.h>
23 #include <media/v4l2-common.h>
27 /* ------------------------------------------------------------------------
31 static int __uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
32 u8 intfnum, u8 cs, void *data, u16 size,
35 u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
38 pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
39 : usb_sndctrlpipe(dev->udev, 0);
40 type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
42 return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
43 unit << 8 | intfnum, data, size, timeout);
46 static const char *uvc_query_name(u8 query)
70 int uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
71 u8 intfnum, u8 cs, void *data, u16 size)
77 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
78 UVC_CTRL_CONTROL_TIMEOUT);
79 if (likely(ret == size))
82 dev_err(&dev->udev->dev,
83 "Failed to query (%s) UVC control %u on unit %u: %d (exp. %u).\n",
84 uvc_query_name(query), cs, unit, ret, size);
91 ret = __uvc_query_ctrl(dev, UVC_GET_CUR, 0, intfnum,
92 UVC_VC_REQUEST_ERROR_CODE_CONTROL, data, 1,
93 UVC_CTRL_CONTROL_TIMEOUT);
99 return ret < 0 ? ret : -EPIPE;
101 uvc_dbg(dev, CONTROL, "Control error %u\n", error);
105 /* Cannot happen - we received a STALL */
107 case 1: /* Not ready */
109 case 2: /* Wrong state */
113 case 4: /* Out of range */
115 case 5: /* Invalid unit */
116 case 6: /* Invalid control */
117 case 7: /* Invalid Request */
118 case 8: /* Invalid value within range */
120 default: /* reserved or unknown */
127 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
128 struct uvc_streaming_control *ctrl)
130 static const struct usb_device_id elgato_cam_link_4k = {
131 USB_DEVICE(0x0fd9, 0x0066)
133 struct uvc_format *format = NULL;
134 struct uvc_frame *frame = NULL;
138 * The response of the Elgato Cam Link 4K is incorrect: The second byte
139 * contains bFormatIndex (instead of being the second byte of bmHint).
140 * The first byte is always zero. The third byte is always 1.
142 * The UVC 1.5 class specification defines the first five bits in the
143 * bmHint bitfield. The remaining bits are reserved and should be zero.
144 * Therefore a valid bmHint will be less than 32.
146 * Latest Elgato Cam Link 4K firmware as of 2021-03-23 needs this fix.
147 * MCU: 20.02.19, FPGA: 67
149 if (usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k) &&
150 ctrl->bmHint > 255) {
151 u8 corrected_format_index = ctrl->bmHint >> 8;
153 uvc_dbg(stream->dev, VIDEO,
154 "Correct USB video probe response from {bmHint: 0x%04x, bFormatIndex: %u} to {bmHint: 0x%04x, bFormatIndex: %u}\n",
155 ctrl->bmHint, ctrl->bFormatIndex,
156 1, corrected_format_index);
158 ctrl->bFormatIndex = corrected_format_index;
161 for (i = 0; i < stream->nformats; ++i) {
162 if (stream->format[i].index == ctrl->bFormatIndex) {
163 format = &stream->format[i];
171 for (i = 0; i < format->nframes; ++i) {
172 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
173 frame = &format->frame[i];
181 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
182 (ctrl->dwMaxVideoFrameSize == 0 &&
183 stream->dev->uvc_version < 0x0110))
184 ctrl->dwMaxVideoFrameSize =
185 frame->dwMaxVideoFrameBufferSize;
187 /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
188 * compute the bandwidth on 16 bits and erroneously sign-extend it to
189 * 32 bits, resulting in a huge bandwidth value. Detect and fix that
190 * condition by setting the 16 MSBs to 0 when they're all equal to 1.
192 if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
193 ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
195 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
196 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
197 stream->intf->num_altsetting > 1) {
201 interval = (ctrl->dwFrameInterval > 100000)
202 ? ctrl->dwFrameInterval
203 : frame->dwFrameInterval[0];
205 /* Compute a bandwidth estimation by multiplying the frame
206 * size by the number of video frames per second, divide the
207 * result by the number of USB frames (or micro-frames for
208 * high-speed devices) per second and add the UVC header size
209 * (assumed to be 12 bytes long).
211 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
212 bandwidth *= 10000000 / interval + 1;
214 if (stream->dev->udev->speed == USB_SPEED_HIGH)
218 /* The bandwidth estimate is too low for many cameras. Don't use
219 * maximum packet sizes lower than 1024 bytes to try and work
220 * around the problem. According to measurements done on two
221 * different camera models, the value is high enough to get most
222 * resolutions working while not preventing two simultaneous
223 * VGA streams at 15 fps.
225 bandwidth = max_t(u32, bandwidth, 1024);
227 ctrl->dwMaxPayloadTransferSize = bandwidth;
231 static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
234 * Return the size of the video probe and commit controls, which depends
235 * on the protocol version.
237 if (stream->dev->uvc_version < 0x0110)
239 else if (stream->dev->uvc_version < 0x0150)
245 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
246 struct uvc_streaming_control *ctrl, int probe, u8 query)
248 u16 size = uvc_video_ctrl_size(stream);
252 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
253 query == UVC_GET_DEF)
256 data = kmalloc(size, GFP_KERNEL);
260 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
261 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
262 size, uvc_timeout_param);
264 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
265 /* Some cameras, mostly based on Bison Electronics chipsets,
266 * answer a GET_MIN or GET_MAX request with the wCompQuality
269 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
270 "compliance - GET_MIN/MAX(PROBE) incorrectly "
271 "supported. Enabling workaround.\n");
272 memset(ctrl, 0, sizeof(*ctrl));
273 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
276 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
277 /* Many cameras don't support the GET_DEF request on their
278 * video probe control. Warn once and return, the caller will
279 * fall back to GET_CUR.
281 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
282 "compliance - GET_DEF(PROBE) not supported. "
283 "Enabling workaround.\n");
286 } else if (ret != size) {
287 dev_err(&stream->intf->dev,
288 "Failed to query (%u) UVC %s control : %d (exp. %u).\n",
289 query, probe ? "probe" : "commit", ret, size);
294 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
295 ctrl->bFormatIndex = data[2];
296 ctrl->bFrameIndex = data[3];
297 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
298 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
299 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
300 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
301 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
302 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
303 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
304 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
307 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
308 ctrl->bmFramingInfo = data[30];
309 ctrl->bPreferedVersion = data[31];
310 ctrl->bMinVersion = data[32];
311 ctrl->bMaxVersion = data[33];
313 ctrl->dwClockFrequency = stream->dev->clock_frequency;
314 ctrl->bmFramingInfo = 0;
315 ctrl->bPreferedVersion = 0;
316 ctrl->bMinVersion = 0;
317 ctrl->bMaxVersion = 0;
320 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
321 * dwMaxPayloadTransferSize fields. Try to get the value from the
322 * format and frame descriptors.
324 uvc_fixup_video_ctrl(stream, ctrl);
332 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
333 struct uvc_streaming_control *ctrl, int probe)
335 u16 size = uvc_video_ctrl_size(stream);
339 data = kzalloc(size, GFP_KERNEL);
343 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
344 data[2] = ctrl->bFormatIndex;
345 data[3] = ctrl->bFrameIndex;
346 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
347 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
348 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
349 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
350 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
351 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
352 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
353 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
356 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
357 data[30] = ctrl->bmFramingInfo;
358 data[31] = ctrl->bPreferedVersion;
359 data[32] = ctrl->bMinVersion;
360 data[33] = ctrl->bMaxVersion;
363 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
364 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
365 size, uvc_timeout_param);
367 dev_err(&stream->intf->dev,
368 "Failed to set UVC %s control : %d (exp. %u).\n",
369 probe ? "probe" : "commit", ret, size);
377 int uvc_probe_video(struct uvc_streaming *stream,
378 struct uvc_streaming_control *probe)
380 struct uvc_streaming_control probe_min, probe_max;
385 /* Perform probing. The device should adjust the requested values
386 * according to its capabilities. However, some devices, namely the
387 * first generation UVC Logitech webcams, don't implement the Video
388 * Probe control properly, and just return the needed bandwidth. For
389 * that reason, if the needed bandwidth exceeds the maximum available
390 * bandwidth, try to lower the quality.
392 ret = uvc_set_video_ctrl(stream, probe, 1);
396 /* Get the minimum and maximum values for compression settings. */
397 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
398 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
401 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
405 probe->wCompQuality = probe_max.wCompQuality;
408 for (i = 0; i < 2; ++i) {
409 ret = uvc_set_video_ctrl(stream, probe, 1);
412 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
416 if (stream->intf->num_altsetting == 1)
419 bandwidth = probe->dwMaxPayloadTransferSize;
420 if (bandwidth <= stream->maxpsize)
423 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
428 /* TODO: negotiate compression parameters */
429 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
430 probe->wPFrameRate = probe_min.wPFrameRate;
431 probe->wCompQuality = probe_max.wCompQuality;
432 probe->wCompWindowSize = probe_min.wCompWindowSize;
439 static int uvc_commit_video(struct uvc_streaming *stream,
440 struct uvc_streaming_control *probe)
442 return uvc_set_video_ctrl(stream, probe, 0);
445 /* -----------------------------------------------------------------------------
446 * Clocks and timestamps
449 static inline ktime_t uvc_video_get_time(void)
451 if (uvc_clock_param == CLOCK_MONOTONIC)
454 return ktime_get_real();
458 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
459 const u8 *data, int len)
461 struct uvc_clock_sample *sample;
462 unsigned int header_size;
463 bool has_pts = false;
464 bool has_scr = false;
470 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
471 case UVC_STREAM_PTS | UVC_STREAM_SCR:
489 /* Check for invalid headers. */
490 if (len < header_size)
493 /* Extract the timestamps:
495 * - store the frame PTS in the buffer structure
496 * - if the SCR field is present, retrieve the host SOF counter and
497 * kernel timestamps and store them with the SCR STC and SOF fields
500 if (has_pts && buf != NULL)
501 buf->pts = get_unaligned_le32(&data[2]);
506 /* To limit the amount of data, drop SCRs with an SOF identical to the
509 dev_sof = get_unaligned_le16(&data[header_size - 2]);
510 if (dev_sof == stream->clock.last_sof)
513 stream->clock.last_sof = dev_sof;
515 host_sof = usb_get_current_frame_number(stream->dev->udev);
516 time = uvc_video_get_time();
518 /* The UVC specification allows device implementations that can't obtain
519 * the USB frame number to keep their own frame counters as long as they
520 * match the size and frequency of the frame number associated with USB
521 * SOF tokens. The SOF values sent by such devices differ from the USB
522 * SOF tokens by a fixed offset that needs to be estimated and accounted
523 * for to make timestamp recovery as accurate as possible.
525 * The offset is estimated the first time a device SOF value is received
526 * as the difference between the host and device SOF values. As the two
527 * SOF values can differ slightly due to transmission delays, consider
528 * that the offset is null if the difference is not higher than 10 ms
529 * (negative differences can not happen and are thus considered as an
530 * offset). The video commit control wDelay field should be used to
531 * compute a dynamic threshold instead of using a fixed 10 ms value, but
532 * devices don't report reliable wDelay values.
534 * See uvc_video_clock_host_sof() for an explanation regarding why only
535 * the 8 LSBs of the delta are kept.
537 if (stream->clock.sof_offset == (u16)-1) {
538 u16 delta_sof = (host_sof - dev_sof) & 255;
540 stream->clock.sof_offset = delta_sof;
542 stream->clock.sof_offset = 0;
545 dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
547 spin_lock_irqsave(&stream->clock.lock, flags);
549 sample = &stream->clock.samples[stream->clock.head];
550 sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
551 sample->dev_sof = dev_sof;
552 sample->host_sof = host_sof;
553 sample->host_time = time;
555 /* Update the sliding window head and count. */
556 stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
558 if (stream->clock.count < stream->clock.size)
559 stream->clock.count++;
561 spin_unlock_irqrestore(&stream->clock.lock, flags);
564 static void uvc_video_clock_reset(struct uvc_streaming *stream)
566 struct uvc_clock *clock = &stream->clock;
570 clock->last_sof = -1;
571 clock->sof_offset = -1;
574 static int uvc_video_clock_init(struct uvc_streaming *stream)
576 struct uvc_clock *clock = &stream->clock;
578 spin_lock_init(&clock->lock);
581 clock->samples = kmalloc_array(clock->size, sizeof(*clock->samples),
583 if (clock->samples == NULL)
586 uvc_video_clock_reset(stream);
591 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
593 kfree(stream->clock.samples);
594 stream->clock.samples = NULL;
598 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
600 * Host SOF counters reported by usb_get_current_frame_number() usually don't
601 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
602 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
603 * controller and its configuration.
605 * We thus need to recover the SOF value corresponding to the host frame number.
606 * As the device and host frame numbers are sampled in a short interval, the
607 * difference between their values should be equal to a small delta plus an
608 * integer multiple of 256 caused by the host frame number limited precision.
610 * To obtain the recovered host SOF value, compute the small delta by masking
611 * the high bits of the host frame counter and device SOF difference and add it
612 * to the device SOF value.
614 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
616 /* The delta value can be negative. */
619 delta_sof = (sample->host_sof - sample->dev_sof) & 255;
621 return (sample->dev_sof + delta_sof) & 2047;
625 * uvc_video_clock_update - Update the buffer timestamp
627 * This function converts the buffer PTS timestamp to the host clock domain by
628 * going through the USB SOF clock domain and stores the result in the V4L2
629 * buffer timestamp field.
631 * The relationship between the device clock and the host clock isn't known.
632 * However, the device and the host share the common USB SOF clock which can be
633 * used to recover that relationship.
635 * The relationship between the device clock and the USB SOF clock is considered
636 * to be linear over the clock samples sliding window and is given by
640 * Several methods to compute the slope (m) and intercept (p) can be used. As
641 * the clock drift should be small compared to the sliding window size, we
642 * assume that the line that goes through the points at both ends of the window
643 * is a good approximation. Naming those points P1 and P2, we get
645 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
646 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
650 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
652 * to avoid losing precision in the division. Similarly, the host timestamp is
655 * TS = ((TS2 - TS1) * SOF + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
657 * SOF values are coded on 11 bits by USB. We extend their precision with 16
658 * decimal bits, leading to a 11.16 coding.
660 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
661 * be normalized using the nominal device clock frequency reported through the
664 * Both the PTS/STC and SOF counters roll over, after a fixed but device
665 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
666 * sliding window size is smaller than the rollover period, differences computed
667 * on unsigned integers will produce the correct result. However, the p term in
668 * the linear relations will be miscomputed.
670 * To fix the issue, we subtract a constant from the PTS and STC values to bring
671 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
672 * the 32 bit range without any rollover.
674 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
675 * computed by (1) will never be smaller than 0. This offset is then compensated
676 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
677 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
678 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
679 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
680 * SOF value at the end of the sliding window.
682 * Finally we subtract a constant from the host timestamps to bring the first
683 * timestamp of the sliding window to 1s.
685 void uvc_video_clock_update(struct uvc_streaming *stream,
686 struct vb2_v4l2_buffer *vbuf,
687 struct uvc_buffer *buf)
689 struct uvc_clock *clock = &stream->clock;
690 struct uvc_clock_sample *first;
691 struct uvc_clock_sample *last;
701 if (!uvc_hw_timestamps_param)
705 * We will get called from __vb2_queue_cancel() if there are buffers
706 * done but not dequeued by the user, but the sample array has already
707 * been released at that time. Just bail out in that case.
712 spin_lock_irqsave(&clock->lock, flags);
714 if (clock->count < clock->size)
717 first = &clock->samples[clock->head];
718 last = &clock->samples[(clock->head - 1) % clock->size];
720 /* First step, PTS to SOF conversion. */
721 delta_stc = buf->pts - (1UL << 31);
722 x1 = first->dev_stc - delta_stc;
723 x2 = last->dev_stc - delta_stc;
727 y1 = (first->dev_sof + 2048) << 16;
728 y2 = (last->dev_sof + 2048) << 16;
732 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
734 y = div_u64(y, x2 - x1);
738 uvc_dbg(stream->dev, CLOCK,
739 "%s: PTS %u y %llu.%06llu SOF %u.%06llu (x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
740 stream->dev->name, buf->pts,
741 y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
742 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
743 x1, x2, y1, y2, clock->sof_offset);
745 /* Second step, SOF to host clock conversion. */
746 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
747 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
754 y2 = (u32)ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
756 /* Interpolated and host SOF timestamps can wrap around at slightly
757 * different times. Handle this by adding or removing 2048 to or from
758 * the computed SOF value to keep it close to the SOF samples mean
761 mean = (x1 + x2) / 2;
762 if (mean - (1024 << 16) > sof)
764 else if (sof > mean + (1024 << 16))
767 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
769 y = div_u64(y, x2 - x1);
771 timestamp = ktime_to_ns(first->host_time) + y - y1;
773 uvc_dbg(stream->dev, CLOCK,
774 "%s: SOF %u.%06llu y %llu ts %llu buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
776 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
777 y, timestamp, vbuf->vb2_buf.timestamp,
778 x1, first->host_sof, first->dev_sof,
779 x2, last->host_sof, last->dev_sof, y1, y2);
781 /* Update the V4L2 buffer. */
782 vbuf->vb2_buf.timestamp = timestamp;
785 spin_unlock_irqrestore(&clock->lock, flags);
788 /* ------------------------------------------------------------------------
792 static void uvc_video_stats_decode(struct uvc_streaming *stream,
793 const u8 *data, int len)
795 unsigned int header_size;
796 bool has_pts = false;
797 bool has_scr = false;
802 if (stream->stats.stream.nb_frames == 0 &&
803 stream->stats.frame.nb_packets == 0)
804 stream->stats.stream.start_ts = ktime_get();
806 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
807 case UVC_STREAM_PTS | UVC_STREAM_SCR:
825 /* Check for invalid headers. */
826 if (len < header_size || data[0] < header_size) {
827 stream->stats.frame.nb_invalid++;
831 /* Extract the timestamps. */
833 pts = get_unaligned_le32(&data[2]);
836 scr_stc = get_unaligned_le32(&data[header_size - 6]);
837 scr_sof = get_unaligned_le16(&data[header_size - 2]);
840 /* Is PTS constant through the whole frame ? */
841 if (has_pts && stream->stats.frame.nb_pts) {
842 if (stream->stats.frame.pts != pts) {
843 stream->stats.frame.nb_pts_diffs++;
844 stream->stats.frame.last_pts_diff =
845 stream->stats.frame.nb_packets;
850 stream->stats.frame.nb_pts++;
851 stream->stats.frame.pts = pts;
854 /* Do all frames have a PTS in their first non-empty packet, or before
855 * their first empty packet ?
857 if (stream->stats.frame.size == 0) {
858 if (len > header_size)
859 stream->stats.frame.has_initial_pts = has_pts;
860 if (len == header_size && has_pts)
861 stream->stats.frame.has_early_pts = true;
864 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
865 if (has_scr && stream->stats.frame.nb_scr) {
866 if (stream->stats.frame.scr_stc != scr_stc)
867 stream->stats.frame.nb_scr_diffs++;
871 /* Expand the SOF counter to 32 bits and store its value. */
872 if (stream->stats.stream.nb_frames > 0 ||
873 stream->stats.frame.nb_scr > 0)
874 stream->stats.stream.scr_sof_count +=
875 (scr_sof - stream->stats.stream.scr_sof) % 2048;
876 stream->stats.stream.scr_sof = scr_sof;
878 stream->stats.frame.nb_scr++;
879 stream->stats.frame.scr_stc = scr_stc;
880 stream->stats.frame.scr_sof = scr_sof;
882 if (scr_sof < stream->stats.stream.min_sof)
883 stream->stats.stream.min_sof = scr_sof;
884 if (scr_sof > stream->stats.stream.max_sof)
885 stream->stats.stream.max_sof = scr_sof;
888 /* Record the first non-empty packet number. */
889 if (stream->stats.frame.size == 0 && len > header_size)
890 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
892 /* Update the frame size. */
893 stream->stats.frame.size += len - header_size;
895 /* Update the packets counters. */
896 stream->stats.frame.nb_packets++;
897 if (len <= header_size)
898 stream->stats.frame.nb_empty++;
900 if (data[1] & UVC_STREAM_ERR)
901 stream->stats.frame.nb_errors++;
904 static void uvc_video_stats_update(struct uvc_streaming *stream)
906 struct uvc_stats_frame *frame = &stream->stats.frame;
908 uvc_dbg(stream->dev, STATS,
909 "frame %u stats: %u/%u/%u packets, %u/%u/%u pts (%searly %sinitial), %u/%u scr, last pts/stc/sof %u/%u/%u\n",
910 stream->sequence, frame->first_data,
911 frame->nb_packets - frame->nb_empty, frame->nb_packets,
912 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
913 frame->has_early_pts ? "" : "!",
914 frame->has_initial_pts ? "" : "!",
915 frame->nb_scr_diffs, frame->nb_scr,
916 frame->pts, frame->scr_stc, frame->scr_sof);
918 stream->stats.stream.nb_frames++;
919 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
920 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
921 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
922 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
924 if (frame->has_early_pts)
925 stream->stats.stream.nb_pts_early++;
926 if (frame->has_initial_pts)
927 stream->stats.stream.nb_pts_initial++;
928 if (frame->last_pts_diff <= frame->first_data)
929 stream->stats.stream.nb_pts_constant++;
930 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
931 stream->stats.stream.nb_scr_count_ok++;
932 if (frame->nb_scr_diffs + 1 == frame->nb_scr)
933 stream->stats.stream.nb_scr_diffs_ok++;
935 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
938 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
941 unsigned int scr_sof_freq;
942 unsigned int duration;
945 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
946 * frequency this will not overflow before more than 1h.
948 duration = ktime_ms_delta(stream->stats.stream.stop_ts,
949 stream->stats.stream.start_ts);
951 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
956 count += scnprintf(buf + count, size - count,
957 "frames: %u\npackets: %u\nempty: %u\n"
958 "errors: %u\ninvalid: %u\n",
959 stream->stats.stream.nb_frames,
960 stream->stats.stream.nb_packets,
961 stream->stats.stream.nb_empty,
962 stream->stats.stream.nb_errors,
963 stream->stats.stream.nb_invalid);
964 count += scnprintf(buf + count, size - count,
965 "pts: %u early, %u initial, %u ok\n",
966 stream->stats.stream.nb_pts_early,
967 stream->stats.stream.nb_pts_initial,
968 stream->stats.stream.nb_pts_constant);
969 count += scnprintf(buf + count, size - count,
970 "scr: %u count ok, %u diff ok\n",
971 stream->stats.stream.nb_scr_count_ok,
972 stream->stats.stream.nb_scr_diffs_ok);
973 count += scnprintf(buf + count, size - count,
974 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
975 stream->stats.stream.min_sof,
976 stream->stats.stream.max_sof,
977 scr_sof_freq / 1000, scr_sof_freq % 1000);
982 static void uvc_video_stats_start(struct uvc_streaming *stream)
984 memset(&stream->stats, 0, sizeof(stream->stats));
985 stream->stats.stream.min_sof = 2048;
988 static void uvc_video_stats_stop(struct uvc_streaming *stream)
990 stream->stats.stream.stop_ts = ktime_get();
993 /* ------------------------------------------------------------------------
997 /* Video payload decoding is handled by uvc_video_decode_start(),
998 * uvc_video_decode_data() and uvc_video_decode_end().
1000 * uvc_video_decode_start is called with URB data at the start of a bulk or
1001 * isochronous payload. It processes header data and returns the header size
1002 * in bytes if successful. If an error occurs, it returns a negative error
1003 * code. The following error codes have special meanings.
1005 * - EAGAIN informs the caller that the current video buffer should be marked
1006 * as done, and that the function should be called again with the same data
1007 * and a new video buffer. This is used when end of frame conditions can be
1008 * reliably detected at the beginning of the next frame only.
1010 * If an error other than -EAGAIN is returned, the caller will drop the current
1011 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
1012 * made until the next payload. -ENODATA can be used to drop the current
1013 * payload if no other error code is appropriate.
1015 * uvc_video_decode_data is called for every URB with URB data. It copies the
1016 * data to the video buffer.
1018 * uvc_video_decode_end is called with header data at the end of a bulk or
1019 * isochronous payload. It performs any additional header data processing and
1020 * returns 0 or a negative error code if an error occurred. As header data have
1021 * already been processed by uvc_video_decode_start, this functions isn't
1022 * required to perform sanity checks a second time.
1024 * For isochronous transfers where a payload is always transferred in a single
1025 * URB, the three functions will be called in a row.
1027 * To let the decoder process header data and update its internal state even
1028 * when no video buffer is available, uvc_video_decode_start must be prepared
1029 * to be called with a NULL buf parameter. uvc_video_decode_data and
1030 * uvc_video_decode_end will never be called with a NULL buffer.
1032 static int uvc_video_decode_start(struct uvc_streaming *stream,
1033 struct uvc_buffer *buf, const u8 *data, int len)
1038 * - packet must be at least 2 bytes long
1039 * - bHeaderLength value must be at least 2 bytes (see above)
1040 * - bHeaderLength value can't be larger than the packet size.
1042 if (len < 2 || data[0] < 2 || data[0] > len) {
1043 stream->stats.frame.nb_invalid++;
1047 fid = data[1] & UVC_STREAM_FID;
1049 /* Increase the sequence number regardless of any buffer states, so
1050 * that discontinuous sequence numbers always indicate lost frames.
1052 if (stream->last_fid != fid) {
1054 if (stream->sequence)
1055 uvc_video_stats_update(stream);
1058 uvc_video_clock_decode(stream, buf, data, len);
1059 uvc_video_stats_decode(stream, data, len);
1061 /* Store the payload FID bit and return immediately when the buffer is
1065 stream->last_fid = fid;
1069 /* Mark the buffer as bad if the error bit is set. */
1070 if (data[1] & UVC_STREAM_ERR) {
1071 uvc_dbg(stream->dev, FRAME,
1072 "Marking buffer as bad (error bit set)\n");
1076 /* Synchronize to the input stream by waiting for the FID bit to be
1077 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1078 * stream->last_fid is initialized to -1, so the first isochronous
1079 * frame will always be in sync.
1081 * If the device doesn't toggle the FID bit, invert stream->last_fid
1082 * when the EOF bit is set to force synchronisation on the next packet.
1084 if (buf->state != UVC_BUF_STATE_ACTIVE) {
1085 if (fid == stream->last_fid) {
1086 uvc_dbg(stream->dev, FRAME,
1087 "Dropping payload (out of sync)\n");
1088 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1089 (data[1] & UVC_STREAM_EOF))
1090 stream->last_fid ^= UVC_STREAM_FID;
1094 buf->buf.field = V4L2_FIELD_NONE;
1095 buf->buf.sequence = stream->sequence;
1096 buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time());
1098 /* TODO: Handle PTS and SCR. */
1099 buf->state = UVC_BUF_STATE_ACTIVE;
1102 /* Mark the buffer as done if we're at the beginning of a new frame.
1103 * End of frame detection is better implemented by checking the EOF
1104 * bit (FID bit toggling is delayed by one frame compared to the EOF
1105 * bit), but some devices don't set the bit at end of frame (and the
1106 * last payload can be lost anyway). We thus must check if the FID has
1109 * stream->last_fid is initialized to -1, so the first isochronous
1110 * frame will never trigger an end of frame detection.
1112 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1113 * as it doesn't make sense to return an empty buffer. This also
1114 * avoids detecting end of frame conditions at FID toggling if the
1115 * previous payload had the EOF bit set.
1117 if (fid != stream->last_fid && buf->bytesused != 0) {
1118 uvc_dbg(stream->dev, FRAME,
1119 "Frame complete (FID bit toggled)\n");
1120 buf->state = UVC_BUF_STATE_READY;
1124 stream->last_fid = fid;
1129 static inline enum dma_data_direction uvc_stream_dir(
1130 struct uvc_streaming *stream)
1132 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1133 return DMA_FROM_DEVICE;
1135 return DMA_TO_DEVICE;
1138 static inline struct device *uvc_stream_to_dmadev(struct uvc_streaming *stream)
1140 return bus_to_hcd(stream->dev->udev->bus)->self.sysdev;
1143 static int uvc_submit_urb(struct uvc_urb *uvc_urb, gfp_t mem_flags)
1146 dma_sync_sgtable_for_device(uvc_stream_to_dmadev(uvc_urb->stream),
1148 uvc_stream_dir(uvc_urb->stream));
1149 return usb_submit_urb(uvc_urb->urb, mem_flags);
1153 * uvc_video_decode_data_work: Asynchronous memcpy processing
1155 * Copy URB data to video buffers in process context, releasing buffer
1156 * references and requeuing the URB when done.
1158 static void uvc_video_copy_data_work(struct work_struct *work)
1160 struct uvc_urb *uvc_urb = container_of(work, struct uvc_urb, work);
1164 for (i = 0; i < uvc_urb->async_operations; i++) {
1165 struct uvc_copy_op *op = &uvc_urb->copy_operations[i];
1167 memcpy(op->dst, op->src, op->len);
1169 /* Release reference taken on this buffer. */
1170 uvc_queue_buffer_release(op->buf);
1173 ret = uvc_submit_urb(uvc_urb, GFP_KERNEL);
1175 dev_err(&uvc_urb->stream->intf->dev,
1176 "Failed to resubmit video URB (%d).\n", ret);
1179 static void uvc_video_decode_data(struct uvc_urb *uvc_urb,
1180 struct uvc_buffer *buf, const u8 *data, int len)
1182 unsigned int active_op = uvc_urb->async_operations;
1183 struct uvc_copy_op *op = &uvc_urb->copy_operations[active_op];
1184 unsigned int maxlen;
1189 maxlen = buf->length - buf->bytesused;
1191 /* Take a buffer reference for async work. */
1192 kref_get(&buf->ref);
1196 op->dst = buf->mem + buf->bytesused;
1197 op->len = min_t(unsigned int, len, maxlen);
1199 buf->bytesused += op->len;
1201 /* Complete the current frame if the buffer size was exceeded. */
1203 uvc_dbg(uvc_urb->stream->dev, FRAME,
1204 "Frame complete (overflow)\n");
1206 buf->state = UVC_BUF_STATE_READY;
1209 uvc_urb->async_operations++;
1212 static void uvc_video_decode_end(struct uvc_streaming *stream,
1213 struct uvc_buffer *buf, const u8 *data, int len)
1215 /* Mark the buffer as done if the EOF marker is set. */
1216 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1217 uvc_dbg(stream->dev, FRAME, "Frame complete (EOF found)\n");
1219 uvc_dbg(stream->dev, FRAME, "EOF in empty payload\n");
1220 buf->state = UVC_BUF_STATE_READY;
1221 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1222 stream->last_fid ^= UVC_STREAM_FID;
1226 /* Video payload encoding is handled by uvc_video_encode_header() and
1227 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1229 * uvc_video_encode_header is called at the start of a payload. It adds header
1230 * data to the transfer buffer and returns the header size. As the only known
1231 * UVC output device transfers a whole frame in a single payload, the EOF bit
1232 * is always set in the header.
1234 * uvc_video_encode_data is called for every URB and copies the data from the
1235 * video buffer to the transfer buffer.
1237 static int uvc_video_encode_header(struct uvc_streaming *stream,
1238 struct uvc_buffer *buf, u8 *data, int len)
1240 data[0] = 2; /* Header length */
1241 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1242 | (stream->last_fid & UVC_STREAM_FID);
1246 static int uvc_video_encode_data(struct uvc_streaming *stream,
1247 struct uvc_buffer *buf, u8 *data, int len)
1249 struct uvc_video_queue *queue = &stream->queue;
1250 unsigned int nbytes;
1253 /* Copy video data to the URB buffer. */
1254 mem = buf->mem + queue->buf_used;
1255 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1256 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1258 memcpy(data, mem, nbytes);
1260 queue->buf_used += nbytes;
1265 /* ------------------------------------------------------------------------
1270 * Additionally to the payload headers we also want to provide the user with USB
1271 * Frame Numbers and system time values. The resulting buffer is thus composed
1272 * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame
1273 * Number, and a copy of the payload header.
1275 * Ideally we want to capture all payload headers for each frame. However, their
1276 * number is unknown and unbound. We thus drop headers that contain no vendor
1277 * data and that either contain no SCR value or an SCR value identical to the
1280 static void uvc_video_decode_meta(struct uvc_streaming *stream,
1281 struct uvc_buffer *meta_buf,
1282 const u8 *mem, unsigned int length)
1284 struct uvc_meta_buf *meta;
1286 bool has_pts, has_scr;
1287 unsigned long flags;
1292 if (!meta_buf || length == 2)
1295 if (meta_buf->length - meta_buf->bytesused <
1296 length + sizeof(meta->ns) + sizeof(meta->sof)) {
1297 meta_buf->error = 1;
1301 has_pts = mem[1] & UVC_STREAM_PTS;
1302 has_scr = mem[1] & UVC_STREAM_SCR;
1314 if (stream->meta.format == V4L2_META_FMT_UVC)
1317 if (length == len_std && (!has_scr ||
1318 !memcmp(scr, stream->clock.last_scr, 6)))
1321 meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
1322 local_irq_save(flags);
1323 time = uvc_video_get_time();
1324 sof = usb_get_current_frame_number(stream->dev->udev);
1325 local_irq_restore(flags);
1326 put_unaligned(ktime_to_ns(time), &meta->ns);
1327 put_unaligned(sof, &meta->sof);
1330 memcpy(stream->clock.last_scr, scr, 6);
1332 memcpy(&meta->length, mem, length);
1333 meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);
1335 uvc_dbg(stream->dev, FRAME,
1336 "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
1337 __func__, ktime_to_ns(time), meta->sof, meta->length,
1339 has_pts ? *(u32 *)meta->buf : 0,
1340 has_scr ? *(u32 *)scr : 0,
1341 has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
1344 /* ------------------------------------------------------------------------
1349 * Set error flag for incomplete buffer.
1351 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1352 struct uvc_buffer *buf)
1354 if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1355 !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1360 * Completion handler for video URBs.
1363 static void uvc_video_next_buffers(struct uvc_streaming *stream,
1364 struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
1366 uvc_video_validate_buffer(stream, *video_buf);
1369 struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
1370 const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;
1372 vb2_meta->sequence = vb2_video->sequence;
1373 vb2_meta->field = vb2_video->field;
1374 vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;
1376 (*meta_buf)->state = UVC_BUF_STATE_READY;
1377 if (!(*meta_buf)->error)
1378 (*meta_buf)->error = (*video_buf)->error;
1379 *meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
1382 *video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
1385 static void uvc_video_decode_isoc(struct uvc_urb *uvc_urb,
1386 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1388 struct urb *urb = uvc_urb->urb;
1389 struct uvc_streaming *stream = uvc_urb->stream;
1393 for (i = 0; i < urb->number_of_packets; ++i) {
1394 if (urb->iso_frame_desc[i].status < 0) {
1395 uvc_dbg(stream->dev, FRAME,
1396 "USB isochronous frame lost (%d)\n",
1397 urb->iso_frame_desc[i].status);
1398 /* Mark the buffer as faulty. */
1404 /* Decode the payload header. */
1405 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1407 ret = uvc_video_decode_start(stream, buf, mem,
1408 urb->iso_frame_desc[i].actual_length);
1410 uvc_video_next_buffers(stream, &buf, &meta_buf);
1411 } while (ret == -EAGAIN);
1416 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1418 /* Decode the payload data. */
1419 uvc_video_decode_data(uvc_urb, buf, mem + ret,
1420 urb->iso_frame_desc[i].actual_length - ret);
1422 /* Process the header again. */
1423 uvc_video_decode_end(stream, buf, mem,
1424 urb->iso_frame_desc[i].actual_length);
1426 if (buf->state == UVC_BUF_STATE_READY)
1427 uvc_video_next_buffers(stream, &buf, &meta_buf);
1431 static void uvc_video_decode_bulk(struct uvc_urb *uvc_urb,
1432 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1434 struct urb *urb = uvc_urb->urb;
1435 struct uvc_streaming *stream = uvc_urb->stream;
1440 * Ignore ZLPs if they're not part of a frame, otherwise process them
1441 * to trigger the end of payload detection.
1443 if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1446 mem = urb->transfer_buffer;
1447 len = urb->actual_length;
1448 stream->bulk.payload_size += len;
1450 /* If the URB is the first of its payload, decode and save the
1453 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1455 ret = uvc_video_decode_start(stream, buf, mem, len);
1457 uvc_video_next_buffers(stream, &buf, &meta_buf);
1458 } while (ret == -EAGAIN);
1460 /* If an error occurred skip the rest of the payload. */
1461 if (ret < 0 || buf == NULL) {
1462 stream->bulk.skip_payload = 1;
1464 memcpy(stream->bulk.header, mem, ret);
1465 stream->bulk.header_size = ret;
1467 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1474 /* The buffer queue might have been cancelled while a bulk transfer
1475 * was in progress, so we can reach here with buf equal to NULL. Make
1476 * sure buf is never dereferenced if NULL.
1479 /* Prepare video data for processing. */
1480 if (!stream->bulk.skip_payload && buf != NULL)
1481 uvc_video_decode_data(uvc_urb, buf, mem, len);
1483 /* Detect the payload end by a URB smaller than the maximum size (or
1484 * a payload size equal to the maximum) and process the header again.
1486 if (urb->actual_length < urb->transfer_buffer_length ||
1487 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1488 if (!stream->bulk.skip_payload && buf != NULL) {
1489 uvc_video_decode_end(stream, buf, stream->bulk.header,
1490 stream->bulk.payload_size);
1491 if (buf->state == UVC_BUF_STATE_READY)
1492 uvc_video_next_buffers(stream, &buf, &meta_buf);
1495 stream->bulk.header_size = 0;
1496 stream->bulk.skip_payload = 0;
1497 stream->bulk.payload_size = 0;
1501 static void uvc_video_encode_bulk(struct uvc_urb *uvc_urb,
1502 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1504 struct urb *urb = uvc_urb->urb;
1505 struct uvc_streaming *stream = uvc_urb->stream;
1507 u8 *mem = urb->transfer_buffer;
1508 int len = stream->urb_size, ret;
1511 urb->transfer_buffer_length = 0;
1515 /* If the URB is the first of its payload, add the header. */
1516 if (stream->bulk.header_size == 0) {
1517 ret = uvc_video_encode_header(stream, buf, mem, len);
1518 stream->bulk.header_size = ret;
1519 stream->bulk.payload_size += ret;
1524 /* Process video data. */
1525 ret = uvc_video_encode_data(stream, buf, mem, len);
1527 stream->bulk.payload_size += ret;
1530 if (buf->bytesused == stream->queue.buf_used ||
1531 stream->bulk.payload_size == stream->bulk.max_payload_size) {
1532 if (buf->bytesused == stream->queue.buf_used) {
1533 stream->queue.buf_used = 0;
1534 buf->state = UVC_BUF_STATE_READY;
1535 buf->buf.sequence = ++stream->sequence;
1536 uvc_queue_next_buffer(&stream->queue, buf);
1537 stream->last_fid ^= UVC_STREAM_FID;
1540 stream->bulk.header_size = 0;
1541 stream->bulk.payload_size = 0;
1544 urb->transfer_buffer_length = stream->urb_size - len;
1547 static void uvc_video_complete(struct urb *urb)
1549 struct uvc_urb *uvc_urb = urb->context;
1550 struct uvc_streaming *stream = uvc_urb->stream;
1551 struct uvc_video_queue *queue = &stream->queue;
1552 struct uvc_video_queue *qmeta = &stream->meta.queue;
1553 struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
1554 struct uvc_buffer *buf = NULL;
1555 struct uvc_buffer *buf_meta = NULL;
1556 unsigned long flags;
1559 switch (urb->status) {
1564 dev_warn(&stream->intf->dev,
1565 "Non-zero status (%d) in video completion handler.\n",
1568 case -ENOENT: /* usb_poison_urb() called. */
1572 case -ECONNRESET: /* usb_unlink_urb() called. */
1573 case -ESHUTDOWN: /* The endpoint is being disabled. */
1574 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1576 uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
1580 buf = uvc_queue_get_current_buffer(queue);
1583 spin_lock_irqsave(&qmeta->irqlock, flags);
1584 if (!list_empty(&qmeta->irqqueue))
1585 buf_meta = list_first_entry(&qmeta->irqqueue,
1586 struct uvc_buffer, queue);
1587 spin_unlock_irqrestore(&qmeta->irqlock, flags);
1590 /* Re-initialise the URB async work. */
1591 uvc_urb->async_operations = 0;
1593 /* Sync DMA and invalidate vmap range. */
1594 dma_sync_sgtable_for_cpu(uvc_stream_to_dmadev(uvc_urb->stream),
1595 uvc_urb->sgt, uvc_stream_dir(stream));
1596 invalidate_kernel_vmap_range(uvc_urb->buffer,
1597 uvc_urb->stream->urb_size);
1600 * Process the URB headers, and optionally queue expensive memcpy tasks
1601 * to be deferred to a work queue.
1603 stream->decode(uvc_urb, buf, buf_meta);
1605 /* If no async work is needed, resubmit the URB immediately. */
1606 if (!uvc_urb->async_operations) {
1607 ret = uvc_submit_urb(uvc_urb, GFP_ATOMIC);
1609 dev_err(&stream->intf->dev,
1610 "Failed to resubmit video URB (%d).\n", ret);
1614 queue_work(stream->async_wq, &uvc_urb->work);
1618 * Free transfer buffers.
1620 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1622 struct device *dma_dev = uvc_stream_to_dmadev(stream);
1623 struct uvc_urb *uvc_urb;
1625 for_each_uvc_urb(uvc_urb, stream) {
1626 if (!uvc_urb->buffer)
1629 dma_vunmap_noncontiguous(dma_dev, uvc_urb->buffer);
1630 dma_free_noncontiguous(dma_dev, stream->urb_size, uvc_urb->sgt,
1631 uvc_stream_dir(stream));
1633 uvc_urb->buffer = NULL;
1634 uvc_urb->sgt = NULL;
1637 stream->urb_size = 0;
1640 static bool uvc_alloc_urb_buffer(struct uvc_streaming *stream,
1641 struct uvc_urb *uvc_urb, gfp_t gfp_flags)
1643 struct device *dma_dev = uvc_stream_to_dmadev(stream);
1645 uvc_urb->sgt = dma_alloc_noncontiguous(dma_dev, stream->urb_size,
1646 uvc_stream_dir(stream),
1650 uvc_urb->dma = uvc_urb->sgt->sgl->dma_address;
1652 uvc_urb->buffer = dma_vmap_noncontiguous(dma_dev, stream->urb_size,
1654 if (!uvc_urb->buffer) {
1655 dma_free_noncontiguous(dma_dev, stream->urb_size,
1657 uvc_stream_dir(stream));
1658 uvc_urb->sgt = NULL;
1666 * Allocate transfer buffers. This function can be called with buffers
1667 * already allocated when resuming from suspend, in which case it will
1668 * return without touching the buffers.
1670 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1671 * system is too low on memory try successively smaller numbers of packets
1672 * until allocation succeeds.
1674 * Return the number of allocated packets on success or 0 when out of memory.
1676 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1677 unsigned int size, unsigned int psize, gfp_t gfp_flags)
1679 unsigned int npackets;
1682 /* Buffers are already allocated, bail out. */
1683 if (stream->urb_size)
1684 return stream->urb_size / psize;
1686 /* Compute the number of packets. Bulk endpoints might transfer UVC
1687 * payloads across multiple URBs.
1689 npackets = DIV_ROUND_UP(size, psize);
1690 if (npackets > UVC_MAX_PACKETS)
1691 npackets = UVC_MAX_PACKETS;
1693 /* Retry allocations until one succeed. */
1694 for (; npackets > 1; npackets /= 2) {
1695 stream->urb_size = psize * npackets;
1697 for (i = 0; i < UVC_URBS; ++i) {
1698 struct uvc_urb *uvc_urb = &stream->uvc_urb[i];
1700 if (!uvc_alloc_urb_buffer(stream, uvc_urb, gfp_flags)) {
1701 uvc_free_urb_buffers(stream);
1705 uvc_urb->stream = stream;
1708 if (i == UVC_URBS) {
1709 uvc_dbg(stream->dev, VIDEO,
1710 "Allocated %u URB buffers of %ux%u bytes each\n",
1711 UVC_URBS, npackets, psize);
1716 uvc_dbg(stream->dev, VIDEO,
1717 "Failed to allocate URB buffers (%u bytes per packet)\n",
1723 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1725 static void uvc_video_stop_transfer(struct uvc_streaming *stream,
1728 struct uvc_urb *uvc_urb;
1730 uvc_video_stats_stop(stream);
1733 * We must poison the URBs rather than kill them to ensure that even
1734 * after the completion handler returns, any asynchronous workqueues
1735 * will be prevented from resubmitting the URBs.
1737 for_each_uvc_urb(uvc_urb, stream)
1738 usb_poison_urb(uvc_urb->urb);
1740 flush_workqueue(stream->async_wq);
1742 for_each_uvc_urb(uvc_urb, stream) {
1743 usb_free_urb(uvc_urb->urb);
1744 uvc_urb->urb = NULL;
1748 uvc_free_urb_buffers(stream);
1752 * Compute the maximum number of bytes per interval for an endpoint.
1754 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1755 struct usb_host_endpoint *ep)
1760 switch (dev->speed) {
1761 case USB_SPEED_SUPER:
1762 case USB_SPEED_SUPER_PLUS:
1763 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1764 case USB_SPEED_HIGH:
1765 psize = usb_endpoint_maxp(&ep->desc);
1766 mult = usb_endpoint_maxp_mult(&ep->desc);
1767 return psize * mult;
1768 case USB_SPEED_WIRELESS:
1769 psize = usb_endpoint_maxp(&ep->desc);
1772 psize = usb_endpoint_maxp(&ep->desc);
1778 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1779 * is given by the endpoint.
1781 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1782 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1785 struct uvc_urb *uvc_urb;
1786 unsigned int npackets, i;
1790 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1791 size = stream->ctrl.dwMaxVideoFrameSize;
1793 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1797 size = npackets * psize;
1799 for_each_uvc_urb(uvc_urb, stream) {
1800 urb = usb_alloc_urb(npackets, gfp_flags);
1802 uvc_video_stop_transfer(stream, 1);
1806 urb->dev = stream->dev->udev;
1807 urb->context = uvc_urb;
1808 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1809 ep->desc.bEndpointAddress);
1810 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1811 urb->transfer_dma = uvc_urb->dma;
1812 urb->interval = ep->desc.bInterval;
1813 urb->transfer_buffer = uvc_urb->buffer;
1814 urb->complete = uvc_video_complete;
1815 urb->number_of_packets = npackets;
1816 urb->transfer_buffer_length = size;
1818 for (i = 0; i < npackets; ++i) {
1819 urb->iso_frame_desc[i].offset = i * psize;
1820 urb->iso_frame_desc[i].length = psize;
1830 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1831 * given by the endpoint.
1833 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1834 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1837 struct uvc_urb *uvc_urb;
1838 unsigned int npackets, pipe;
1842 psize = usb_endpoint_maxp(&ep->desc);
1843 size = stream->ctrl.dwMaxPayloadTransferSize;
1844 stream->bulk.max_payload_size = size;
1846 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1850 size = npackets * psize;
1852 if (usb_endpoint_dir_in(&ep->desc))
1853 pipe = usb_rcvbulkpipe(stream->dev->udev,
1854 ep->desc.bEndpointAddress);
1856 pipe = usb_sndbulkpipe(stream->dev->udev,
1857 ep->desc.bEndpointAddress);
1859 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1862 for_each_uvc_urb(uvc_urb, stream) {
1863 urb = usb_alloc_urb(0, gfp_flags);
1865 uvc_video_stop_transfer(stream, 1);
1869 usb_fill_bulk_urb(urb, stream->dev->udev, pipe, uvc_urb->buffer,
1870 size, uvc_video_complete, uvc_urb);
1871 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1872 urb->transfer_dma = uvc_urb->dma;
1881 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1883 static int uvc_video_start_transfer(struct uvc_streaming *stream,
1886 struct usb_interface *intf = stream->intf;
1887 struct usb_host_endpoint *ep;
1888 struct uvc_urb *uvc_urb;
1892 stream->sequence = -1;
1893 stream->last_fid = -1;
1894 stream->bulk.header_size = 0;
1895 stream->bulk.skip_payload = 0;
1896 stream->bulk.payload_size = 0;
1898 uvc_video_stats_start(stream);
1900 if (intf->num_altsetting > 1) {
1901 struct usb_host_endpoint *best_ep = NULL;
1902 unsigned int best_psize = UINT_MAX;
1903 unsigned int bandwidth;
1904 unsigned int altsetting;
1905 int intfnum = stream->intfnum;
1907 /* Isochronous endpoint, select the alternate setting. */
1908 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1910 if (bandwidth == 0) {
1911 uvc_dbg(stream->dev, VIDEO,
1912 "Device requested null bandwidth, defaulting to lowest\n");
1915 uvc_dbg(stream->dev, VIDEO,
1916 "Device requested %u B/frame bandwidth\n",
1920 for (i = 0; i < intf->num_altsetting; ++i) {
1921 struct usb_host_interface *alts;
1924 alts = &intf->altsetting[i];
1925 ep = uvc_find_endpoint(alts,
1926 stream->header.bEndpointAddress);
1930 /* Check if the bandwidth is high enough. */
1931 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1932 if (psize >= bandwidth && psize <= best_psize) {
1933 altsetting = alts->desc.bAlternateSetting;
1939 if (best_ep == NULL) {
1940 uvc_dbg(stream->dev, VIDEO,
1941 "No fast enough alt setting for requested bandwidth\n");
1945 uvc_dbg(stream->dev, VIDEO,
1946 "Selecting alternate setting %u (%u B/frame bandwidth)\n",
1947 altsetting, best_psize);
1949 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1953 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1955 /* Bulk endpoint, proceed to URB initialization. */
1956 ep = uvc_find_endpoint(&intf->altsetting[0],
1957 stream->header.bEndpointAddress);
1961 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1967 /* Submit the URBs. */
1968 for_each_uvc_urb(uvc_urb, stream) {
1969 ret = uvc_submit_urb(uvc_urb, gfp_flags);
1971 dev_err(&stream->intf->dev,
1972 "Failed to submit URB %u (%d).\n",
1973 uvc_urb_index(uvc_urb), ret);
1974 uvc_video_stop_transfer(stream, 1);
1979 /* The Logitech C920 temporarily forgets that it should not be adjusting
1980 * Exposure Absolute during init so restore controls to stored values.
1982 if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1983 uvc_ctrl_restore_values(stream->dev);
1988 /* --------------------------------------------------------------------------
1993 * Stop streaming without disabling the video queue.
1995 * To let userspace applications resume without trouble, we must not touch the
1996 * video buffers in any way. We mark the device as frozen to make sure the URB
1997 * completion handler won't try to cancel the queue when we kill the URBs.
1999 int uvc_video_suspend(struct uvc_streaming *stream)
2001 if (!uvc_queue_streaming(&stream->queue))
2005 uvc_video_stop_transfer(stream, 0);
2006 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2011 * Reconfigure the video interface and restart streaming if it was enabled
2014 * If an error occurs, disable the video queue. This will wake all pending
2015 * buffers, making sure userspace applications are notified of the problem
2016 * instead of waiting forever.
2018 int uvc_video_resume(struct uvc_streaming *stream, int reset)
2022 /* If the bus has been reset on resume, set the alternate setting to 0.
2023 * This should be the default value, but some devices crash or otherwise
2024 * misbehave if they don't receive a SET_INTERFACE request before any
2025 * other video control request.
2028 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2032 uvc_video_clock_reset(stream);
2034 if (!uvc_queue_streaming(&stream->queue))
2037 ret = uvc_commit_video(stream, &stream->ctrl);
2041 return uvc_video_start_transfer(stream, GFP_NOIO);
2044 /* ------------------------------------------------------------------------
2049 * Initialize the UVC video device by switching to alternate setting 0 and
2050 * retrieve the default format.
2052 * Some cameras (namely the Fuji Finepix) set the format and frame
2053 * indexes to zero. The UVC standard doesn't clearly make this a spec
2054 * violation, so try to silently fix the values if possible.
2056 * This function is called before registering the device with V4L.
2058 int uvc_video_init(struct uvc_streaming *stream)
2060 struct uvc_streaming_control *probe = &stream->ctrl;
2061 struct uvc_format *format = NULL;
2062 struct uvc_frame *frame = NULL;
2063 struct uvc_urb *uvc_urb;
2067 if (stream->nformats == 0) {
2068 dev_info(&stream->intf->dev,
2069 "No supported video formats found.\n");
2073 atomic_set(&stream->active, 0);
2075 /* Alternate setting 0 should be the default, yet the XBox Live Vision
2076 * Cam (and possibly other devices) crash or otherwise misbehave if
2077 * they don't receive a SET_INTERFACE request before any other video
2080 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2082 /* Set the streaming probe control with default streaming parameters
2083 * retrieved from the device. Webcams that don't support GET_DEF
2084 * requests on the probe control will just keep their current streaming
2087 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
2088 uvc_set_video_ctrl(stream, probe, 1);
2090 /* Initialize the streaming parameters with the probe control current
2091 * value. This makes sure SET_CUR requests on the streaming commit
2092 * control will always use values retrieved from a successful GET_CUR
2093 * request on the probe control, as required by the UVC specification.
2095 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
2099 /* Check if the default format descriptor exists. Use the first
2100 * available format otherwise.
2102 for (i = stream->nformats; i > 0; --i) {
2103 format = &stream->format[i-1];
2104 if (format->index == probe->bFormatIndex)
2108 if (format->nframes == 0) {
2109 dev_info(&stream->intf->dev,
2110 "No frame descriptor found for the default format.\n");
2114 /* Zero bFrameIndex might be correct. Stream-based formats (including
2115 * MPEG-2 TS and DV) do not support frames but have a dummy frame
2116 * descriptor with bFrameIndex set to zero. If the default frame
2117 * descriptor is not found, use the first available frame.
2119 for (i = format->nframes; i > 0; --i) {
2120 frame = &format->frame[i-1];
2121 if (frame->bFrameIndex == probe->bFrameIndex)
2125 probe->bFormatIndex = format->index;
2126 probe->bFrameIndex = frame->bFrameIndex;
2128 stream->def_format = format;
2129 stream->cur_format = format;
2130 stream->cur_frame = frame;
2132 /* Select the video decoding function */
2133 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2134 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
2135 stream->decode = uvc_video_decode_isight;
2136 else if (stream->intf->num_altsetting > 1)
2137 stream->decode = uvc_video_decode_isoc;
2139 stream->decode = uvc_video_decode_bulk;
2141 if (stream->intf->num_altsetting == 1)
2142 stream->decode = uvc_video_encode_bulk;
2144 dev_info(&stream->intf->dev,
2145 "Isochronous endpoints are not supported for video output devices.\n");
2150 /* Prepare asynchronous work items. */
2151 for_each_uvc_urb(uvc_urb, stream)
2152 INIT_WORK(&uvc_urb->work, uvc_video_copy_data_work);
2157 int uvc_video_start_streaming(struct uvc_streaming *stream)
2161 ret = uvc_video_clock_init(stream);
2165 /* Commit the streaming parameters. */
2166 ret = uvc_commit_video(stream, &stream->ctrl);
2170 ret = uvc_video_start_transfer(stream, GFP_KERNEL);
2177 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2179 uvc_video_clock_cleanup(stream);
2184 void uvc_video_stop_streaming(struct uvc_streaming *stream)
2186 uvc_video_stop_transfer(stream, 1);
2188 if (stream->intf->num_altsetting > 1) {
2189 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2191 /* UVC doesn't specify how to inform a bulk-based device
2192 * when the video stream is stopped. Windows sends a
2193 * CLEAR_FEATURE(HALT) request to the video streaming
2194 * bulk endpoint, mimic the same behaviour.
2196 unsigned int epnum = stream->header.bEndpointAddress
2197 & USB_ENDPOINT_NUMBER_MASK;
2198 unsigned int dir = stream->header.bEndpointAddress
2199 & USB_ENDPOINT_DIR_MASK;
2202 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
2203 usb_clear_halt(stream->dev->udev, pipe);
2206 uvc_video_clock_cleanup(stream);