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 struct uvc_format *format = NULL;
131 struct uvc_frame *frame = NULL;
134 for (i = 0; i < stream->nformats; ++i) {
135 if (stream->format[i].index == ctrl->bFormatIndex) {
136 format = &stream->format[i];
144 for (i = 0; i < format->nframes; ++i) {
145 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
146 frame = &format->frame[i];
154 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
155 (ctrl->dwMaxVideoFrameSize == 0 &&
156 stream->dev->uvc_version < 0x0110))
157 ctrl->dwMaxVideoFrameSize =
158 frame->dwMaxVideoFrameBufferSize;
160 /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
161 * compute the bandwidth on 16 bits and erroneously sign-extend it to
162 * 32 bits, resulting in a huge bandwidth value. Detect and fix that
163 * condition by setting the 16 MSBs to 0 when they're all equal to 1.
165 if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
166 ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
168 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
169 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
170 stream->intf->num_altsetting > 1) {
174 interval = (ctrl->dwFrameInterval > 100000)
175 ? ctrl->dwFrameInterval
176 : frame->dwFrameInterval[0];
178 /* Compute a bandwidth estimation by multiplying the frame
179 * size by the number of video frames per second, divide the
180 * result by the number of USB frames (or micro-frames for
181 * high-speed devices) per second and add the UVC header size
182 * (assumed to be 12 bytes long).
184 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
185 bandwidth *= 10000000 / interval + 1;
187 if (stream->dev->udev->speed == USB_SPEED_HIGH)
191 /* The bandwidth estimate is too low for many cameras. Don't use
192 * maximum packet sizes lower than 1024 bytes to try and work
193 * around the problem. According to measurements done on two
194 * different camera models, the value is high enough to get most
195 * resolutions working while not preventing two simultaneous
196 * VGA streams at 15 fps.
198 bandwidth = max_t(u32, bandwidth, 1024);
200 ctrl->dwMaxPayloadTransferSize = bandwidth;
204 static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
207 * Return the size of the video probe and commit controls, which depends
208 * on the protocol version.
210 if (stream->dev->uvc_version < 0x0110)
212 else if (stream->dev->uvc_version < 0x0150)
218 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
219 struct uvc_streaming_control *ctrl, int probe, u8 query)
221 u16 size = uvc_video_ctrl_size(stream);
225 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
226 query == UVC_GET_DEF)
229 data = kmalloc(size, GFP_KERNEL);
233 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
234 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
235 size, uvc_timeout_param);
237 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
238 /* Some cameras, mostly based on Bison Electronics chipsets,
239 * answer a GET_MIN or GET_MAX request with the wCompQuality
242 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
243 "compliance - GET_MIN/MAX(PROBE) incorrectly "
244 "supported. Enabling workaround.\n");
245 memset(ctrl, 0, sizeof(*ctrl));
246 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
249 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
250 /* Many cameras don't support the GET_DEF request on their
251 * video probe control. Warn once and return, the caller will
252 * fall back to GET_CUR.
254 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
255 "compliance - GET_DEF(PROBE) not supported. "
256 "Enabling workaround.\n");
259 } else if (ret != size) {
260 dev_err(&stream->intf->dev,
261 "Failed to query (%u) UVC %s control : %d (exp. %u).\n",
262 query, probe ? "probe" : "commit", ret, size);
267 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
268 ctrl->bFormatIndex = data[2];
269 ctrl->bFrameIndex = data[3];
270 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
271 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
272 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
273 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
274 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
275 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
276 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
277 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
280 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
281 ctrl->bmFramingInfo = data[30];
282 ctrl->bPreferedVersion = data[31];
283 ctrl->bMinVersion = data[32];
284 ctrl->bMaxVersion = data[33];
286 ctrl->dwClockFrequency = stream->dev->clock_frequency;
287 ctrl->bmFramingInfo = 0;
288 ctrl->bPreferedVersion = 0;
289 ctrl->bMinVersion = 0;
290 ctrl->bMaxVersion = 0;
293 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
294 * dwMaxPayloadTransferSize fields. Try to get the value from the
295 * format and frame descriptors.
297 uvc_fixup_video_ctrl(stream, ctrl);
305 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
306 struct uvc_streaming_control *ctrl, int probe)
308 u16 size = uvc_video_ctrl_size(stream);
312 data = kzalloc(size, GFP_KERNEL);
316 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
317 data[2] = ctrl->bFormatIndex;
318 data[3] = ctrl->bFrameIndex;
319 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
320 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
321 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
322 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
323 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
324 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
325 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
326 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
329 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
330 data[30] = ctrl->bmFramingInfo;
331 data[31] = ctrl->bPreferedVersion;
332 data[32] = ctrl->bMinVersion;
333 data[33] = ctrl->bMaxVersion;
336 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
337 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
338 size, uvc_timeout_param);
340 dev_err(&stream->intf->dev,
341 "Failed to set UVC %s control : %d (exp. %u).\n",
342 probe ? "probe" : "commit", ret, size);
350 int uvc_probe_video(struct uvc_streaming *stream,
351 struct uvc_streaming_control *probe)
353 struct uvc_streaming_control probe_min, probe_max;
358 /* Perform probing. The device should adjust the requested values
359 * according to its capabilities. However, some devices, namely the
360 * first generation UVC Logitech webcams, don't implement the Video
361 * Probe control properly, and just return the needed bandwidth. For
362 * that reason, if the needed bandwidth exceeds the maximum available
363 * bandwidth, try to lower the quality.
365 ret = uvc_set_video_ctrl(stream, probe, 1);
369 /* Get the minimum and maximum values for compression settings. */
370 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
371 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
374 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
378 probe->wCompQuality = probe_max.wCompQuality;
381 for (i = 0; i < 2; ++i) {
382 ret = uvc_set_video_ctrl(stream, probe, 1);
385 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
389 if (stream->intf->num_altsetting == 1)
392 bandwidth = probe->dwMaxPayloadTransferSize;
393 if (bandwidth <= stream->maxpsize)
396 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
401 /* TODO: negotiate compression parameters */
402 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
403 probe->wPFrameRate = probe_min.wPFrameRate;
404 probe->wCompQuality = probe_max.wCompQuality;
405 probe->wCompWindowSize = probe_min.wCompWindowSize;
412 static int uvc_commit_video(struct uvc_streaming *stream,
413 struct uvc_streaming_control *probe)
415 return uvc_set_video_ctrl(stream, probe, 0);
418 /* -----------------------------------------------------------------------------
419 * Clocks and timestamps
422 static inline ktime_t uvc_video_get_time(void)
424 if (uvc_clock_param == CLOCK_MONOTONIC)
427 return ktime_get_real();
431 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
432 const u8 *data, int len)
434 struct uvc_clock_sample *sample;
435 unsigned int header_size;
436 bool has_pts = false;
437 bool has_scr = false;
443 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
444 case UVC_STREAM_PTS | UVC_STREAM_SCR:
462 /* Check for invalid headers. */
463 if (len < header_size)
466 /* Extract the timestamps:
468 * - store the frame PTS in the buffer structure
469 * - if the SCR field is present, retrieve the host SOF counter and
470 * kernel timestamps and store them with the SCR STC and SOF fields
473 if (has_pts && buf != NULL)
474 buf->pts = get_unaligned_le32(&data[2]);
479 /* To limit the amount of data, drop SCRs with an SOF identical to the
482 dev_sof = get_unaligned_le16(&data[header_size - 2]);
483 if (dev_sof == stream->clock.last_sof)
486 stream->clock.last_sof = dev_sof;
488 host_sof = usb_get_current_frame_number(stream->dev->udev);
489 time = uvc_video_get_time();
491 /* The UVC specification allows device implementations that can't obtain
492 * the USB frame number to keep their own frame counters as long as they
493 * match the size and frequency of the frame number associated with USB
494 * SOF tokens. The SOF values sent by such devices differ from the USB
495 * SOF tokens by a fixed offset that needs to be estimated and accounted
496 * for to make timestamp recovery as accurate as possible.
498 * The offset is estimated the first time a device SOF value is received
499 * as the difference between the host and device SOF values. As the two
500 * SOF values can differ slightly due to transmission delays, consider
501 * that the offset is null if the difference is not higher than 10 ms
502 * (negative differences can not happen and are thus considered as an
503 * offset). The video commit control wDelay field should be used to
504 * compute a dynamic threshold instead of using a fixed 10 ms value, but
505 * devices don't report reliable wDelay values.
507 * See uvc_video_clock_host_sof() for an explanation regarding why only
508 * the 8 LSBs of the delta are kept.
510 if (stream->clock.sof_offset == (u16)-1) {
511 u16 delta_sof = (host_sof - dev_sof) & 255;
513 stream->clock.sof_offset = delta_sof;
515 stream->clock.sof_offset = 0;
518 dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
520 spin_lock_irqsave(&stream->clock.lock, flags);
522 sample = &stream->clock.samples[stream->clock.head];
523 sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
524 sample->dev_sof = dev_sof;
525 sample->host_sof = host_sof;
526 sample->host_time = time;
528 /* Update the sliding window head and count. */
529 stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
531 if (stream->clock.count < stream->clock.size)
532 stream->clock.count++;
534 spin_unlock_irqrestore(&stream->clock.lock, flags);
537 static void uvc_video_clock_reset(struct uvc_streaming *stream)
539 struct uvc_clock *clock = &stream->clock;
543 clock->last_sof = -1;
544 clock->sof_offset = -1;
547 static int uvc_video_clock_init(struct uvc_streaming *stream)
549 struct uvc_clock *clock = &stream->clock;
551 spin_lock_init(&clock->lock);
554 clock->samples = kmalloc_array(clock->size, sizeof(*clock->samples),
556 if (clock->samples == NULL)
559 uvc_video_clock_reset(stream);
564 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
566 kfree(stream->clock.samples);
567 stream->clock.samples = NULL;
571 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
573 * Host SOF counters reported by usb_get_current_frame_number() usually don't
574 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
575 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
576 * controller and its configuration.
578 * We thus need to recover the SOF value corresponding to the host frame number.
579 * As the device and host frame numbers are sampled in a short interval, the
580 * difference between their values should be equal to a small delta plus an
581 * integer multiple of 256 caused by the host frame number limited precision.
583 * To obtain the recovered host SOF value, compute the small delta by masking
584 * the high bits of the host frame counter and device SOF difference and add it
585 * to the device SOF value.
587 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
589 /* The delta value can be negative. */
592 delta_sof = (sample->host_sof - sample->dev_sof) & 255;
594 return (sample->dev_sof + delta_sof) & 2047;
598 * uvc_video_clock_update - Update the buffer timestamp
600 * This function converts the buffer PTS timestamp to the host clock domain by
601 * going through the USB SOF clock domain and stores the result in the V4L2
602 * buffer timestamp field.
604 * The relationship between the device clock and the host clock isn't known.
605 * However, the device and the host share the common USB SOF clock which can be
606 * used to recover that relationship.
608 * The relationship between the device clock and the USB SOF clock is considered
609 * to be linear over the clock samples sliding window and is given by
613 * Several methods to compute the slope (m) and intercept (p) can be used. As
614 * the clock drift should be small compared to the sliding window size, we
615 * assume that the line that goes through the points at both ends of the window
616 * is a good approximation. Naming those points P1 and P2, we get
618 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
619 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
623 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
625 * to avoid losing precision in the division. Similarly, the host timestamp is
628 * TS = ((TS2 - TS1) * SOF + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
630 * SOF values are coded on 11 bits by USB. We extend their precision with 16
631 * decimal bits, leading to a 11.16 coding.
633 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
634 * be normalized using the nominal device clock frequency reported through the
637 * Both the PTS/STC and SOF counters roll over, after a fixed but device
638 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
639 * sliding window size is smaller than the rollover period, differences computed
640 * on unsigned integers will produce the correct result. However, the p term in
641 * the linear relations will be miscomputed.
643 * To fix the issue, we subtract a constant from the PTS and STC values to bring
644 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
645 * the 32 bit range without any rollover.
647 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
648 * computed by (1) will never be smaller than 0. This offset is then compensated
649 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
650 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
651 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
652 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
653 * SOF value at the end of the sliding window.
655 * Finally we subtract a constant from the host timestamps to bring the first
656 * timestamp of the sliding window to 1s.
658 void uvc_video_clock_update(struct uvc_streaming *stream,
659 struct vb2_v4l2_buffer *vbuf,
660 struct uvc_buffer *buf)
662 struct uvc_clock *clock = &stream->clock;
663 struct uvc_clock_sample *first;
664 struct uvc_clock_sample *last;
674 if (!uvc_hw_timestamps_param)
678 * We will get called from __vb2_queue_cancel() if there are buffers
679 * done but not dequeued by the user, but the sample array has already
680 * been released at that time. Just bail out in that case.
685 spin_lock_irqsave(&clock->lock, flags);
687 if (clock->count < clock->size)
690 first = &clock->samples[clock->head];
691 last = &clock->samples[(clock->head - 1) % clock->size];
693 /* First step, PTS to SOF conversion. */
694 delta_stc = buf->pts - (1UL << 31);
695 x1 = first->dev_stc - delta_stc;
696 x2 = last->dev_stc - delta_stc;
700 y1 = (first->dev_sof + 2048) << 16;
701 y2 = (last->dev_sof + 2048) << 16;
705 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
707 y = div_u64(y, x2 - x1);
711 uvc_dbg(stream->dev, CLOCK,
712 "%s: PTS %u y %llu.%06llu SOF %u.%06llu (x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
713 stream->dev->name, buf->pts,
714 y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
715 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
716 x1, x2, y1, y2, clock->sof_offset);
718 /* Second step, SOF to host clock conversion. */
719 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
720 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
727 y2 = (u32)ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
729 /* Interpolated and host SOF timestamps can wrap around at slightly
730 * different times. Handle this by adding or removing 2048 to or from
731 * the computed SOF value to keep it close to the SOF samples mean
734 mean = (x1 + x2) / 2;
735 if (mean - (1024 << 16) > sof)
737 else if (sof > mean + (1024 << 16))
740 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
742 y = div_u64(y, x2 - x1);
744 timestamp = ktime_to_ns(first->host_time) + y - y1;
746 uvc_dbg(stream->dev, CLOCK,
747 "%s: SOF %u.%06llu y %llu ts %llu buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
749 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
750 y, timestamp, vbuf->vb2_buf.timestamp,
751 x1, first->host_sof, first->dev_sof,
752 x2, last->host_sof, last->dev_sof, y1, y2);
754 /* Update the V4L2 buffer. */
755 vbuf->vb2_buf.timestamp = timestamp;
758 spin_unlock_irqrestore(&clock->lock, flags);
761 /* ------------------------------------------------------------------------
765 static void uvc_video_stats_decode(struct uvc_streaming *stream,
766 const u8 *data, int len)
768 unsigned int header_size;
769 bool has_pts = false;
770 bool has_scr = false;
775 if (stream->stats.stream.nb_frames == 0 &&
776 stream->stats.frame.nb_packets == 0)
777 stream->stats.stream.start_ts = ktime_get();
779 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
780 case UVC_STREAM_PTS | UVC_STREAM_SCR:
798 /* Check for invalid headers. */
799 if (len < header_size || data[0] < header_size) {
800 stream->stats.frame.nb_invalid++;
804 /* Extract the timestamps. */
806 pts = get_unaligned_le32(&data[2]);
809 scr_stc = get_unaligned_le32(&data[header_size - 6]);
810 scr_sof = get_unaligned_le16(&data[header_size - 2]);
813 /* Is PTS constant through the whole frame ? */
814 if (has_pts && stream->stats.frame.nb_pts) {
815 if (stream->stats.frame.pts != pts) {
816 stream->stats.frame.nb_pts_diffs++;
817 stream->stats.frame.last_pts_diff =
818 stream->stats.frame.nb_packets;
823 stream->stats.frame.nb_pts++;
824 stream->stats.frame.pts = pts;
827 /* Do all frames have a PTS in their first non-empty packet, or before
828 * their first empty packet ?
830 if (stream->stats.frame.size == 0) {
831 if (len > header_size)
832 stream->stats.frame.has_initial_pts = has_pts;
833 if (len == header_size && has_pts)
834 stream->stats.frame.has_early_pts = true;
837 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
838 if (has_scr && stream->stats.frame.nb_scr) {
839 if (stream->stats.frame.scr_stc != scr_stc)
840 stream->stats.frame.nb_scr_diffs++;
844 /* Expand the SOF counter to 32 bits and store its value. */
845 if (stream->stats.stream.nb_frames > 0 ||
846 stream->stats.frame.nb_scr > 0)
847 stream->stats.stream.scr_sof_count +=
848 (scr_sof - stream->stats.stream.scr_sof) % 2048;
849 stream->stats.stream.scr_sof = scr_sof;
851 stream->stats.frame.nb_scr++;
852 stream->stats.frame.scr_stc = scr_stc;
853 stream->stats.frame.scr_sof = scr_sof;
855 if (scr_sof < stream->stats.stream.min_sof)
856 stream->stats.stream.min_sof = scr_sof;
857 if (scr_sof > stream->stats.stream.max_sof)
858 stream->stats.stream.max_sof = scr_sof;
861 /* Record the first non-empty packet number. */
862 if (stream->stats.frame.size == 0 && len > header_size)
863 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
865 /* Update the frame size. */
866 stream->stats.frame.size += len - header_size;
868 /* Update the packets counters. */
869 stream->stats.frame.nb_packets++;
870 if (len <= header_size)
871 stream->stats.frame.nb_empty++;
873 if (data[1] & UVC_STREAM_ERR)
874 stream->stats.frame.nb_errors++;
877 static void uvc_video_stats_update(struct uvc_streaming *stream)
879 struct uvc_stats_frame *frame = &stream->stats.frame;
881 uvc_dbg(stream->dev, STATS,
882 "frame %u stats: %u/%u/%u packets, %u/%u/%u pts (%searly %sinitial), %u/%u scr, last pts/stc/sof %u/%u/%u\n",
883 stream->sequence, frame->first_data,
884 frame->nb_packets - frame->nb_empty, frame->nb_packets,
885 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
886 frame->has_early_pts ? "" : "!",
887 frame->has_initial_pts ? "" : "!",
888 frame->nb_scr_diffs, frame->nb_scr,
889 frame->pts, frame->scr_stc, frame->scr_sof);
891 stream->stats.stream.nb_frames++;
892 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
893 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
894 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
895 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
897 if (frame->has_early_pts)
898 stream->stats.stream.nb_pts_early++;
899 if (frame->has_initial_pts)
900 stream->stats.stream.nb_pts_initial++;
901 if (frame->last_pts_diff <= frame->first_data)
902 stream->stats.stream.nb_pts_constant++;
903 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
904 stream->stats.stream.nb_scr_count_ok++;
905 if (frame->nb_scr_diffs + 1 == frame->nb_scr)
906 stream->stats.stream.nb_scr_diffs_ok++;
908 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
911 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
914 unsigned int scr_sof_freq;
915 unsigned int duration;
918 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
919 * frequency this will not overflow before more than 1h.
921 duration = ktime_ms_delta(stream->stats.stream.stop_ts,
922 stream->stats.stream.start_ts);
924 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
929 count += scnprintf(buf + count, size - count,
930 "frames: %u\npackets: %u\nempty: %u\n"
931 "errors: %u\ninvalid: %u\n",
932 stream->stats.stream.nb_frames,
933 stream->stats.stream.nb_packets,
934 stream->stats.stream.nb_empty,
935 stream->stats.stream.nb_errors,
936 stream->stats.stream.nb_invalid);
937 count += scnprintf(buf + count, size - count,
938 "pts: %u early, %u initial, %u ok\n",
939 stream->stats.stream.nb_pts_early,
940 stream->stats.stream.nb_pts_initial,
941 stream->stats.stream.nb_pts_constant);
942 count += scnprintf(buf + count, size - count,
943 "scr: %u count ok, %u diff ok\n",
944 stream->stats.stream.nb_scr_count_ok,
945 stream->stats.stream.nb_scr_diffs_ok);
946 count += scnprintf(buf + count, size - count,
947 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
948 stream->stats.stream.min_sof,
949 stream->stats.stream.max_sof,
950 scr_sof_freq / 1000, scr_sof_freq % 1000);
955 static void uvc_video_stats_start(struct uvc_streaming *stream)
957 memset(&stream->stats, 0, sizeof(stream->stats));
958 stream->stats.stream.min_sof = 2048;
961 static void uvc_video_stats_stop(struct uvc_streaming *stream)
963 stream->stats.stream.stop_ts = ktime_get();
966 /* ------------------------------------------------------------------------
970 /* Video payload decoding is handled by uvc_video_decode_start(),
971 * uvc_video_decode_data() and uvc_video_decode_end().
973 * uvc_video_decode_start is called with URB data at the start of a bulk or
974 * isochronous payload. It processes header data and returns the header size
975 * in bytes if successful. If an error occurs, it returns a negative error
976 * code. The following error codes have special meanings.
978 * - EAGAIN informs the caller that the current video buffer should be marked
979 * as done, and that the function should be called again with the same data
980 * and a new video buffer. This is used when end of frame conditions can be
981 * reliably detected at the beginning of the next frame only.
983 * If an error other than -EAGAIN is returned, the caller will drop the current
984 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
985 * made until the next payload. -ENODATA can be used to drop the current
986 * payload if no other error code is appropriate.
988 * uvc_video_decode_data is called for every URB with URB data. It copies the
989 * data to the video buffer.
991 * uvc_video_decode_end is called with header data at the end of a bulk or
992 * isochronous payload. It performs any additional header data processing and
993 * returns 0 or a negative error code if an error occurred. As header data have
994 * already been processed by uvc_video_decode_start, this functions isn't
995 * required to perform sanity checks a second time.
997 * For isochronous transfers where a payload is always transferred in a single
998 * URB, the three functions will be called in a row.
1000 * To let the decoder process header data and update its internal state even
1001 * when no video buffer is available, uvc_video_decode_start must be prepared
1002 * to be called with a NULL buf parameter. uvc_video_decode_data and
1003 * uvc_video_decode_end will never be called with a NULL buffer.
1005 static int uvc_video_decode_start(struct uvc_streaming *stream,
1006 struct uvc_buffer *buf, const u8 *data, int len)
1011 * - packet must be at least 2 bytes long
1012 * - bHeaderLength value must be at least 2 bytes (see above)
1013 * - bHeaderLength value can't be larger than the packet size.
1015 if (len < 2 || data[0] < 2 || data[0] > len) {
1016 stream->stats.frame.nb_invalid++;
1020 fid = data[1] & UVC_STREAM_FID;
1022 /* Increase the sequence number regardless of any buffer states, so
1023 * that discontinuous sequence numbers always indicate lost frames.
1025 if (stream->last_fid != fid) {
1027 if (stream->sequence)
1028 uvc_video_stats_update(stream);
1031 uvc_video_clock_decode(stream, buf, data, len);
1032 uvc_video_stats_decode(stream, data, len);
1034 /* Store the payload FID bit and return immediately when the buffer is
1038 stream->last_fid = fid;
1042 /* Mark the buffer as bad if the error bit is set. */
1043 if (data[1] & UVC_STREAM_ERR) {
1044 uvc_dbg(stream->dev, FRAME,
1045 "Marking buffer as bad (error bit set)\n");
1049 /* Synchronize to the input stream by waiting for the FID bit to be
1050 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1051 * stream->last_fid is initialized to -1, so the first isochronous
1052 * frame will always be in sync.
1054 * If the device doesn't toggle the FID bit, invert stream->last_fid
1055 * when the EOF bit is set to force synchronisation on the next packet.
1057 if (buf->state != UVC_BUF_STATE_ACTIVE) {
1058 if (fid == stream->last_fid) {
1059 uvc_dbg(stream->dev, FRAME,
1060 "Dropping payload (out of sync)\n");
1061 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1062 (data[1] & UVC_STREAM_EOF))
1063 stream->last_fid ^= UVC_STREAM_FID;
1067 buf->buf.field = V4L2_FIELD_NONE;
1068 buf->buf.sequence = stream->sequence;
1069 buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time());
1071 /* TODO: Handle PTS and SCR. */
1072 buf->state = UVC_BUF_STATE_ACTIVE;
1075 /* Mark the buffer as done if we're at the beginning of a new frame.
1076 * End of frame detection is better implemented by checking the EOF
1077 * bit (FID bit toggling is delayed by one frame compared to the EOF
1078 * bit), but some devices don't set the bit at end of frame (and the
1079 * last payload can be lost anyway). We thus must check if the FID has
1082 * stream->last_fid is initialized to -1, so the first isochronous
1083 * frame will never trigger an end of frame detection.
1085 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1086 * as it doesn't make sense to return an empty buffer. This also
1087 * avoids detecting end of frame conditions at FID toggling if the
1088 * previous payload had the EOF bit set.
1090 if (fid != stream->last_fid && buf->bytesused != 0) {
1091 uvc_dbg(stream->dev, FRAME,
1092 "Frame complete (FID bit toggled)\n");
1093 buf->state = UVC_BUF_STATE_READY;
1097 stream->last_fid = fid;
1102 static inline enum dma_data_direction uvc_stream_dir(
1103 struct uvc_streaming *stream)
1105 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1106 return DMA_FROM_DEVICE;
1108 return DMA_TO_DEVICE;
1111 static inline struct device *uvc_stream_to_dmadev(struct uvc_streaming *stream)
1113 return bus_to_hcd(stream->dev->udev->bus)->self.sysdev;
1116 static int uvc_submit_urb(struct uvc_urb *uvc_urb, gfp_t mem_flags)
1119 dma_sync_sgtable_for_device(uvc_stream_to_dmadev(uvc_urb->stream),
1121 uvc_stream_dir(uvc_urb->stream));
1122 return usb_submit_urb(uvc_urb->urb, mem_flags);
1126 * uvc_video_decode_data_work: Asynchronous memcpy processing
1128 * Copy URB data to video buffers in process context, releasing buffer
1129 * references and requeuing the URB when done.
1131 static void uvc_video_copy_data_work(struct work_struct *work)
1133 struct uvc_urb *uvc_urb = container_of(work, struct uvc_urb, work);
1137 for (i = 0; i < uvc_urb->async_operations; i++) {
1138 struct uvc_copy_op *op = &uvc_urb->copy_operations[i];
1140 memcpy(op->dst, op->src, op->len);
1142 /* Release reference taken on this buffer. */
1143 uvc_queue_buffer_release(op->buf);
1146 ret = uvc_submit_urb(uvc_urb, GFP_KERNEL);
1148 dev_err(&uvc_urb->stream->intf->dev,
1149 "Failed to resubmit video URB (%d).\n", ret);
1152 static void uvc_video_decode_data(struct uvc_urb *uvc_urb,
1153 struct uvc_buffer *buf, const u8 *data, int len)
1155 unsigned int active_op = uvc_urb->async_operations;
1156 struct uvc_copy_op *op = &uvc_urb->copy_operations[active_op];
1157 unsigned int maxlen;
1162 maxlen = buf->length - buf->bytesused;
1164 /* Take a buffer reference for async work. */
1165 kref_get(&buf->ref);
1169 op->dst = buf->mem + buf->bytesused;
1170 op->len = min_t(unsigned int, len, maxlen);
1172 buf->bytesused += op->len;
1174 /* Complete the current frame if the buffer size was exceeded. */
1176 uvc_dbg(uvc_urb->stream->dev, FRAME,
1177 "Frame complete (overflow)\n");
1179 buf->state = UVC_BUF_STATE_READY;
1182 uvc_urb->async_operations++;
1185 static void uvc_video_decode_end(struct uvc_streaming *stream,
1186 struct uvc_buffer *buf, const u8 *data, int len)
1188 /* Mark the buffer as done if the EOF marker is set. */
1189 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1190 uvc_dbg(stream->dev, FRAME, "Frame complete (EOF found)\n");
1192 uvc_dbg(stream->dev, FRAME, "EOF in empty payload\n");
1193 buf->state = UVC_BUF_STATE_READY;
1194 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1195 stream->last_fid ^= UVC_STREAM_FID;
1199 /* Video payload encoding is handled by uvc_video_encode_header() and
1200 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1202 * uvc_video_encode_header is called at the start of a payload. It adds header
1203 * data to the transfer buffer and returns the header size. As the only known
1204 * UVC output device transfers a whole frame in a single payload, the EOF bit
1205 * is always set in the header.
1207 * uvc_video_encode_data is called for every URB and copies the data from the
1208 * video buffer to the transfer buffer.
1210 static int uvc_video_encode_header(struct uvc_streaming *stream,
1211 struct uvc_buffer *buf, u8 *data, int len)
1213 data[0] = 2; /* Header length */
1214 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1215 | (stream->last_fid & UVC_STREAM_FID);
1219 static int uvc_video_encode_data(struct uvc_streaming *stream,
1220 struct uvc_buffer *buf, u8 *data, int len)
1222 struct uvc_video_queue *queue = &stream->queue;
1223 unsigned int nbytes;
1226 /* Copy video data to the URB buffer. */
1227 mem = buf->mem + queue->buf_used;
1228 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1229 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1231 memcpy(data, mem, nbytes);
1233 queue->buf_used += nbytes;
1238 /* ------------------------------------------------------------------------
1243 * Additionally to the payload headers we also want to provide the user with USB
1244 * Frame Numbers and system time values. The resulting buffer is thus composed
1245 * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame
1246 * Number, and a copy of the payload header.
1248 * Ideally we want to capture all payload headers for each frame. However, their
1249 * number is unknown and unbound. We thus drop headers that contain no vendor
1250 * data and that either contain no SCR value or an SCR value identical to the
1253 static void uvc_video_decode_meta(struct uvc_streaming *stream,
1254 struct uvc_buffer *meta_buf,
1255 const u8 *mem, unsigned int length)
1257 struct uvc_meta_buf *meta;
1259 bool has_pts, has_scr;
1260 unsigned long flags;
1265 if (!meta_buf || length == 2)
1268 if (meta_buf->length - meta_buf->bytesused <
1269 length + sizeof(meta->ns) + sizeof(meta->sof)) {
1270 meta_buf->error = 1;
1274 has_pts = mem[1] & UVC_STREAM_PTS;
1275 has_scr = mem[1] & UVC_STREAM_SCR;
1287 if (stream->meta.format == V4L2_META_FMT_UVC)
1290 if (length == len_std && (!has_scr ||
1291 !memcmp(scr, stream->clock.last_scr, 6)))
1294 meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
1295 local_irq_save(flags);
1296 time = uvc_video_get_time();
1297 sof = usb_get_current_frame_number(stream->dev->udev);
1298 local_irq_restore(flags);
1299 put_unaligned(ktime_to_ns(time), &meta->ns);
1300 put_unaligned(sof, &meta->sof);
1303 memcpy(stream->clock.last_scr, scr, 6);
1305 memcpy(&meta->length, mem, length);
1306 meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);
1308 uvc_dbg(stream->dev, FRAME,
1309 "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
1310 __func__, ktime_to_ns(time), meta->sof, meta->length,
1312 has_pts ? *(u32 *)meta->buf : 0,
1313 has_scr ? *(u32 *)scr : 0,
1314 has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
1317 /* ------------------------------------------------------------------------
1322 * Set error flag for incomplete buffer.
1324 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1325 struct uvc_buffer *buf)
1327 if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1328 !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1333 * Completion handler for video URBs.
1336 static void uvc_video_next_buffers(struct uvc_streaming *stream,
1337 struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
1339 uvc_video_validate_buffer(stream, *video_buf);
1342 struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
1343 const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;
1345 vb2_meta->sequence = vb2_video->sequence;
1346 vb2_meta->field = vb2_video->field;
1347 vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;
1349 (*meta_buf)->state = UVC_BUF_STATE_READY;
1350 if (!(*meta_buf)->error)
1351 (*meta_buf)->error = (*video_buf)->error;
1352 *meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
1355 *video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
1358 static void uvc_video_decode_isoc(struct uvc_urb *uvc_urb,
1359 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1361 struct urb *urb = uvc_urb->urb;
1362 struct uvc_streaming *stream = uvc_urb->stream;
1366 for (i = 0; i < urb->number_of_packets; ++i) {
1367 if (urb->iso_frame_desc[i].status < 0) {
1368 uvc_dbg(stream->dev, FRAME,
1369 "USB isochronous frame lost (%d)\n",
1370 urb->iso_frame_desc[i].status);
1371 /* Mark the buffer as faulty. */
1377 /* Decode the payload header. */
1378 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1380 ret = uvc_video_decode_start(stream, buf, mem,
1381 urb->iso_frame_desc[i].actual_length);
1383 uvc_video_next_buffers(stream, &buf, &meta_buf);
1384 } while (ret == -EAGAIN);
1389 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1391 /* Decode the payload data. */
1392 uvc_video_decode_data(uvc_urb, buf, mem + ret,
1393 urb->iso_frame_desc[i].actual_length - ret);
1395 /* Process the header again. */
1396 uvc_video_decode_end(stream, buf, mem,
1397 urb->iso_frame_desc[i].actual_length);
1399 if (buf->state == UVC_BUF_STATE_READY)
1400 uvc_video_next_buffers(stream, &buf, &meta_buf);
1404 static void uvc_video_decode_bulk(struct uvc_urb *uvc_urb,
1405 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1407 struct urb *urb = uvc_urb->urb;
1408 struct uvc_streaming *stream = uvc_urb->stream;
1413 * Ignore ZLPs if they're not part of a frame, otherwise process them
1414 * to trigger the end of payload detection.
1416 if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1419 mem = urb->transfer_buffer;
1420 len = urb->actual_length;
1421 stream->bulk.payload_size += len;
1423 /* If the URB is the first of its payload, decode and save the
1426 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1428 ret = uvc_video_decode_start(stream, buf, mem, len);
1430 uvc_video_next_buffers(stream, &buf, &meta_buf);
1431 } while (ret == -EAGAIN);
1433 /* If an error occurred skip the rest of the payload. */
1434 if (ret < 0 || buf == NULL) {
1435 stream->bulk.skip_payload = 1;
1437 memcpy(stream->bulk.header, mem, ret);
1438 stream->bulk.header_size = ret;
1440 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1447 /* The buffer queue might have been cancelled while a bulk transfer
1448 * was in progress, so we can reach here with buf equal to NULL. Make
1449 * sure buf is never dereferenced if NULL.
1452 /* Prepare video data for processing. */
1453 if (!stream->bulk.skip_payload && buf != NULL)
1454 uvc_video_decode_data(uvc_urb, buf, mem, len);
1456 /* Detect the payload end by a URB smaller than the maximum size (or
1457 * a payload size equal to the maximum) and process the header again.
1459 if (urb->actual_length < urb->transfer_buffer_length ||
1460 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1461 if (!stream->bulk.skip_payload && buf != NULL) {
1462 uvc_video_decode_end(stream, buf, stream->bulk.header,
1463 stream->bulk.payload_size);
1464 if (buf->state == UVC_BUF_STATE_READY)
1465 uvc_video_next_buffers(stream, &buf, &meta_buf);
1468 stream->bulk.header_size = 0;
1469 stream->bulk.skip_payload = 0;
1470 stream->bulk.payload_size = 0;
1474 static void uvc_video_encode_bulk(struct uvc_urb *uvc_urb,
1475 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1477 struct urb *urb = uvc_urb->urb;
1478 struct uvc_streaming *stream = uvc_urb->stream;
1480 u8 *mem = urb->transfer_buffer;
1481 int len = stream->urb_size, ret;
1484 urb->transfer_buffer_length = 0;
1488 /* If the URB is the first of its payload, add the header. */
1489 if (stream->bulk.header_size == 0) {
1490 ret = uvc_video_encode_header(stream, buf, mem, len);
1491 stream->bulk.header_size = ret;
1492 stream->bulk.payload_size += ret;
1497 /* Process video data. */
1498 ret = uvc_video_encode_data(stream, buf, mem, len);
1500 stream->bulk.payload_size += ret;
1503 if (buf->bytesused == stream->queue.buf_used ||
1504 stream->bulk.payload_size == stream->bulk.max_payload_size) {
1505 if (buf->bytesused == stream->queue.buf_used) {
1506 stream->queue.buf_used = 0;
1507 buf->state = UVC_BUF_STATE_READY;
1508 buf->buf.sequence = ++stream->sequence;
1509 uvc_queue_next_buffer(&stream->queue, buf);
1510 stream->last_fid ^= UVC_STREAM_FID;
1513 stream->bulk.header_size = 0;
1514 stream->bulk.payload_size = 0;
1517 urb->transfer_buffer_length = stream->urb_size - len;
1520 static void uvc_video_complete(struct urb *urb)
1522 struct uvc_urb *uvc_urb = urb->context;
1523 struct uvc_streaming *stream = uvc_urb->stream;
1524 struct uvc_video_queue *queue = &stream->queue;
1525 struct uvc_video_queue *qmeta = &stream->meta.queue;
1526 struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
1527 struct uvc_buffer *buf = NULL;
1528 struct uvc_buffer *buf_meta = NULL;
1529 unsigned long flags;
1532 switch (urb->status) {
1537 dev_warn(&stream->intf->dev,
1538 "Non-zero status (%d) in video completion handler.\n",
1541 case -ENOENT: /* usb_poison_urb() called. */
1545 case -ECONNRESET: /* usb_unlink_urb() called. */
1546 case -ESHUTDOWN: /* The endpoint is being disabled. */
1547 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1549 uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
1553 buf = uvc_queue_get_current_buffer(queue);
1556 spin_lock_irqsave(&qmeta->irqlock, flags);
1557 if (!list_empty(&qmeta->irqqueue))
1558 buf_meta = list_first_entry(&qmeta->irqqueue,
1559 struct uvc_buffer, queue);
1560 spin_unlock_irqrestore(&qmeta->irqlock, flags);
1563 /* Re-initialise the URB async work. */
1564 uvc_urb->async_operations = 0;
1566 /* Sync DMA and invalidate vmap range. */
1567 dma_sync_sgtable_for_cpu(uvc_stream_to_dmadev(uvc_urb->stream),
1568 uvc_urb->sgt, uvc_stream_dir(stream));
1569 invalidate_kernel_vmap_range(uvc_urb->buffer,
1570 uvc_urb->stream->urb_size);
1573 * Process the URB headers, and optionally queue expensive memcpy tasks
1574 * to be deferred to a work queue.
1576 stream->decode(uvc_urb, buf, buf_meta);
1578 /* If no async work is needed, resubmit the URB immediately. */
1579 if (!uvc_urb->async_operations) {
1580 ret = uvc_submit_urb(uvc_urb, GFP_ATOMIC);
1582 dev_err(&stream->intf->dev,
1583 "Failed to resubmit video URB (%d).\n", ret);
1587 queue_work(stream->async_wq, &uvc_urb->work);
1591 * Free transfer buffers.
1593 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1595 struct device *dma_dev = uvc_stream_to_dmadev(stream);
1596 struct uvc_urb *uvc_urb;
1598 for_each_uvc_urb(uvc_urb, stream) {
1599 if (!uvc_urb->buffer)
1602 dma_vunmap_noncontiguous(dma_dev, uvc_urb->buffer);
1603 dma_free_noncontiguous(dma_dev, stream->urb_size, uvc_urb->sgt,
1604 uvc_stream_dir(stream));
1606 uvc_urb->buffer = NULL;
1607 uvc_urb->sgt = NULL;
1610 stream->urb_size = 0;
1613 static bool uvc_alloc_urb_buffer(struct uvc_streaming *stream,
1614 struct uvc_urb *uvc_urb, gfp_t gfp_flags)
1616 struct device *dma_dev = uvc_stream_to_dmadev(stream);
1618 uvc_urb->sgt = dma_alloc_noncontiguous(dma_dev, stream->urb_size,
1619 uvc_stream_dir(stream),
1623 uvc_urb->dma = uvc_urb->sgt->sgl->dma_address;
1625 uvc_urb->buffer = dma_vmap_noncontiguous(dma_dev, stream->urb_size,
1627 if (!uvc_urb->buffer) {
1628 dma_free_noncontiguous(dma_dev, stream->urb_size,
1630 uvc_stream_dir(stream));
1631 uvc_urb->sgt = NULL;
1639 * Allocate transfer buffers. This function can be called with buffers
1640 * already allocated when resuming from suspend, in which case it will
1641 * return without touching the buffers.
1643 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1644 * system is too low on memory try successively smaller numbers of packets
1645 * until allocation succeeds.
1647 * Return the number of allocated packets on success or 0 when out of memory.
1649 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1650 unsigned int size, unsigned int psize, gfp_t gfp_flags)
1652 unsigned int npackets;
1655 /* Buffers are already allocated, bail out. */
1656 if (stream->urb_size)
1657 return stream->urb_size / psize;
1659 /* Compute the number of packets. Bulk endpoints might transfer UVC
1660 * payloads across multiple URBs.
1662 npackets = DIV_ROUND_UP(size, psize);
1663 if (npackets > UVC_MAX_PACKETS)
1664 npackets = UVC_MAX_PACKETS;
1666 /* Retry allocations until one succeed. */
1667 for (; npackets > 1; npackets /= 2) {
1668 stream->urb_size = psize * npackets;
1670 for (i = 0; i < UVC_URBS; ++i) {
1671 struct uvc_urb *uvc_urb = &stream->uvc_urb[i];
1673 if (!uvc_alloc_urb_buffer(stream, uvc_urb, gfp_flags)) {
1674 uvc_free_urb_buffers(stream);
1678 uvc_urb->stream = stream;
1681 if (i == UVC_URBS) {
1682 uvc_dbg(stream->dev, VIDEO,
1683 "Allocated %u URB buffers of %ux%u bytes each\n",
1684 UVC_URBS, npackets, psize);
1689 uvc_dbg(stream->dev, VIDEO,
1690 "Failed to allocate URB buffers (%u bytes per packet)\n",
1696 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1698 static void uvc_video_stop_transfer(struct uvc_streaming *stream,
1701 struct uvc_urb *uvc_urb;
1703 uvc_video_stats_stop(stream);
1706 * We must poison the URBs rather than kill them to ensure that even
1707 * after the completion handler returns, any asynchronous workqueues
1708 * will be prevented from resubmitting the URBs.
1710 for_each_uvc_urb(uvc_urb, stream)
1711 usb_poison_urb(uvc_urb->urb);
1713 flush_workqueue(stream->async_wq);
1715 for_each_uvc_urb(uvc_urb, stream) {
1716 usb_free_urb(uvc_urb->urb);
1717 uvc_urb->urb = NULL;
1721 uvc_free_urb_buffers(stream);
1725 * Compute the maximum number of bytes per interval for an endpoint.
1727 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1728 struct usb_host_endpoint *ep)
1733 switch (dev->speed) {
1734 case USB_SPEED_SUPER:
1735 case USB_SPEED_SUPER_PLUS:
1736 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1737 case USB_SPEED_HIGH:
1738 psize = usb_endpoint_maxp(&ep->desc);
1739 mult = usb_endpoint_maxp_mult(&ep->desc);
1740 return psize * mult;
1741 case USB_SPEED_WIRELESS:
1742 psize = usb_endpoint_maxp(&ep->desc);
1745 psize = usb_endpoint_maxp(&ep->desc);
1751 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1752 * is given by the endpoint.
1754 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1755 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1758 struct uvc_urb *uvc_urb;
1759 unsigned int npackets, i;
1763 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1764 size = stream->ctrl.dwMaxVideoFrameSize;
1766 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1770 size = npackets * psize;
1772 for_each_uvc_urb(uvc_urb, stream) {
1773 urb = usb_alloc_urb(npackets, gfp_flags);
1775 uvc_video_stop_transfer(stream, 1);
1779 urb->dev = stream->dev->udev;
1780 urb->context = uvc_urb;
1781 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1782 ep->desc.bEndpointAddress);
1783 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1784 urb->transfer_dma = uvc_urb->dma;
1785 urb->interval = ep->desc.bInterval;
1786 urb->transfer_buffer = uvc_urb->buffer;
1787 urb->complete = uvc_video_complete;
1788 urb->number_of_packets = npackets;
1789 urb->transfer_buffer_length = size;
1791 for (i = 0; i < npackets; ++i) {
1792 urb->iso_frame_desc[i].offset = i * psize;
1793 urb->iso_frame_desc[i].length = psize;
1803 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1804 * given by the endpoint.
1806 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1807 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1810 struct uvc_urb *uvc_urb;
1811 unsigned int npackets, pipe;
1815 psize = usb_endpoint_maxp(&ep->desc);
1816 size = stream->ctrl.dwMaxPayloadTransferSize;
1817 stream->bulk.max_payload_size = size;
1819 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1823 size = npackets * psize;
1825 if (usb_endpoint_dir_in(&ep->desc))
1826 pipe = usb_rcvbulkpipe(stream->dev->udev,
1827 ep->desc.bEndpointAddress);
1829 pipe = usb_sndbulkpipe(stream->dev->udev,
1830 ep->desc.bEndpointAddress);
1832 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1835 for_each_uvc_urb(uvc_urb, stream) {
1836 urb = usb_alloc_urb(0, gfp_flags);
1838 uvc_video_stop_transfer(stream, 1);
1842 usb_fill_bulk_urb(urb, stream->dev->udev, pipe, uvc_urb->buffer,
1843 size, uvc_video_complete, uvc_urb);
1844 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1845 urb->transfer_dma = uvc_urb->dma;
1854 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1856 static int uvc_video_start_transfer(struct uvc_streaming *stream,
1859 struct usb_interface *intf = stream->intf;
1860 struct usb_host_endpoint *ep;
1861 struct uvc_urb *uvc_urb;
1865 stream->sequence = -1;
1866 stream->last_fid = -1;
1867 stream->bulk.header_size = 0;
1868 stream->bulk.skip_payload = 0;
1869 stream->bulk.payload_size = 0;
1871 uvc_video_stats_start(stream);
1873 if (intf->num_altsetting > 1) {
1874 struct usb_host_endpoint *best_ep = NULL;
1875 unsigned int best_psize = UINT_MAX;
1876 unsigned int bandwidth;
1877 unsigned int altsetting;
1878 int intfnum = stream->intfnum;
1880 /* Isochronous endpoint, select the alternate setting. */
1881 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1883 if (bandwidth == 0) {
1884 uvc_dbg(stream->dev, VIDEO,
1885 "Device requested null bandwidth, defaulting to lowest\n");
1888 uvc_dbg(stream->dev, VIDEO,
1889 "Device requested %u B/frame bandwidth\n",
1893 for (i = 0; i < intf->num_altsetting; ++i) {
1894 struct usb_host_interface *alts;
1897 alts = &intf->altsetting[i];
1898 ep = uvc_find_endpoint(alts,
1899 stream->header.bEndpointAddress);
1903 /* Check if the bandwidth is high enough. */
1904 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1905 if (psize >= bandwidth && psize <= best_psize) {
1906 altsetting = alts->desc.bAlternateSetting;
1912 if (best_ep == NULL) {
1913 uvc_dbg(stream->dev, VIDEO,
1914 "No fast enough alt setting for requested bandwidth\n");
1918 uvc_dbg(stream->dev, VIDEO,
1919 "Selecting alternate setting %u (%u B/frame bandwidth)\n",
1920 altsetting, best_psize);
1922 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1926 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1928 /* Bulk endpoint, proceed to URB initialization. */
1929 ep = uvc_find_endpoint(&intf->altsetting[0],
1930 stream->header.bEndpointAddress);
1934 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1940 /* Submit the URBs. */
1941 for_each_uvc_urb(uvc_urb, stream) {
1942 ret = uvc_submit_urb(uvc_urb, gfp_flags);
1944 dev_err(&stream->intf->dev,
1945 "Failed to submit URB %u (%d).\n",
1946 uvc_urb_index(uvc_urb), ret);
1947 uvc_video_stop_transfer(stream, 1);
1952 /* The Logitech C920 temporarily forgets that it should not be adjusting
1953 * Exposure Absolute during init so restore controls to stored values.
1955 if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1956 uvc_ctrl_restore_values(stream->dev);
1961 /* --------------------------------------------------------------------------
1966 * Stop streaming without disabling the video queue.
1968 * To let userspace applications resume without trouble, we must not touch the
1969 * video buffers in any way. We mark the device as frozen to make sure the URB
1970 * completion handler won't try to cancel the queue when we kill the URBs.
1972 int uvc_video_suspend(struct uvc_streaming *stream)
1974 if (!uvc_queue_streaming(&stream->queue))
1978 uvc_video_stop_transfer(stream, 0);
1979 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1984 * Reconfigure the video interface and restart streaming if it was enabled
1987 * If an error occurs, disable the video queue. This will wake all pending
1988 * buffers, making sure userspace applications are notified of the problem
1989 * instead of waiting forever.
1991 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1995 /* If the bus has been reset on resume, set the alternate setting to 0.
1996 * This should be the default value, but some devices crash or otherwise
1997 * misbehave if they don't receive a SET_INTERFACE request before any
1998 * other video control request.
2001 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2005 uvc_video_clock_reset(stream);
2007 if (!uvc_queue_streaming(&stream->queue))
2010 ret = uvc_commit_video(stream, &stream->ctrl);
2014 return uvc_video_start_transfer(stream, GFP_NOIO);
2017 /* ------------------------------------------------------------------------
2022 * Initialize the UVC video device by switching to alternate setting 0 and
2023 * retrieve the default format.
2025 * Some cameras (namely the Fuji Finepix) set the format and frame
2026 * indexes to zero. The UVC standard doesn't clearly make this a spec
2027 * violation, so try to silently fix the values if possible.
2029 * This function is called before registering the device with V4L.
2031 int uvc_video_init(struct uvc_streaming *stream)
2033 struct uvc_streaming_control *probe = &stream->ctrl;
2034 struct uvc_format *format = NULL;
2035 struct uvc_frame *frame = NULL;
2036 struct uvc_urb *uvc_urb;
2040 if (stream->nformats == 0) {
2041 dev_info(&stream->intf->dev,
2042 "No supported video formats found.\n");
2046 atomic_set(&stream->active, 0);
2048 /* Alternate setting 0 should be the default, yet the XBox Live Vision
2049 * Cam (and possibly other devices) crash or otherwise misbehave if
2050 * they don't receive a SET_INTERFACE request before any other video
2053 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2055 /* Set the streaming probe control with default streaming parameters
2056 * retrieved from the device. Webcams that don't support GET_DEF
2057 * requests on the probe control will just keep their current streaming
2060 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
2061 uvc_set_video_ctrl(stream, probe, 1);
2063 /* Initialize the streaming parameters with the probe control current
2064 * value. This makes sure SET_CUR requests on the streaming commit
2065 * control will always use values retrieved from a successful GET_CUR
2066 * request on the probe control, as required by the UVC specification.
2068 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
2072 /* Check if the default format descriptor exists. Use the first
2073 * available format otherwise.
2075 for (i = stream->nformats; i > 0; --i) {
2076 format = &stream->format[i-1];
2077 if (format->index == probe->bFormatIndex)
2081 if (format->nframes == 0) {
2082 dev_info(&stream->intf->dev,
2083 "No frame descriptor found for the default format.\n");
2087 /* Zero bFrameIndex might be correct. Stream-based formats (including
2088 * MPEG-2 TS and DV) do not support frames but have a dummy frame
2089 * descriptor with bFrameIndex set to zero. If the default frame
2090 * descriptor is not found, use the first available frame.
2092 for (i = format->nframes; i > 0; --i) {
2093 frame = &format->frame[i-1];
2094 if (frame->bFrameIndex == probe->bFrameIndex)
2098 probe->bFormatIndex = format->index;
2099 probe->bFrameIndex = frame->bFrameIndex;
2101 stream->def_format = format;
2102 stream->cur_format = format;
2103 stream->cur_frame = frame;
2105 /* Select the video decoding function */
2106 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2107 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
2108 stream->decode = uvc_video_decode_isight;
2109 else if (stream->intf->num_altsetting > 1)
2110 stream->decode = uvc_video_decode_isoc;
2112 stream->decode = uvc_video_decode_bulk;
2114 if (stream->intf->num_altsetting == 1)
2115 stream->decode = uvc_video_encode_bulk;
2117 dev_info(&stream->intf->dev,
2118 "Isochronous endpoints are not supported for video output devices.\n");
2123 /* Prepare asynchronous work items. */
2124 for_each_uvc_urb(uvc_urb, stream)
2125 INIT_WORK(&uvc_urb->work, uvc_video_copy_data_work);
2130 int uvc_video_start_streaming(struct uvc_streaming *stream)
2134 ret = uvc_video_clock_init(stream);
2138 /* Commit the streaming parameters. */
2139 ret = uvc_commit_video(stream, &stream->ctrl);
2143 ret = uvc_video_start_transfer(stream, GFP_KERNEL);
2150 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2152 uvc_video_clock_cleanup(stream);
2157 void uvc_video_stop_streaming(struct uvc_streaming *stream)
2159 uvc_video_stop_transfer(stream, 1);
2161 if (stream->intf->num_altsetting > 1) {
2162 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2164 /* UVC doesn't specify how to inform a bulk-based device
2165 * when the video stream is stopped. Windows sends a
2166 * CLEAR_FEATURE(HALT) request to the video streaming
2167 * bulk endpoint, mimic the same behaviour.
2169 unsigned int epnum = stream->header.bEndpointAddress
2170 & USB_ENDPOINT_NUMBER_MASK;
2171 unsigned int dir = stream->header.bEndpointAddress
2172 & USB_ENDPOINT_DIR_MASK;
2175 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
2176 usb_clear_halt(stream->dev->udev, pipe);
2179 uvc_video_clock_cleanup(stream);