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