xref: /linux/drivers/media/usb/uvc/uvc_video.c (revision 0cdee263bc5e7b20f657ea09f9272f50c568f35b)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *      uvc_video.c  --  USB Video Class driver - Video handling
4  *
5  *      Copyright (C) 2005-2010
6  *          Laurent Pinchart (laurent.pinchart@ideasonboard.com)
7  */
8 
9 #include <linux/dma-mapping.h>
10 #include <linux/highmem.h>
11 #include <linux/kernel.h>
12 #include <linux/list.h>
13 #include <linux/module.h>
14 #include <linux/slab.h>
15 #include <linux/usb.h>
16 #include <linux/usb/hcd.h>
17 #include <linux/videodev2.h>
18 #include <linux/vmalloc.h>
19 #include <linux/wait.h>
20 #include <linux/atomic.h>
21 #include <linux/unaligned.h>
22 
23 #include <media/jpeg.h>
24 #include <media/v4l2-common.h>
25 
26 #include "uvcvideo.h"
27 
28 /* ------------------------------------------------------------------------
29  * UVC Controls
30  */
31 
__uvc_query_ctrl(struct uvc_device * dev,u8 query,u8 unit,u8 intfnum,u8 cs,void * data,u16 size,int timeout)32 static int __uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
33 			u8 intfnum, u8 cs, void *data, u16 size,
34 			int timeout)
35 {
36 	u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
37 	unsigned int pipe;
38 
39 	pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
40 			      : usb_sndctrlpipe(dev->udev, 0);
41 	type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
42 
43 	return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
44 			unit << 8 | intfnum, data, size, timeout);
45 }
46 
uvc_query_name(u8 query)47 static const char *uvc_query_name(u8 query)
48 {
49 	switch (query) {
50 	case UVC_SET_CUR:
51 		return "SET_CUR";
52 	case UVC_GET_CUR:
53 		return "GET_CUR";
54 	case UVC_GET_MIN:
55 		return "GET_MIN";
56 	case UVC_GET_MAX:
57 		return "GET_MAX";
58 	case UVC_GET_RES:
59 		return "GET_RES";
60 	case UVC_GET_LEN:
61 		return "GET_LEN";
62 	case UVC_GET_INFO:
63 		return "GET_INFO";
64 	case UVC_GET_DEF:
65 		return "GET_DEF";
66 	default:
67 		return "<invalid>";
68 	}
69 }
70 
uvc_query_ctrl(struct uvc_device * dev,u8 query,u8 unit,u8 intfnum,u8 cs,void * data,u16 size)71 int uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
72 			u8 intfnum, u8 cs, void *data, u16 size)
73 {
74 	int ret;
75 	u8 error;
76 	u8 tmp;
77 
78 	ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
79 				UVC_CTRL_CONTROL_TIMEOUT);
80 	if (likely(ret == size))
81 		return 0;
82 
83 	/*
84 	 * Some devices return shorter USB control packets than expected if the
85 	 * returned value can fit in less bytes. Zero all the bytes that the
86 	 * device has not written.
87 	 *
88 	 * This quirk is applied to all controls, regardless of their data type.
89 	 * Most controls are little-endian integers, in which case the missing
90 	 * bytes become 0 MSBs. For other data types, a different heuristic
91 	 * could be implemented if a device is found needing it.
92 	 *
93 	 * We exclude UVC_GET_INFO from the quirk. UVC_GET_LEN does not need
94 	 * to be excluded because its size is always 1.
95 	 */
96 	if (ret > 0 && query != UVC_GET_INFO) {
97 		memset(data + ret, 0, size - ret);
98 		dev_warn_once(&dev->udev->dev,
99 			      "UVC non compliance: %s control %u on unit %u returned %d bytes when we expected %u.\n",
100 			      uvc_query_name(query), cs, unit, ret, size);
101 		return 0;
102 	}
103 
104 	if (ret != -EPIPE) {
105 		dev_err(&dev->udev->dev,
106 			"Failed to query (%s) UVC control %u on unit %u: %d (exp. %u).\n",
107 			uvc_query_name(query), cs, unit, ret, size);
108 		return ret < 0 ? ret : -EPIPE;
109 	}
110 
111 	/* Reuse data[0] to request the error code. */
112 	tmp = *(u8 *)data;
113 
114 	ret = __uvc_query_ctrl(dev, UVC_GET_CUR, 0, intfnum,
115 			       UVC_VC_REQUEST_ERROR_CODE_CONTROL, data, 1,
116 			       UVC_CTRL_CONTROL_TIMEOUT);
117 
118 	error = *(u8 *)data;
119 	*(u8 *)data = tmp;
120 
121 	if (ret != 1) {
122 		dev_err_ratelimited(&dev->udev->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: the max payload transmission size (%u) exceeds the size of the ep max packet (%u). Using the max size.\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_array(clock->size, sizeof(*clock->samples),
686 				       GFP_KERNEL);
687 	if (clock->samples == NULL)
688 		return -ENOMEM;
689 
690 	uvc_video_clock_reset(clock);
691 
692 	return 0;
693 }
694 
uvc_video_clock_cleanup(struct uvc_clock * clock)695 static void uvc_video_clock_cleanup(struct uvc_clock *clock)
696 {
697 	kfree(clock->samples);
698 	clock->samples = NULL;
699 }
700 
701 /*
702  * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
703  *
704  * Host SOF counters reported by usb_get_current_frame_number() usually don't
705  * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
706  * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
707  * controller and its configuration.
708  *
709  * We thus need to recover the SOF value corresponding to the host frame number.
710  * As the device and host frame numbers are sampled in a short interval, the
711  * difference between their values should be equal to a small delta plus an
712  * integer multiple of 256 caused by the host frame number limited precision.
713  *
714  * To obtain the recovered host SOF value, compute the small delta by masking
715  * the high bits of the host frame counter and device SOF difference and add it
716  * to the device SOF value.
717  */
uvc_video_clock_host_sof(const struct uvc_clock_sample * sample)718 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
719 {
720 	/* The delta value can be negative. */
721 	s8 delta_sof;
722 
723 	delta_sof = (sample->host_sof - sample->dev_sof) & 255;
724 
725 	return (sample->dev_sof + delta_sof) & 2047;
726 }
727 
728 /*
729  * uvc_video_clock_update - Update the buffer timestamp
730  *
731  * This function converts the buffer PTS timestamp to the host clock domain by
732  * going through the USB SOF clock domain and stores the result in the V4L2
733  * buffer timestamp field.
734  *
735  * The relationship between the device clock and the host clock isn't known.
736  * However, the device and the host share the common USB SOF clock which can be
737  * used to recover that relationship.
738  *
739  * The relationship between the device clock and the USB SOF clock is considered
740  * to be linear over the clock samples sliding window and is given by
741  *
742  * SOF = m * PTS + p
743  *
744  * Several methods to compute the slope (m) and intercept (p) can be used. As
745  * the clock drift should be small compared to the sliding window size, we
746  * assume that the line that goes through the points at both ends of the window
747  * is a good approximation. Naming those points P1 and P2, we get
748  *
749  * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
750  *     + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
751  *
752  * or
753  *
754  * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)   (1)
755  *
756  * to avoid losing precision in the division. Similarly, the host timestamp is
757  * computed with
758  *
759  * TS = ((TS2 - TS1) * SOF + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1)	     (2)
760  *
761  * SOF values are coded on 11 bits by USB. We extend their precision with 16
762  * decimal bits, leading to a 11.16 coding.
763  *
764  * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
765  * be normalized using the nominal device clock frequency reported through the
766  * UVC descriptors.
767  *
768  * Both the PTS/STC and SOF counters roll over, after a fixed but device
769  * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
770  * sliding window size is smaller than the rollover period, differences computed
771  * on unsigned integers will produce the correct result. However, the p term in
772  * the linear relations will be miscomputed.
773  *
774  * To fix the issue, we subtract a constant from the PTS and STC values to bring
775  * PTS to half the 32 bit STC range. The sliding window STC values then fit into
776  * the 32 bit range without any rollover.
777  *
778  * Similarly, we add 2048 to the device SOF values to make sure that the SOF
779  * computed by (1) will never be smaller than 0. This offset is then compensated
780  * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
781  * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
782  * lower than 4096, and the host SOF counters can have rolled over to 2048. This
783  * case is handled by subtracting 2048 from the SOF value if it exceeds the host
784  * SOF value at the end of the sliding window.
785  *
786  * Finally we subtract a constant from the host timestamps to bring the first
787  * timestamp of the sliding window to 1s.
788  */
uvc_video_clock_update(struct uvc_streaming * stream,struct vb2_v4l2_buffer * vbuf,struct uvc_buffer * buf)789 void uvc_video_clock_update(struct uvc_streaming *stream,
790 			    struct vb2_v4l2_buffer *vbuf,
791 			    struct uvc_buffer *buf)
792 {
793 	struct uvc_clock *clock = &stream->clock;
794 	struct uvc_clock_sample *first;
795 	struct uvc_clock_sample *last;
796 	unsigned long flags;
797 	u64 timestamp;
798 	u32 delta_stc;
799 	u32 y1;
800 	u32 x1, x2;
801 	u32 mean;
802 	u32 sof;
803 	u64 y, y2;
804 
805 	if (!uvc_hw_timestamps_param)
806 		return;
807 
808 	/*
809 	 * We will get called from __vb2_queue_cancel() if there are buffers
810 	 * done but not dequeued by the user, but the sample array has already
811 	 * been released at that time. Just bail out in that case.
812 	 */
813 	if (!clock->samples)
814 		return;
815 
816 	spin_lock_irqsave(&clock->lock, flags);
817 
818 	if (clock->count < 2)
819 		goto done;
820 
821 	first = &clock->samples[(clock->head - clock->count + clock->size) % clock->size];
822 	last = &clock->samples[(clock->head - 1 + clock->size) % clock->size];
823 
824 	/* First step, PTS to SOF conversion. */
825 	delta_stc = buf->pts - (1UL << 31);
826 	x1 = first->dev_stc - delta_stc;
827 	x2 = last->dev_stc - delta_stc;
828 	if (x1 == x2)
829 		goto done;
830 
831 	y1 = (first->dev_sof + 2048) << 16;
832 	y2 = (last->dev_sof + 2048) << 16;
833 	if (y2 < y1)
834 		y2 += 2048 << 16;
835 
836 	/*
837 	 * Have at least 1/4 of a second of timestamps before we
838 	 * try to do any calculation. Otherwise we do not have enough
839 	 * precision. This value was determined by running Android CTS
840 	 * on different devices.
841 	 *
842 	 * dev_sof runs at 1KHz, and we have a fixed point precision of
843 	 * 16 bits.
844 	 */
845 	if ((y2 - y1) < ((1000 / 4) << 16))
846 		goto done;
847 
848 	y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
849 	  - (u64)y2 * (u64)x1;
850 	y = div_u64(y, x2 - x1);
851 
852 	sof = y;
853 
854 	uvc_dbg(stream->dev, CLOCK,
855 		"%s: PTS %u y %llu.%06llu SOF %u.%06llu (x1 %u x2 %u y1 %u y2 %llu SOF offset %u)\n",
856 		stream->dev->name, buf->pts,
857 		y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
858 		sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
859 		x1, x2, y1, y2, clock->sof_offset);
860 
861 	/* Second step, SOF to host clock conversion. */
862 	x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
863 	x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
864 	if (x2 < x1)
865 		x2 += 2048 << 16;
866 	if (x1 == x2)
867 		goto done;
868 
869 	y1 = NSEC_PER_SEC;
870 	y2 = ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
871 
872 	/*
873 	 * Interpolated and host SOF timestamps can wrap around at slightly
874 	 * different times. Handle this by adding or removing 2048 to or from
875 	 * the computed SOF value to keep it close to the SOF samples mean
876 	 * value.
877 	 */
878 	mean = (x1 + x2) / 2;
879 	if (mean - (1024 << 16) > sof)
880 		sof += 2048 << 16;
881 	else if (sof > mean + (1024 << 16))
882 		sof -= 2048 << 16;
883 
884 	y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
885 	  - (u64)y2 * (u64)x1;
886 	y = div_u64(y, x2 - x1);
887 
888 	timestamp = ktime_to_ns(first->host_time) + y - y1;
889 
890 	uvc_dbg(stream->dev, CLOCK,
891 		"%s: SOF %u.%06llu y %llu ts %llu buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %llu)\n",
892 		stream->dev->name,
893 		sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
894 		y, timestamp, vbuf->vb2_buf.timestamp,
895 		x1, first->host_sof, first->dev_sof,
896 		x2, last->host_sof, last->dev_sof, y1, y2);
897 
898 	/* Update the V4L2 buffer. */
899 	vbuf->vb2_buf.timestamp = timestamp;
900 
901 done:
902 	spin_unlock_irqrestore(&clock->lock, flags);
903 }
904 
905 /* ------------------------------------------------------------------------
906  * Stream statistics
907  */
908 
uvc_video_stats_decode(struct uvc_streaming * stream,const u8 * data,int len)909 static void uvc_video_stats_decode(struct uvc_streaming *stream,
910 		const u8 *data, int len)
911 {
912 	unsigned int header_size;
913 	bool has_pts = false;
914 	bool has_scr = false;
915 	u16 scr_sof;
916 	u32 scr_stc;
917 	u32 pts;
918 
919 	if (stream->stats.stream.nb_frames == 0 &&
920 	    stream->stats.frame.nb_packets == 0)
921 		stream->stats.stream.start_ts = ktime_get();
922 
923 	switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
924 	case UVC_STREAM_PTS | UVC_STREAM_SCR:
925 		header_size = 12;
926 		has_pts = true;
927 		has_scr = true;
928 		break;
929 	case UVC_STREAM_PTS:
930 		header_size = 6;
931 		has_pts = true;
932 		break;
933 	case UVC_STREAM_SCR:
934 		header_size = 8;
935 		has_scr = true;
936 		break;
937 	default:
938 		header_size = 2;
939 		break;
940 	}
941 
942 	/* Check for invalid headers. */
943 	if (len < header_size || data[0] < header_size) {
944 		stream->stats.frame.nb_invalid++;
945 		return;
946 	}
947 
948 	/* Extract the timestamps. */
949 	if (has_pts)
950 		pts = get_unaligned_le32(&data[2]);
951 
952 	if (has_scr) {
953 		scr_stc = get_unaligned_le32(&data[header_size - 6]);
954 		scr_sof = get_unaligned_le16(&data[header_size - 2]);
955 	}
956 
957 	/* Is PTS constant through the whole frame ? */
958 	if (has_pts && stream->stats.frame.nb_pts) {
959 		if (stream->stats.frame.pts != pts) {
960 			stream->stats.frame.nb_pts_diffs++;
961 			stream->stats.frame.last_pts_diff =
962 				stream->stats.frame.nb_packets;
963 		}
964 	}
965 
966 	if (has_pts) {
967 		stream->stats.frame.nb_pts++;
968 		stream->stats.frame.pts = pts;
969 	}
970 
971 	/*
972 	 * Do all frames have a PTS in their first non-empty packet, or before
973 	 * their first empty packet ?
974 	 */
975 	if (stream->stats.frame.size == 0) {
976 		if (len > header_size)
977 			stream->stats.frame.has_initial_pts = has_pts;
978 		if (len == header_size && has_pts)
979 			stream->stats.frame.has_early_pts = true;
980 	}
981 
982 	/* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
983 	if (has_scr && stream->stats.frame.nb_scr) {
984 		if (stream->stats.frame.scr_stc != scr_stc)
985 			stream->stats.frame.nb_scr_diffs++;
986 	}
987 
988 	if (has_scr) {
989 		/* Expand the SOF counter to 32 bits and store its value. */
990 		if (stream->stats.stream.nb_frames > 0 ||
991 		    stream->stats.frame.nb_scr > 0)
992 			stream->stats.stream.scr_sof_count +=
993 				(scr_sof - stream->stats.stream.scr_sof) % 2048;
994 		stream->stats.stream.scr_sof = scr_sof;
995 
996 		stream->stats.frame.nb_scr++;
997 		stream->stats.frame.scr_stc = scr_stc;
998 		stream->stats.frame.scr_sof = scr_sof;
999 
1000 		if (scr_sof < stream->stats.stream.min_sof)
1001 			stream->stats.stream.min_sof = scr_sof;
1002 		if (scr_sof > stream->stats.stream.max_sof)
1003 			stream->stats.stream.max_sof = scr_sof;
1004 	}
1005 
1006 	/* Record the first non-empty packet number. */
1007 	if (stream->stats.frame.size == 0 && len > header_size)
1008 		stream->stats.frame.first_data = stream->stats.frame.nb_packets;
1009 
1010 	/* Update the frame size. */
1011 	stream->stats.frame.size += len - header_size;
1012 
1013 	/* Update the packets counters. */
1014 	stream->stats.frame.nb_packets++;
1015 	if (len <= header_size)
1016 		stream->stats.frame.nb_empty++;
1017 
1018 	if (data[1] & UVC_STREAM_ERR)
1019 		stream->stats.frame.nb_errors++;
1020 }
1021 
uvc_video_stats_update(struct uvc_streaming * stream)1022 static void uvc_video_stats_update(struct uvc_streaming *stream)
1023 {
1024 	struct uvc_stats_frame *frame = &stream->stats.frame;
1025 
1026 	uvc_dbg(stream->dev, STATS,
1027 		"frame %u stats: %u/%u/%u packets, %u/%u/%u pts (%searly %sinitial), %u/%u scr, last pts/stc/sof %u/%u/%u\n",
1028 		stream->sequence, frame->first_data,
1029 		frame->nb_packets - frame->nb_empty, frame->nb_packets,
1030 		frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
1031 		frame->has_early_pts ? "" : "!",
1032 		frame->has_initial_pts ? "" : "!",
1033 		frame->nb_scr_diffs, frame->nb_scr,
1034 		frame->pts, frame->scr_stc, frame->scr_sof);
1035 
1036 	stream->stats.stream.nb_frames++;
1037 	stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
1038 	stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
1039 	stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
1040 	stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
1041 
1042 	if (frame->has_early_pts)
1043 		stream->stats.stream.nb_pts_early++;
1044 	if (frame->has_initial_pts)
1045 		stream->stats.stream.nb_pts_initial++;
1046 	if (frame->last_pts_diff <= frame->first_data)
1047 		stream->stats.stream.nb_pts_constant++;
1048 	if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
1049 		stream->stats.stream.nb_scr_count_ok++;
1050 	if (frame->nb_scr_diffs + 1 == frame->nb_scr)
1051 		stream->stats.stream.nb_scr_diffs_ok++;
1052 
1053 	memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
1054 }
1055 
uvc_video_stats_dump(struct uvc_streaming * stream,char * buf,size_t size)1056 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
1057 			    size_t size)
1058 {
1059 	unsigned int scr_sof_freq;
1060 	unsigned int duration;
1061 	size_t count = 0;
1062 
1063 	/*
1064 	 * Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
1065 	 * frequency this will not overflow before more than 1h.
1066 	 */
1067 	duration = ktime_ms_delta(stream->stats.stream.stop_ts,
1068 				  stream->stats.stream.start_ts);
1069 	if (duration != 0)
1070 		scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
1071 			     / duration;
1072 	else
1073 		scr_sof_freq = 0;
1074 
1075 	count += scnprintf(buf + count, size - count,
1076 			   "frames:  %u\npackets: %u\nempty:   %u\n"
1077 			   "errors:  %u\ninvalid: %u\n",
1078 			   stream->stats.stream.nb_frames,
1079 			   stream->stats.stream.nb_packets,
1080 			   stream->stats.stream.nb_empty,
1081 			   stream->stats.stream.nb_errors,
1082 			   stream->stats.stream.nb_invalid);
1083 	count += scnprintf(buf + count, size - count,
1084 			   "pts: %u early, %u initial, %u ok\n",
1085 			   stream->stats.stream.nb_pts_early,
1086 			   stream->stats.stream.nb_pts_initial,
1087 			   stream->stats.stream.nb_pts_constant);
1088 	count += scnprintf(buf + count, size - count,
1089 			   "scr: %u count ok, %u diff ok\n",
1090 			   stream->stats.stream.nb_scr_count_ok,
1091 			   stream->stats.stream.nb_scr_diffs_ok);
1092 	count += scnprintf(buf + count, size - count,
1093 			   "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
1094 			   stream->stats.stream.min_sof,
1095 			   stream->stats.stream.max_sof,
1096 			   scr_sof_freq / 1000, scr_sof_freq % 1000);
1097 
1098 	return count;
1099 }
1100 
uvc_video_stats_start(struct uvc_streaming * stream)1101 static void uvc_video_stats_start(struct uvc_streaming *stream)
1102 {
1103 	memset(&stream->stats, 0, sizeof(stream->stats));
1104 	stream->stats.stream.min_sof = 2048;
1105 }
1106 
uvc_video_stats_stop(struct uvc_streaming * stream)1107 static void uvc_video_stats_stop(struct uvc_streaming *stream)
1108 {
1109 	stream->stats.stream.stop_ts = ktime_get();
1110 }
1111 
1112 /* ------------------------------------------------------------------------
1113  * Video codecs
1114  */
1115 
1116 /*
1117  * Video payload decoding is handled by uvc_video_decode_start(),
1118  * uvc_video_decode_data() and uvc_video_decode_end().
1119  *
1120  * uvc_video_decode_start is called with URB data at the start of a bulk or
1121  * isochronous payload. It processes header data and returns the header size
1122  * in bytes if successful. If an error occurs, it returns a negative error
1123  * code. The following error codes have special meanings.
1124  *
1125  * - EAGAIN informs the caller that the current video buffer should be marked
1126  *   as done, and that the function should be called again with the same data
1127  *   and a new video buffer. This is used when end of frame conditions can be
1128  *   reliably detected at the beginning of the next frame only.
1129  *
1130  * If an error other than -EAGAIN is returned, the caller will drop the current
1131  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
1132  * made until the next payload. -ENODATA can be used to drop the current
1133  * payload if no other error code is appropriate.
1134  *
1135  * uvc_video_decode_data is called for every URB with URB data. It copies the
1136  * data to the video buffer.
1137  *
1138  * uvc_video_decode_end is called with header data at the end of a bulk or
1139  * isochronous payload. It performs any additional header data processing and
1140  * returns 0 or a negative error code if an error occurred. As header data have
1141  * already been processed by uvc_video_decode_start, this functions isn't
1142  * required to perform sanity checks a second time.
1143  *
1144  * For isochronous transfers where a payload is always transferred in a single
1145  * URB, the three functions will be called in a row.
1146  *
1147  * To let the decoder process header data and update its internal state even
1148  * when no video buffer is available, uvc_video_decode_start must be prepared
1149  * to be called with a NULL buf parameter. uvc_video_decode_data and
1150  * uvc_video_decode_end will never be called with a NULL buffer.
1151  */
uvc_video_decode_start(struct uvc_streaming * stream,struct uvc_buffer * buf,const u8 * data,int len)1152 static int uvc_video_decode_start(struct uvc_streaming *stream,
1153 		struct uvc_buffer *buf, const u8 *data, int len)
1154 {
1155 	u8 header_len;
1156 	u8 fid;
1157 
1158 	/*
1159 	 * Sanity checks:
1160 	 * - packet must be at least 2 bytes long
1161 	 * - bHeaderLength value must be at least 2 bytes (see above)
1162 	 * - bHeaderLength value can't be larger than the packet size.
1163 	 */
1164 	if (len < 2 || data[0] < 2 || data[0] > len) {
1165 		stream->stats.frame.nb_invalid++;
1166 		return -EINVAL;
1167 	}
1168 
1169 	header_len = data[0];
1170 	fid = data[1] & UVC_STREAM_FID;
1171 
1172 	/*
1173 	 * Increase the sequence number regardless of any buffer states, so
1174 	 * that discontinuous sequence numbers always indicate lost frames.
1175 	 */
1176 	if (stream->last_fid != fid) {
1177 		stream->sequence++;
1178 		if (stream->sequence)
1179 			uvc_video_stats_update(stream);
1180 	}
1181 
1182 	uvc_video_clock_decode(stream, buf, data, len);
1183 	uvc_video_stats_decode(stream, data, len);
1184 
1185 	/*
1186 	 * Store the payload FID bit and return immediately when the buffer is
1187 	 * NULL.
1188 	 */
1189 	if (buf == NULL) {
1190 		stream->last_fid = fid;
1191 		return -ENODATA;
1192 	}
1193 
1194 	/* Mark the buffer as bad if the error bit is set. */
1195 	if (data[1] & UVC_STREAM_ERR) {
1196 		uvc_dbg(stream->dev, FRAME,
1197 			"Marking buffer as bad (error bit set)\n");
1198 		buf->error = 1;
1199 	}
1200 
1201 	/*
1202 	 * Synchronize to the input stream by waiting for the FID bit to be
1203 	 * toggled when the buffer state is not UVC_BUF_STATE_ACTIVE.
1204 	 * stream->last_fid is initialized to -1, so the first isochronous
1205 	 * frame will always be in sync.
1206 	 *
1207 	 * If the device doesn't toggle the FID bit, invert stream->last_fid
1208 	 * when the EOF bit is set to force synchronisation on the next packet.
1209 	 */
1210 	if (buf->state != UVC_BUF_STATE_ACTIVE) {
1211 		if (fid == stream->last_fid) {
1212 			uvc_dbg(stream->dev, FRAME,
1213 				"Dropping payload (out of sync)\n");
1214 			if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1215 			    (data[1] & UVC_STREAM_EOF))
1216 				stream->last_fid ^= UVC_STREAM_FID;
1217 			return -ENODATA;
1218 		}
1219 
1220 		buf->buf.field = V4L2_FIELD_NONE;
1221 		buf->buf.sequence = stream->sequence;
1222 		buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time());
1223 
1224 		/* TODO: Handle PTS and SCR. */
1225 		buf->state = UVC_BUF_STATE_ACTIVE;
1226 	}
1227 
1228 	/*
1229 	 * Mark the buffer as done if we're at the beginning of a new frame.
1230 	 * End of frame detection is better implemented by checking the EOF
1231 	 * bit (FID bit toggling is delayed by one frame compared to the EOF
1232 	 * bit), but some devices don't set the bit at end of frame (and the
1233 	 * last payload can be lost anyway). We thus must check if the FID has
1234 	 * been toggled.
1235 	 *
1236 	 * stream->last_fid is initialized to -1, so the first isochronous
1237 	 * frame will never trigger an end of frame detection.
1238 	 *
1239 	 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1240 	 * as it doesn't make sense to return an empty buffer. This also
1241 	 * avoids detecting end of frame conditions at FID toggling if the
1242 	 * previous payload had the EOF bit set.
1243 	 */
1244 	if (fid != stream->last_fid && buf->bytesused != 0) {
1245 		uvc_dbg(stream->dev, FRAME,
1246 			"Frame complete (FID bit toggled)\n");
1247 		buf->state = UVC_BUF_STATE_READY;
1248 		return -EAGAIN;
1249 	}
1250 
1251 	/*
1252 	 * Some cameras, when running two parallel streams (one MJPEG alongside
1253 	 * another non-MJPEG stream), are known to lose the EOF packet for a frame.
1254 	 * We can detect the end of a frame by checking for a new SOI marker, as
1255 	 * the SOI always lies on the packet boundary between two frames for
1256 	 * these devices.
1257 	 */
1258 	if (stream->dev->quirks & UVC_QUIRK_MJPEG_NO_EOF &&
1259 	    (stream->cur_format->fcc == V4L2_PIX_FMT_MJPEG ||
1260 	    stream->cur_format->fcc == V4L2_PIX_FMT_JPEG)) {
1261 		const u8 *packet = data + header_len;
1262 
1263 		if (len >= header_len + 2 &&
1264 		    packet[0] == 0xff && packet[1] == JPEG_MARKER_SOI &&
1265 		    buf->bytesused != 0) {
1266 			buf->state = UVC_BUF_STATE_READY;
1267 			buf->error = 1;
1268 			stream->last_fid ^= UVC_STREAM_FID;
1269 			return -EAGAIN;
1270 		}
1271 	}
1272 
1273 	stream->last_fid = fid;
1274 
1275 	return header_len;
1276 }
1277 
uvc_stream_dir(struct uvc_streaming * stream)1278 static inline enum dma_data_direction uvc_stream_dir(
1279 				struct uvc_streaming *stream)
1280 {
1281 	if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1282 		return DMA_FROM_DEVICE;
1283 	else
1284 		return DMA_TO_DEVICE;
1285 }
1286 
1287 /*
1288  * uvc_video_decode_data_work: Asynchronous memcpy processing
1289  *
1290  * Copy URB data to video buffers in process context, releasing buffer
1291  * references and requeuing the URB when done.
1292  */
uvc_video_copy_data_work(struct work_struct * work)1293 static void uvc_video_copy_data_work(struct work_struct *work)
1294 {
1295 	struct uvc_urb *uvc_urb = container_of(work, struct uvc_urb, work);
1296 	unsigned int i;
1297 	int ret;
1298 
1299 	for (i = 0; i < uvc_urb->async_operations; i++) {
1300 		struct uvc_copy_op *op = &uvc_urb->copy_operations[i];
1301 
1302 		memcpy(op->dst, op->src, op->len);
1303 
1304 		/* Release reference taken on this buffer. */
1305 		uvc_queue_buffer_release(op->buf);
1306 	}
1307 
1308 	ret = usb_submit_urb(uvc_urb->urb, GFP_KERNEL);
1309 	if (ret < 0)
1310 		dev_err(&uvc_urb->stream->intf->dev,
1311 			"Failed to resubmit video URB (%d).\n", ret);
1312 }
1313 
uvc_video_decode_data(struct uvc_urb * uvc_urb,struct uvc_buffer * buf,const u8 * data,int len)1314 static void uvc_video_decode_data(struct uvc_urb *uvc_urb,
1315 		struct uvc_buffer *buf, const u8 *data, int len)
1316 {
1317 	unsigned int active_op = uvc_urb->async_operations;
1318 	struct uvc_copy_op *op = &uvc_urb->copy_operations[active_op];
1319 	unsigned int maxlen;
1320 
1321 	if (len <= 0)
1322 		return;
1323 
1324 	maxlen = buf->length - buf->bytesused;
1325 
1326 	/* Take a buffer reference for async work. */
1327 	kref_get(&buf->ref);
1328 
1329 	op->buf = buf;
1330 	op->src = data;
1331 	op->dst = buf->mem + buf->bytesused;
1332 	op->len = min_t(unsigned int, len, maxlen);
1333 
1334 	buf->bytesused += op->len;
1335 
1336 	/* Complete the current frame if the buffer size was exceeded. */
1337 	if (len > maxlen) {
1338 		uvc_dbg(uvc_urb->stream->dev, FRAME,
1339 			"Frame complete (overflow)\n");
1340 		buf->error = 1;
1341 		buf->state = UVC_BUF_STATE_READY;
1342 	}
1343 
1344 	uvc_urb->async_operations++;
1345 }
1346 
uvc_video_decode_end(struct uvc_streaming * stream,struct uvc_buffer * buf,const u8 * data,int len)1347 static void uvc_video_decode_end(struct uvc_streaming *stream,
1348 		struct uvc_buffer *buf, const u8 *data, int len)
1349 {
1350 	/* Mark the buffer as done if the EOF marker is set. */
1351 	if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1352 		uvc_dbg(stream->dev, FRAME, "Frame complete (EOF found)\n");
1353 		if (data[0] == len)
1354 			uvc_dbg(stream->dev, FRAME, "EOF in empty payload\n");
1355 		buf->state = UVC_BUF_STATE_READY;
1356 		if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1357 			stream->last_fid ^= UVC_STREAM_FID;
1358 	}
1359 }
1360 
1361 /*
1362  * Video payload encoding is handled by uvc_video_encode_header() and
1363  * uvc_video_encode_data(). Only bulk transfers are currently supported.
1364  *
1365  * uvc_video_encode_header is called at the start of a payload. It adds header
1366  * data to the transfer buffer and returns the header size. As the only known
1367  * UVC output device transfers a whole frame in a single payload, the EOF bit
1368  * is always set in the header.
1369  *
1370  * uvc_video_encode_data is called for every URB and copies the data from the
1371  * video buffer to the transfer buffer.
1372  */
uvc_video_encode_header(struct uvc_streaming * stream,struct uvc_buffer * buf,u8 * data,int len)1373 static int uvc_video_encode_header(struct uvc_streaming *stream,
1374 		struct uvc_buffer *buf, u8 *data, int len)
1375 {
1376 	data[0] = 2;	/* Header length */
1377 	data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1378 		| (stream->last_fid & UVC_STREAM_FID);
1379 	return 2;
1380 }
1381 
uvc_video_encode_data(struct uvc_streaming * stream,struct uvc_buffer * buf,u8 * data,int len)1382 static int uvc_video_encode_data(struct uvc_streaming *stream,
1383 		struct uvc_buffer *buf, u8 *data, int len)
1384 {
1385 	struct uvc_video_queue *queue = &stream->queue;
1386 	unsigned int nbytes;
1387 	void *mem;
1388 
1389 	/* Copy video data to the URB buffer. */
1390 	mem = buf->mem + queue->buf_used;
1391 	nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1392 	nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1393 			nbytes);
1394 	memcpy(data, mem, nbytes);
1395 
1396 	queue->buf_used += nbytes;
1397 
1398 	return nbytes;
1399 }
1400 
1401 /* ------------------------------------------------------------------------
1402  * Metadata
1403  */
1404 
1405 /*
1406  * Additionally to the payload headers we also want to provide the user with USB
1407  * Frame Numbers and system time values. The resulting buffer is thus composed
1408  * of blocks, containing a 64-bit timestamp in  nanoseconds, a 16-bit USB Frame
1409  * Number, and a copy of the payload header.
1410  *
1411  * Ideally we want to capture all payload headers for each frame. However, their
1412  * number is unknown and unbound. We thus drop headers that contain no vendor
1413  * data and that either contain no SCR value or an SCR value identical to the
1414  * previous header.
1415  */
uvc_video_decode_meta(struct uvc_streaming * stream,struct uvc_buffer * meta_buf,const u8 * mem,unsigned int length)1416 static void uvc_video_decode_meta(struct uvc_streaming *stream,
1417 				  struct uvc_buffer *meta_buf,
1418 				  const u8 *mem, unsigned int length)
1419 {
1420 	struct uvc_meta_buf *meta;
1421 	size_t len_std = 2;
1422 	bool has_pts, has_scr;
1423 	unsigned long flags;
1424 	unsigned int sof;
1425 	ktime_t time;
1426 	const u8 *scr;
1427 
1428 	if (!meta_buf || length == 2)
1429 		return;
1430 
1431 	has_pts = mem[1] & UVC_STREAM_PTS;
1432 	has_scr = mem[1] & UVC_STREAM_SCR;
1433 
1434 	if (has_pts) {
1435 		len_std += 4;
1436 		scr = mem + 6;
1437 	} else {
1438 		scr = mem + 2;
1439 	}
1440 
1441 	if (has_scr)
1442 		len_std += 6;
1443 
1444 	if (stream->meta.format == V4L2_META_FMT_UVC)
1445 		length = len_std;
1446 
1447 	if (length == len_std && (!has_scr ||
1448 				  !memcmp(scr, stream->clock.last_scr, 6)))
1449 		return;
1450 
1451 	if (meta_buf->length - meta_buf->bytesused <
1452 	    length + sizeof(meta->ns) + sizeof(meta->sof)) {
1453 		meta_buf->error = 1;
1454 		return;
1455 	}
1456 
1457 	meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
1458 	local_irq_save(flags);
1459 	time = uvc_video_get_time();
1460 	sof = usb_get_current_frame_number(stream->dev->udev);
1461 	local_irq_restore(flags);
1462 	put_unaligned(ktime_to_ns(time), &meta->ns);
1463 	put_unaligned(sof, &meta->sof);
1464 
1465 	if (has_scr)
1466 		memcpy(stream->clock.last_scr, scr, 6);
1467 
1468 	meta->length = mem[0];
1469 	meta->flags  = mem[1];
1470 	memcpy(meta->buf, &mem[2], length - 2);
1471 	meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);
1472 
1473 	uvc_dbg(stream->dev, FRAME,
1474 		"%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
1475 		__func__, ktime_to_ns(time), meta->sof, meta->length,
1476 		meta->flags,
1477 		has_pts ? *(u32 *)meta->buf : 0,
1478 		has_scr ? *(u32 *)scr : 0,
1479 		has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
1480 }
1481 
1482 /* ------------------------------------------------------------------------
1483  * URB handling
1484  */
1485 
1486 /*
1487  * Set error flag for incomplete buffer.
1488  */
uvc_video_validate_buffer(const struct uvc_streaming * stream,struct uvc_buffer * buf)1489 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1490 				      struct uvc_buffer *buf)
1491 {
1492 	if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1493 	    !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1494 		buf->error = 1;
1495 }
1496 
1497 /*
1498  * Completion handler for video URBs.
1499  */
1500 
uvc_video_next_buffers(struct uvc_streaming * stream,struct uvc_buffer ** video_buf,struct uvc_buffer ** meta_buf)1501 static void uvc_video_next_buffers(struct uvc_streaming *stream,
1502 		struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
1503 {
1504 	uvc_video_validate_buffer(stream, *video_buf);
1505 
1506 	if (*meta_buf) {
1507 		struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
1508 		const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;
1509 
1510 		vb2_meta->sequence = vb2_video->sequence;
1511 		vb2_meta->field = vb2_video->field;
1512 		vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;
1513 
1514 		(*meta_buf)->state = UVC_BUF_STATE_READY;
1515 		if (!(*meta_buf)->error)
1516 			(*meta_buf)->error = (*video_buf)->error;
1517 		*meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
1518 						  *meta_buf);
1519 	}
1520 	*video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
1521 }
1522 
uvc_video_decode_isoc(struct uvc_urb * uvc_urb,struct uvc_buffer * buf,struct uvc_buffer * meta_buf)1523 static void uvc_video_decode_isoc(struct uvc_urb *uvc_urb,
1524 			struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1525 {
1526 	struct urb *urb = uvc_urb->urb;
1527 	struct uvc_streaming *stream = uvc_urb->stream;
1528 	u8 *mem;
1529 	int ret, i;
1530 
1531 	for (i = 0; i < urb->number_of_packets; ++i) {
1532 		if (urb->iso_frame_desc[i].status < 0) {
1533 			uvc_dbg(stream->dev, FRAME,
1534 				"USB isochronous frame lost (%d)\n",
1535 				urb->iso_frame_desc[i].status);
1536 			/* Mark the buffer as faulty. */
1537 			if (buf != NULL)
1538 				buf->error = 1;
1539 			continue;
1540 		}
1541 
1542 		/* Decode the payload header. */
1543 		mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1544 		do {
1545 			ret = uvc_video_decode_start(stream, buf, mem,
1546 				urb->iso_frame_desc[i].actual_length);
1547 			if (ret == -EAGAIN)
1548 				uvc_video_next_buffers(stream, &buf, &meta_buf);
1549 		} while (ret == -EAGAIN);
1550 
1551 		if (ret < 0)
1552 			continue;
1553 
1554 		uvc_video_decode_meta(stream, meta_buf, mem, ret);
1555 
1556 		/* Decode the payload data. */
1557 		uvc_video_decode_data(uvc_urb, buf, mem + ret,
1558 			urb->iso_frame_desc[i].actual_length - ret);
1559 
1560 		/* Process the header again. */
1561 		uvc_video_decode_end(stream, buf, mem,
1562 			urb->iso_frame_desc[i].actual_length);
1563 
1564 		if (buf->state == UVC_BUF_STATE_READY)
1565 			uvc_video_next_buffers(stream, &buf, &meta_buf);
1566 	}
1567 }
1568 
uvc_video_decode_bulk(struct uvc_urb * uvc_urb,struct uvc_buffer * buf,struct uvc_buffer * meta_buf)1569 static void uvc_video_decode_bulk(struct uvc_urb *uvc_urb,
1570 			struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1571 {
1572 	struct urb *urb = uvc_urb->urb;
1573 	struct uvc_streaming *stream = uvc_urb->stream;
1574 	u8 *mem;
1575 	int len, ret;
1576 
1577 	/*
1578 	 * Ignore ZLPs if they're not part of a frame, otherwise process them
1579 	 * to trigger the end of payload detection.
1580 	 */
1581 	if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1582 		return;
1583 
1584 	mem = urb->transfer_buffer;
1585 	len = urb->actual_length;
1586 	stream->bulk.payload_size += len;
1587 
1588 	/*
1589 	 * If the URB is the first of its payload, decode and save the
1590 	 * header.
1591 	 */
1592 	if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1593 		do {
1594 			ret = uvc_video_decode_start(stream, buf, mem, len);
1595 			if (ret == -EAGAIN)
1596 				uvc_video_next_buffers(stream, &buf, &meta_buf);
1597 		} while (ret == -EAGAIN);
1598 
1599 		/* If an error occurred skip the rest of the payload. */
1600 		if (ret < 0 || buf == NULL) {
1601 			stream->bulk.skip_payload = 1;
1602 		} else {
1603 			memcpy(stream->bulk.header, mem, ret);
1604 			stream->bulk.header_size = ret;
1605 
1606 			uvc_video_decode_meta(stream, meta_buf, mem, ret);
1607 
1608 			mem += ret;
1609 			len -= ret;
1610 		}
1611 	}
1612 
1613 	/*
1614 	 * The buffer queue might have been cancelled while a bulk transfer
1615 	 * was in progress, so we can reach here with buf equal to NULL. Make
1616 	 * sure buf is never dereferenced if NULL.
1617 	 */
1618 
1619 	/* Prepare video data for processing. */
1620 	if (!stream->bulk.skip_payload && buf != NULL)
1621 		uvc_video_decode_data(uvc_urb, buf, mem, len);
1622 
1623 	/*
1624 	 * Detect the payload end by a URB smaller than the maximum size (or
1625 	 * a payload size equal to the maximum) and process the header again.
1626 	 */
1627 	if (urb->actual_length < urb->transfer_buffer_length ||
1628 	    stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1629 		if (!stream->bulk.skip_payload && buf != NULL) {
1630 			uvc_video_decode_end(stream, buf, stream->bulk.header,
1631 				stream->bulk.payload_size);
1632 			if (buf->state == UVC_BUF_STATE_READY)
1633 				uvc_video_next_buffers(stream, &buf, &meta_buf);
1634 		}
1635 
1636 		stream->bulk.header_size = 0;
1637 		stream->bulk.skip_payload = 0;
1638 		stream->bulk.payload_size = 0;
1639 	}
1640 }
1641 
uvc_video_encode_bulk(struct uvc_urb * uvc_urb,struct uvc_buffer * buf,struct uvc_buffer * meta_buf)1642 static void uvc_video_encode_bulk(struct uvc_urb *uvc_urb,
1643 	struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1644 {
1645 	struct urb *urb = uvc_urb->urb;
1646 	struct uvc_streaming *stream = uvc_urb->stream;
1647 
1648 	u8 *mem = urb->transfer_buffer;
1649 	int len = stream->urb_size, ret;
1650 
1651 	if (buf == NULL) {
1652 		urb->transfer_buffer_length = 0;
1653 		return;
1654 	}
1655 
1656 	/* If the URB is the first of its payload, add the header. */
1657 	if (stream->bulk.header_size == 0) {
1658 		ret = uvc_video_encode_header(stream, buf, mem, len);
1659 		stream->bulk.header_size = ret;
1660 		stream->bulk.payload_size += ret;
1661 		mem += ret;
1662 		len -= ret;
1663 	}
1664 
1665 	/* Process video data. */
1666 	ret = uvc_video_encode_data(stream, buf, mem, len);
1667 
1668 	stream->bulk.payload_size += ret;
1669 	len -= ret;
1670 
1671 	if (buf->bytesused == stream->queue.buf_used ||
1672 	    stream->bulk.payload_size == stream->bulk.max_payload_size) {
1673 		if (buf->bytesused == stream->queue.buf_used) {
1674 			stream->queue.buf_used = 0;
1675 			buf->state = UVC_BUF_STATE_READY;
1676 			buf->buf.sequence = ++stream->sequence;
1677 			uvc_queue_next_buffer(&stream->queue, buf);
1678 			stream->last_fid ^= UVC_STREAM_FID;
1679 		}
1680 
1681 		stream->bulk.header_size = 0;
1682 		stream->bulk.payload_size = 0;
1683 	}
1684 
1685 	urb->transfer_buffer_length = stream->urb_size - len;
1686 }
1687 
uvc_video_complete(struct urb * urb)1688 static void uvc_video_complete(struct urb *urb)
1689 {
1690 	struct uvc_urb *uvc_urb = urb->context;
1691 	struct uvc_streaming *stream = uvc_urb->stream;
1692 	struct uvc_video_queue *queue = &stream->queue;
1693 	struct uvc_video_queue *qmeta = &stream->meta.queue;
1694 	struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
1695 	struct uvc_buffer *buf = NULL;
1696 	struct uvc_buffer *buf_meta = NULL;
1697 	unsigned long flags;
1698 	int ret;
1699 
1700 	switch (urb->status) {
1701 	case 0:
1702 		break;
1703 
1704 	default:
1705 		dev_warn(&stream->intf->dev,
1706 			 "Non-zero status (%d) in video completion handler.\n",
1707 			 urb->status);
1708 		fallthrough;
1709 	case -ENOENT:		/* usb_poison_urb() called. */
1710 		if (stream->frozen)
1711 			return;
1712 		fallthrough;
1713 	case -ECONNRESET:	/* usb_unlink_urb() called. */
1714 	case -ESHUTDOWN:	/* The endpoint is being disabled. */
1715 		uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1716 		if (vb2_qmeta)
1717 			uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
1718 		return;
1719 	}
1720 
1721 	buf = uvc_queue_get_current_buffer(queue);
1722 
1723 	if (vb2_qmeta) {
1724 		spin_lock_irqsave(&qmeta->irqlock, flags);
1725 		if (!list_empty(&qmeta->irqqueue))
1726 			buf_meta = list_first_entry(&qmeta->irqqueue,
1727 						    struct uvc_buffer, queue);
1728 		spin_unlock_irqrestore(&qmeta->irqlock, flags);
1729 	}
1730 
1731 	/* Re-initialise the URB async work. */
1732 	uvc_urb->async_operations = 0;
1733 
1734 	/*
1735 	 * Process the URB headers, and optionally queue expensive memcpy tasks
1736 	 * to be deferred to a work queue.
1737 	 */
1738 	stream->decode(uvc_urb, buf, buf_meta);
1739 
1740 	/* If no async work is needed, resubmit the URB immediately. */
1741 	if (!uvc_urb->async_operations) {
1742 		ret = usb_submit_urb(uvc_urb->urb, GFP_ATOMIC);
1743 		if (ret < 0)
1744 			dev_err(&stream->intf->dev,
1745 				"Failed to resubmit video URB (%d).\n", ret);
1746 		return;
1747 	}
1748 
1749 	queue_work(stream->async_wq, &uvc_urb->work);
1750 }
1751 
1752 /*
1753  * Free transfer buffers.
1754  */
uvc_free_urb_buffers(struct uvc_streaming * stream)1755 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1756 {
1757 	struct usb_device *udev = stream->dev->udev;
1758 	struct uvc_urb *uvc_urb;
1759 
1760 	for_each_uvc_urb(uvc_urb, stream) {
1761 		if (!uvc_urb->buffer)
1762 			continue;
1763 
1764 		usb_free_noncoherent(udev, stream->urb_size, uvc_urb->buffer,
1765 				     uvc_stream_dir(stream), uvc_urb->sgt);
1766 		uvc_urb->buffer = NULL;
1767 		uvc_urb->sgt = NULL;
1768 	}
1769 
1770 	stream->urb_size = 0;
1771 }
1772 
uvc_alloc_urb_buffer(struct uvc_streaming * stream,struct uvc_urb * uvc_urb,gfp_t gfp_flags)1773 static bool uvc_alloc_urb_buffer(struct uvc_streaming *stream,
1774 				 struct uvc_urb *uvc_urb, gfp_t gfp_flags)
1775 {
1776 	struct usb_device *udev = stream->dev->udev;
1777 
1778 	uvc_urb->buffer = usb_alloc_noncoherent(udev, stream->urb_size,
1779 						gfp_flags, &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 > 1; npackets /= 2) {
1816 		stream->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, gfp_flags)) {
1822 				uvc_free_urb_buffers(stream);
1823 				break;
1824 			}
1825 
1826 			uvc_urb->stream = stream;
1827 		}
1828 
1829 		if (i == UVC_URBS) {
1830 			uvc_dbg(stream->dev, VIDEO,
1831 				"Allocated %u URB buffers of %ux%u bytes each\n",
1832 				UVC_URBS, npackets, psize);
1833 			return npackets;
1834 		}
1835 	}
1836 
1837 	uvc_dbg(stream->dev, VIDEO,
1838 		"Failed to allocate URB buffers (%u bytes per packet)\n",
1839 		psize);
1840 	return 0;
1841 }
1842 
1843 /*
1844  * Uninitialize isochronous/bulk URBs and free transfer buffers.
1845  */
uvc_video_stop_transfer(struct uvc_streaming * stream,int free_buffers)1846 static void uvc_video_stop_transfer(struct uvc_streaming *stream,
1847 				    int free_buffers)
1848 {
1849 	struct uvc_urb *uvc_urb;
1850 
1851 	uvc_video_stats_stop(stream);
1852 
1853 	/*
1854 	 * We must poison the URBs rather than kill them to ensure that even
1855 	 * after the completion handler returns, any asynchronous workqueues
1856 	 * will be prevented from resubmitting the URBs.
1857 	 */
1858 	for_each_uvc_urb(uvc_urb, stream)
1859 		usb_poison_urb(uvc_urb->urb);
1860 
1861 	flush_workqueue(stream->async_wq);
1862 
1863 	for_each_uvc_urb(uvc_urb, stream) {
1864 		usb_free_urb(uvc_urb->urb);
1865 		uvc_urb->urb = NULL;
1866 	}
1867 
1868 	if (free_buffers)
1869 		uvc_free_urb_buffers(stream);
1870 }
1871 
1872 /*
1873  * Compute the maximum number of bytes per interval for an endpoint.
1874  */
uvc_endpoint_max_bpi(struct usb_device * dev,struct usb_host_endpoint * ep)1875 u16 uvc_endpoint_max_bpi(struct usb_device *dev, struct usb_host_endpoint *ep)
1876 {
1877 	u16 psize;
1878 
1879 	switch (dev->speed) {
1880 	case USB_SPEED_SUPER:
1881 	case USB_SPEED_SUPER_PLUS:
1882 		return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1883 	default:
1884 		psize = usb_endpoint_maxp(&ep->desc);
1885 		psize *= usb_endpoint_maxp_mult(&ep->desc);
1886 		return psize;
1887 	}
1888 }
1889 
1890 /*
1891  * Initialize isochronous URBs and allocate transfer buffers. The packet size
1892  * is given by the endpoint.
1893  */
uvc_init_video_isoc(struct uvc_streaming * stream,struct usb_host_endpoint * ep,gfp_t gfp_flags)1894 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1895 	struct usb_host_endpoint *ep, gfp_t gfp_flags)
1896 {
1897 	struct urb *urb;
1898 	struct uvc_urb *uvc_urb;
1899 	unsigned int npackets, i;
1900 	u16 psize;
1901 	u32 size;
1902 
1903 	psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1904 	size = stream->ctrl.dwMaxVideoFrameSize;
1905 
1906 	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1907 	if (npackets == 0)
1908 		return -ENOMEM;
1909 
1910 	size = npackets * psize;
1911 
1912 	for_each_uvc_urb(uvc_urb, stream) {
1913 		urb = usb_alloc_urb(npackets, gfp_flags);
1914 		if (urb == NULL) {
1915 			uvc_video_stop_transfer(stream, 1);
1916 			return -ENOMEM;
1917 		}
1918 
1919 		urb->dev = stream->dev->udev;
1920 		urb->context = uvc_urb;
1921 		urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1922 				ep->desc.bEndpointAddress);
1923 		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1924 		urb->transfer_dma = uvc_urb->dma;
1925 		urb->interval = ep->desc.bInterval;
1926 		urb->transfer_buffer = uvc_urb->buffer;
1927 		urb->complete = uvc_video_complete;
1928 		urb->number_of_packets = npackets;
1929 		urb->transfer_buffer_length = size;
1930 		urb->sgt = uvc_urb->sgt;
1931 
1932 		for (i = 0; i < npackets; ++i) {
1933 			urb->iso_frame_desc[i].offset = i * psize;
1934 			urb->iso_frame_desc[i].length = psize;
1935 		}
1936 
1937 		uvc_urb->urb = urb;
1938 	}
1939 
1940 	return 0;
1941 }
1942 
1943 /*
1944  * Initialize bulk URBs and allocate transfer buffers. The packet size is
1945  * given by the endpoint.
1946  */
uvc_init_video_bulk(struct uvc_streaming * stream,struct usb_host_endpoint * ep,gfp_t gfp_flags)1947 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1948 	struct usb_host_endpoint *ep, gfp_t gfp_flags)
1949 {
1950 	struct urb *urb;
1951 	struct uvc_urb *uvc_urb;
1952 	unsigned int npackets, pipe;
1953 	u16 psize;
1954 	u32 size;
1955 
1956 	psize = usb_endpoint_maxp(&ep->desc);
1957 	size = stream->ctrl.dwMaxPayloadTransferSize;
1958 	stream->bulk.max_payload_size = size;
1959 
1960 	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1961 	if (npackets == 0)
1962 		return -ENOMEM;
1963 
1964 	size = npackets * psize;
1965 
1966 	if (usb_endpoint_dir_in(&ep->desc))
1967 		pipe = usb_rcvbulkpipe(stream->dev->udev,
1968 				       ep->desc.bEndpointAddress);
1969 	else
1970 		pipe = usb_sndbulkpipe(stream->dev->udev,
1971 				       ep->desc.bEndpointAddress);
1972 
1973 	if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1974 		size = 0;
1975 
1976 	for_each_uvc_urb(uvc_urb, stream) {
1977 		urb = usb_alloc_urb(0, gfp_flags);
1978 		if (urb == NULL) {
1979 			uvc_video_stop_transfer(stream, 1);
1980 			return -ENOMEM;
1981 		}
1982 
1983 		usb_fill_bulk_urb(urb, stream->dev->udev, pipe,	uvc_urb->buffer,
1984 				  size, uvc_video_complete, uvc_urb);
1985 		urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1986 		urb->transfer_dma = uvc_urb->dma;
1987 		urb->sgt = uvc_urb->sgt;
1988 
1989 		uvc_urb->urb = urb;
1990 	}
1991 
1992 	return 0;
1993 }
1994 
1995 /*
1996  * Initialize isochronous/bulk URBs and allocate transfer buffers.
1997  */
uvc_video_start_transfer(struct uvc_streaming * stream,gfp_t gfp_flags)1998 static int uvc_video_start_transfer(struct uvc_streaming *stream,
1999 				    gfp_t gfp_flags)
2000 {
2001 	struct usb_interface *intf = stream->intf;
2002 	struct usb_host_endpoint *ep;
2003 	struct uvc_urb *uvc_urb;
2004 	unsigned int i;
2005 	int ret;
2006 
2007 	stream->sequence = -1;
2008 	stream->last_fid = -1;
2009 	stream->bulk.header_size = 0;
2010 	stream->bulk.skip_payload = 0;
2011 	stream->bulk.payload_size = 0;
2012 
2013 	uvc_video_stats_start(stream);
2014 
2015 	if (intf->num_altsetting > 1) {
2016 		struct usb_host_endpoint *best_ep = NULL;
2017 		unsigned int best_psize = UINT_MAX;
2018 		unsigned int bandwidth;
2019 		unsigned int altsetting;
2020 		int intfnum = stream->intfnum;
2021 
2022 		/* Isochronous endpoint, select the alternate setting. */
2023 		bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
2024 
2025 		if (bandwidth == 0) {
2026 			uvc_dbg(stream->dev, VIDEO,
2027 				"Device requested null bandwidth, defaulting to lowest\n");
2028 			bandwidth = 1;
2029 		} else {
2030 			uvc_dbg(stream->dev, VIDEO,
2031 				"Device requested %u B/frame bandwidth\n",
2032 				bandwidth);
2033 		}
2034 
2035 		for (i = 0; i < intf->num_altsetting; ++i) {
2036 			struct usb_host_interface *alts;
2037 			unsigned int psize;
2038 
2039 			alts = &intf->altsetting[i];
2040 			ep = uvc_find_endpoint(alts,
2041 				stream->header.bEndpointAddress);
2042 			if (ep == NULL)
2043 				continue;
2044 
2045 			/* Check if the bandwidth is high enough. */
2046 			psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
2047 			if (psize >= bandwidth && psize < best_psize) {
2048 				altsetting = alts->desc.bAlternateSetting;
2049 				best_psize = psize;
2050 				best_ep = ep;
2051 			}
2052 		}
2053 
2054 		if (best_ep == NULL) {
2055 			uvc_dbg(stream->dev, VIDEO,
2056 				"No fast enough alt setting for requested bandwidth\n");
2057 			return -EIO;
2058 		}
2059 
2060 		uvc_dbg(stream->dev, VIDEO,
2061 			"Selecting alternate setting %u (%u B/frame bandwidth)\n",
2062 			altsetting, best_psize);
2063 
2064 		/*
2065 		 * Some devices, namely the Logitech C910 and B910, are unable
2066 		 * to recover from a USB autosuspend, unless the alternate
2067 		 * setting of the streaming interface is toggled.
2068 		 */
2069 		if (stream->dev->quirks & UVC_QUIRK_WAKE_AUTOSUSPEND) {
2070 			usb_set_interface(stream->dev->udev, intfnum,
2071 					  altsetting);
2072 			usb_set_interface(stream->dev->udev, intfnum, 0);
2073 		}
2074 
2075 		ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
2076 		if (ret < 0)
2077 			return ret;
2078 
2079 		ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
2080 	} else {
2081 		/* Bulk endpoint, proceed to URB initialization. */
2082 		ep = uvc_find_endpoint(&intf->altsetting[0],
2083 				stream->header.bEndpointAddress);
2084 		if (ep == NULL)
2085 			return -EIO;
2086 
2087 		/* Reject broken descriptors. */
2088 		if (usb_endpoint_maxp(&ep->desc) == 0)
2089 			return -EIO;
2090 
2091 		ret = uvc_init_video_bulk(stream, ep, gfp_flags);
2092 	}
2093 
2094 	if (ret < 0)
2095 		return ret;
2096 
2097 	/* Submit the URBs. */
2098 	for_each_uvc_urb(uvc_urb, stream) {
2099 		ret = usb_submit_urb(uvc_urb->urb, gfp_flags);
2100 		if (ret < 0) {
2101 			dev_err(&stream->intf->dev,
2102 				"Failed to submit URB %u (%d).\n",
2103 				uvc_urb_index(uvc_urb), ret);
2104 			uvc_video_stop_transfer(stream, 1);
2105 			return ret;
2106 		}
2107 	}
2108 
2109 	/*
2110 	 * The Logitech C920 temporarily forgets that it should not be adjusting
2111 	 * Exposure Absolute during init so restore controls to stored values.
2112 	 */
2113 	if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
2114 		uvc_ctrl_restore_values(stream->dev);
2115 
2116 	return 0;
2117 }
2118 
2119 /* --------------------------------------------------------------------------
2120  * Suspend/resume
2121  */
2122 
2123 /*
2124  * Stop streaming without disabling the video queue.
2125  *
2126  * To let userspace applications resume without trouble, we must not touch the
2127  * video buffers in any way. We mark the device as frozen to make sure the URB
2128  * completion handler won't try to cancel the queue when we kill the URBs.
2129  */
uvc_video_suspend(struct uvc_streaming * stream)2130 int uvc_video_suspend(struct uvc_streaming *stream)
2131 {
2132 	if (!uvc_queue_streaming(&stream->queue))
2133 		return 0;
2134 
2135 	stream->frozen = 1;
2136 	uvc_video_stop_transfer(stream, 0);
2137 	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2138 	return 0;
2139 }
2140 
2141 /*
2142  * Reconfigure the video interface and restart streaming if it was enabled
2143  * before suspend.
2144  *
2145  * If an error occurs, disable the video queue. This will wake all pending
2146  * buffers, making sure userspace applications are notified of the problem
2147  * instead of waiting forever.
2148  */
uvc_video_resume(struct uvc_streaming * stream,int reset)2149 int uvc_video_resume(struct uvc_streaming *stream, int reset)
2150 {
2151 	int ret;
2152 
2153 	/*
2154 	 * If the bus has been reset on resume, set the alternate setting to 0.
2155 	 * This should be the default value, but some devices crash or otherwise
2156 	 * misbehave if they don't receive a SET_INTERFACE request before any
2157 	 * other video control request.
2158 	 */
2159 	if (reset)
2160 		usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2161 
2162 	stream->frozen = 0;
2163 
2164 	uvc_video_clock_reset(&stream->clock);
2165 
2166 	if (!uvc_queue_streaming(&stream->queue))
2167 		return 0;
2168 
2169 	ret = uvc_commit_video(stream, &stream->ctrl);
2170 	if (ret < 0)
2171 		return ret;
2172 
2173 	return uvc_video_start_transfer(stream, GFP_NOIO);
2174 }
2175 
2176 /* ------------------------------------------------------------------------
2177  * Video device
2178  */
2179 
2180 /*
2181  * Initialize the UVC video device by switching to alternate setting 0 and
2182  * retrieve the default format.
2183  *
2184  * Some cameras (namely the Fuji Finepix) set the format and frame
2185  * indexes to zero. The UVC standard doesn't clearly make this a spec
2186  * violation, so try to silently fix the values if possible.
2187  *
2188  * This function is called before registering the device with V4L.
2189  */
uvc_video_init(struct uvc_streaming * stream)2190 int uvc_video_init(struct uvc_streaming *stream)
2191 {
2192 	struct uvc_streaming_control *probe = &stream->ctrl;
2193 	const struct uvc_format *format = NULL;
2194 	const struct uvc_frame *frame = NULL;
2195 	struct uvc_urb *uvc_urb;
2196 	unsigned int i;
2197 	int ret;
2198 
2199 	if (stream->nformats == 0) {
2200 		dev_info(&stream->intf->dev,
2201 			 "No supported video formats found.\n");
2202 		return -EINVAL;
2203 	}
2204 
2205 	atomic_set(&stream->active, 0);
2206 
2207 	/*
2208 	 * Alternate setting 0 should be the default, yet the XBox Live Vision
2209 	 * Cam (and possibly other devices) crash or otherwise misbehave if
2210 	 * they don't receive a SET_INTERFACE request before any other video
2211 	 * control request.
2212 	 */
2213 	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2214 
2215 	/*
2216 	 * Set the streaming probe control with default streaming parameters
2217 	 * retrieved from the device. Webcams that don't support GET_DEF
2218 	 * requests on the probe control will just keep their current streaming
2219 	 * parameters.
2220 	 */
2221 	if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
2222 		uvc_set_video_ctrl(stream, probe, 1);
2223 
2224 	/*
2225 	 * Initialize the streaming parameters with the probe control current
2226 	 * value. This makes sure SET_CUR requests on the streaming commit
2227 	 * control will always use values retrieved from a successful GET_CUR
2228 	 * request on the probe control, as required by the UVC specification.
2229 	 */
2230 	ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
2231 
2232 	/*
2233 	 * Elgato Cam Link 4k can be in a stalled state if the resolution of
2234 	 * the external source has changed while the firmware initializes.
2235 	 * Once in this state, the device is useless until it receives a
2236 	 * USB reset. It has even been observed that the stalled state will
2237 	 * continue even after unplugging the device.
2238 	 */
2239 	if (ret == -EPROTO &&
2240 	    usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k)) {
2241 		dev_err(&stream->intf->dev, "Elgato Cam Link 4K firmware crash detected\n");
2242 		dev_err(&stream->intf->dev, "Resetting the device, unplug and replug to recover\n");
2243 		usb_reset_device(stream->dev->udev);
2244 	}
2245 
2246 	if (ret < 0)
2247 		return ret;
2248 
2249 	/*
2250 	 * Check if the default format descriptor exists. Use the first
2251 	 * available format otherwise.
2252 	 */
2253 	for (i = stream->nformats; i > 0; --i) {
2254 		format = &stream->formats[i-1];
2255 		if (format->index == probe->bFormatIndex)
2256 			break;
2257 	}
2258 
2259 	if (format->nframes == 0) {
2260 		dev_info(&stream->intf->dev,
2261 			 "No frame descriptor found for the default format.\n");
2262 		return -EINVAL;
2263 	}
2264 
2265 	/*
2266 	 * Zero bFrameIndex might be correct. Stream-based formats (including
2267 	 * MPEG-2 TS and DV) do not support frames but have a dummy frame
2268 	 * descriptor with bFrameIndex set to zero. If the default frame
2269 	 * descriptor is not found, use the first available frame.
2270 	 */
2271 	for (i = format->nframes; i > 0; --i) {
2272 		frame = &format->frames[i-1];
2273 		if (frame->bFrameIndex == probe->bFrameIndex)
2274 			break;
2275 	}
2276 
2277 	probe->bFormatIndex = format->index;
2278 	probe->bFrameIndex = frame->bFrameIndex;
2279 
2280 	stream->def_format = format;
2281 	stream->cur_format = format;
2282 	stream->cur_frame = frame;
2283 
2284 	/* Select the video decoding function */
2285 	if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2286 		if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
2287 			stream->decode = uvc_video_decode_isight;
2288 		else if (stream->intf->num_altsetting > 1)
2289 			stream->decode = uvc_video_decode_isoc;
2290 		else
2291 			stream->decode = uvc_video_decode_bulk;
2292 	} else {
2293 		if (stream->intf->num_altsetting == 1)
2294 			stream->decode = uvc_video_encode_bulk;
2295 		else {
2296 			dev_info(&stream->intf->dev,
2297 				 "Isochronous endpoints are not supported for video output devices.\n");
2298 			return -EINVAL;
2299 		}
2300 	}
2301 
2302 	/* Prepare asynchronous work items. */
2303 	for_each_uvc_urb(uvc_urb, stream)
2304 		INIT_WORK(&uvc_urb->work, uvc_video_copy_data_work);
2305 
2306 	return 0;
2307 }
2308 
uvc_video_start_streaming(struct uvc_streaming * stream)2309 int uvc_video_start_streaming(struct uvc_streaming *stream)
2310 {
2311 	int ret;
2312 
2313 	ret = uvc_video_clock_init(&stream->clock);
2314 	if (ret < 0)
2315 		return ret;
2316 
2317 	/* Commit the streaming parameters. */
2318 	ret = uvc_commit_video(stream, &stream->ctrl);
2319 	if (ret < 0)
2320 		goto error_commit;
2321 
2322 	ret = uvc_video_start_transfer(stream, GFP_KERNEL);
2323 	if (ret < 0)
2324 		goto error_video;
2325 
2326 	return 0;
2327 
2328 error_video:
2329 	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2330 error_commit:
2331 	uvc_video_clock_cleanup(&stream->clock);
2332 
2333 	return ret;
2334 }
2335 
uvc_video_stop_streaming(struct uvc_streaming * stream)2336 void uvc_video_stop_streaming(struct uvc_streaming *stream)
2337 {
2338 	uvc_video_stop_transfer(stream, 1);
2339 
2340 	if (stream->intf->num_altsetting > 1) {
2341 		usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2342 	} else {
2343 		/*
2344 		 * UVC doesn't specify how to inform a bulk-based device
2345 		 * when the video stream is stopped. Windows sends a
2346 		 * CLEAR_FEATURE(HALT) request to the video streaming
2347 		 * bulk endpoint, mimic the same behaviour.
2348 		 */
2349 		unsigned int epnum = stream->header.bEndpointAddress
2350 				   & USB_ENDPOINT_NUMBER_MASK;
2351 		unsigned int dir = stream->header.bEndpointAddress
2352 				 & USB_ENDPOINT_DIR_MASK;
2353 		unsigned int pipe;
2354 
2355 		pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
2356 		usb_clear_halt(stream->dev->udev, pipe);
2357 	}
2358 
2359 	uvc_video_clock_cleanup(&stream->clock);
2360 }
2361