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