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