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