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