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