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