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