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