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