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