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