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 
__uvc_query_ctrl(struct uvc_device * dev,__u8 query,__u8 unit,__u8 intfnum,__u8 cs,void * data,__u16 size,int timeout)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 
uvc_query_name(__u8 query)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 
uvc_query_ctrl(struct uvc_device * dev,__u8 query,__u8 unit,__u8 intfnum,__u8 cs,void * data,__u16 size)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 
uvc_fixup_video_ctrl(struct uvc_streaming * stream,struct uvc_streaming_control * ctrl)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 
uvc_get_video_ctrl(struct uvc_streaming * stream,struct uvc_streaming_control * ctrl,int probe,__u8 query)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 
uvc_set_video_ctrl(struct uvc_streaming * stream,struct uvc_streaming_control * ctrl,int probe)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 
uvc_probe_video(struct uvc_streaming * stream,struct uvc_streaming_control * probe)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 
uvc_commit_video(struct uvc_streaming * stream,struct uvc_streaming_control * probe)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
uvc_video_clock_decode(struct uvc_streaming * stream,struct uvc_buffer * buf,const __u8 * data,int len)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 
uvc_video_clock_init(struct uvc_streaming * stream)471 static int uvc_video_clock_init(struct uvc_streaming *stream)
472 {
473 	struct uvc_clock *clock = &stream->clock;
474 
475 	spin_lock_init(&clock->lock);
476 	clock->head = 0;
477 	clock->count = 0;
478 	clock->size = 32;
479 	clock->last_sof = -1;
480 	clock->sof_offset = -1;
481 
482 	clock->samples = kmalloc(clock->size * sizeof(*clock->samples),
483 				 GFP_KERNEL);
484 	if (clock->samples == NULL)
485 		return -ENOMEM;
486 
487 	return 0;
488 }
489 
uvc_video_clock_cleanup(struct uvc_streaming * stream)490 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
491 {
492 	kfree(stream->clock.samples);
493 	stream->clock.samples = NULL;
494 }
495 
496 /*
497  * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
498  *
499  * Host SOF counters reported by usb_get_current_frame_number() usually don't
500  * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
501  * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
502  * controller and its configuration.
503  *
504  * We thus need to recover the SOF value corresponding to the host frame number.
505  * As the device and host frame numbers are sampled in a short interval, the
506  * difference between their values should be equal to a small delta plus an
507  * integer multiple of 256 caused by the host frame number limited precision.
508  *
509  * To obtain the recovered host SOF value, compute the small delta by masking
510  * the high bits of the host frame counter and device SOF difference and add it
511  * to the device SOF value.
512  */
uvc_video_clock_host_sof(const struct uvc_clock_sample * sample)513 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
514 {
515 	/* The delta value can be negative. */
516 	s8 delta_sof;
517 
518 	delta_sof = (sample->host_sof - sample->dev_sof) & 255;
519 
520 	return (sample->dev_sof + delta_sof) & 2047;
521 }
522 
523 /*
524  * uvc_video_clock_update - Update the buffer timestamp
525  *
526  * This function converts the buffer PTS timestamp to the host clock domain by
527  * going through the USB SOF clock domain and stores the result in the V4L2
528  * buffer timestamp field.
529  *
530  * The relationship between the device clock and the host clock isn't known.
531  * However, the device and the host share the common USB SOF clock which can be
532  * used to recover that relationship.
533  *
534  * The relationship between the device clock and the USB SOF clock is considered
535  * to be linear over the clock samples sliding window and is given by
536  *
537  * SOF = m * PTS + p
538  *
539  * Several methods to compute the slope (m) and intercept (p) can be used. As
540  * the clock drift should be small compared to the sliding window size, we
541  * assume that the line that goes through the points at both ends of the window
542  * is a good approximation. Naming those points P1 and P2, we get
543  *
544  * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
545  *     + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
546  *
547  * or
548  *
549  * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)   (1)
550  *
551  * to avoid loosing precision in the division. Similarly, the host timestamp is
552  * computed with
553  *
554  * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1)	     (2)
555  *
556  * SOF values are coded on 11 bits by USB. We extend their precision with 16
557  * decimal bits, leading to a 11.16 coding.
558  *
559  * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
560  * be normalized using the nominal device clock frequency reported through the
561  * UVC descriptors.
562  *
563  * Both the PTS/STC and SOF counters roll over, after a fixed but device
564  * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
565  * sliding window size is smaller than the rollover period, differences computed
566  * on unsigned integers will produce the correct result. However, the p term in
567  * the linear relations will be miscomputed.
568  *
569  * To fix the issue, we subtract a constant from the PTS and STC values to bring
570  * PTS to half the 32 bit STC range. The sliding window STC values then fit into
571  * the 32 bit range without any rollover.
572  *
573  * Similarly, we add 2048 to the device SOF values to make sure that the SOF
574  * computed by (1) will never be smaller than 0. This offset is then compensated
575  * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
576  * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
577  * lower than 4096, and the host SOF counters can have rolled over to 2048. This
578  * case is handled by subtracting 2048 from the SOF value if it exceeds the host
579  * SOF value at the end of the sliding window.
580  *
581  * Finally we subtract a constant from the host timestamps to bring the first
582  * timestamp of the sliding window to 1s.
583  */
uvc_video_clock_update(struct uvc_streaming * stream,struct v4l2_buffer * v4l2_buf,struct uvc_buffer * buf)584 void uvc_video_clock_update(struct uvc_streaming *stream,
585 			    struct v4l2_buffer *v4l2_buf,
586 			    struct uvc_buffer *buf)
587 {
588 	struct uvc_clock *clock = &stream->clock;
589 	struct uvc_clock_sample *first;
590 	struct uvc_clock_sample *last;
591 	unsigned long flags;
592 	struct timespec ts;
593 	u32 delta_stc;
594 	u32 y1, y2;
595 	u32 x1, x2;
596 	u32 mean;
597 	u32 sof;
598 	u32 div;
599 	u32 rem;
600 	u64 y;
601 
602 	spin_lock_irqsave(&clock->lock, flags);
603 
604 	if (clock->count < clock->size)
605 		goto done;
606 
607 	first = &clock->samples[clock->head];
608 	last = &clock->samples[(clock->head - 1) % clock->size];
609 
610 	/* First step, PTS to SOF conversion. */
611 	delta_stc = buf->pts - (1UL << 31);
612 	x1 = first->dev_stc - delta_stc;
613 	x2 = last->dev_stc - delta_stc;
614 	if (x1 == x2)
615 		goto done;
616 
617 	y1 = (first->dev_sof + 2048) << 16;
618 	y2 = (last->dev_sof + 2048) << 16;
619 	if (y2 < y1)
620 		y2 += 2048 << 16;
621 
622 	y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
623 	  - (u64)y2 * (u64)x1;
624 	y = div_u64(y, x2 - x1);
625 
626 	sof = y;
627 
628 	uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
629 		  "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
630 		  stream->dev->name, buf->pts,
631 		  y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
632 		  sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
633 		  x1, x2, y1, y2, clock->sof_offset);
634 
635 	/* Second step, SOF to host clock conversion. */
636 	x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
637 	x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
638 	if (x2 < x1)
639 		x2 += 2048 << 16;
640 	if (x1 == x2)
641 		goto done;
642 
643 	ts = timespec_sub(last->host_ts, first->host_ts);
644 	y1 = NSEC_PER_SEC;
645 	y2 = (ts.tv_sec + 1) * NSEC_PER_SEC + ts.tv_nsec;
646 
647 	/* Interpolated and host SOF timestamps can wrap around at slightly
648 	 * different times. Handle this by adding or removing 2048 to or from
649 	 * the computed SOF value to keep it close to the SOF samples mean
650 	 * value.
651 	 */
652 	mean = (x1 + x2) / 2;
653 	if (mean - (1024 << 16) > sof)
654 		sof += 2048 << 16;
655 	else if (sof > mean + (1024 << 16))
656 		sof -= 2048 << 16;
657 
658 	y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
659 	  - (u64)y2 * (u64)x1;
660 	y = div_u64(y, x2 - x1);
661 
662 	div = div_u64_rem(y, NSEC_PER_SEC, &rem);
663 	ts.tv_sec = first->host_ts.tv_sec - 1 + div;
664 	ts.tv_nsec = first->host_ts.tv_nsec + rem;
665 	if (ts.tv_nsec >= NSEC_PER_SEC) {
666 		ts.tv_sec++;
667 		ts.tv_nsec -= NSEC_PER_SEC;
668 	}
669 
670 	uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %lu.%06lu "
671 		  "buf ts %lu.%06lu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
672 		  stream->dev->name,
673 		  sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
674 		  y, ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC,
675 		  v4l2_buf->timestamp.tv_sec, v4l2_buf->timestamp.tv_usec,
676 		  x1, first->host_sof, first->dev_sof,
677 		  x2, last->host_sof, last->dev_sof, y1, y2);
678 
679 	/* Update the V4L2 buffer. */
680 	v4l2_buf->timestamp.tv_sec = ts.tv_sec;
681 	v4l2_buf->timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
682 
683 done:
684 	spin_unlock_irqrestore(&stream->clock.lock, flags);
685 }
686 
687 /* ------------------------------------------------------------------------
688  * Stream statistics
689  */
690 
uvc_video_stats_decode(struct uvc_streaming * stream,const __u8 * data,int len)691 static void uvc_video_stats_decode(struct uvc_streaming *stream,
692 		const __u8 *data, int len)
693 {
694 	unsigned int header_size;
695 	bool has_pts = false;
696 	bool has_scr = false;
697 	u16 uninitialized_var(scr_sof);
698 	u32 uninitialized_var(scr_stc);
699 	u32 uninitialized_var(pts);
700 
701 	if (stream->stats.stream.nb_frames == 0 &&
702 	    stream->stats.frame.nb_packets == 0)
703 		ktime_get_ts(&stream->stats.stream.start_ts);
704 
705 	switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
706 	case UVC_STREAM_PTS | UVC_STREAM_SCR:
707 		header_size = 12;
708 		has_pts = true;
709 		has_scr = true;
710 		break;
711 	case UVC_STREAM_PTS:
712 		header_size = 6;
713 		has_pts = true;
714 		break;
715 	case UVC_STREAM_SCR:
716 		header_size = 8;
717 		has_scr = true;
718 		break;
719 	default:
720 		header_size = 2;
721 		break;
722 	}
723 
724 	/* Check for invalid headers. */
725 	if (len < header_size || data[0] < header_size) {
726 		stream->stats.frame.nb_invalid++;
727 		return;
728 	}
729 
730 	/* Extract the timestamps. */
731 	if (has_pts)
732 		pts = get_unaligned_le32(&data[2]);
733 
734 	if (has_scr) {
735 		scr_stc = get_unaligned_le32(&data[header_size - 6]);
736 		scr_sof = get_unaligned_le16(&data[header_size - 2]);
737 	}
738 
739 	/* Is PTS constant through the whole frame ? */
740 	if (has_pts && stream->stats.frame.nb_pts) {
741 		if (stream->stats.frame.pts != pts) {
742 			stream->stats.frame.nb_pts_diffs++;
743 			stream->stats.frame.last_pts_diff =
744 				stream->stats.frame.nb_packets;
745 		}
746 	}
747 
748 	if (has_pts) {
749 		stream->stats.frame.nb_pts++;
750 		stream->stats.frame.pts = pts;
751 	}
752 
753 	/* Do all frames have a PTS in their first non-empty packet, or before
754 	 * their first empty packet ?
755 	 */
756 	if (stream->stats.frame.size == 0) {
757 		if (len > header_size)
758 			stream->stats.frame.has_initial_pts = has_pts;
759 		if (len == header_size && has_pts)
760 			stream->stats.frame.has_early_pts = true;
761 	}
762 
763 	/* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
764 	if (has_scr && stream->stats.frame.nb_scr) {
765 		if (stream->stats.frame.scr_stc != scr_stc)
766 			stream->stats.frame.nb_scr_diffs++;
767 	}
768 
769 	if (has_scr) {
770 		/* Expand the SOF counter to 32 bits and store its value. */
771 		if (stream->stats.stream.nb_frames > 0 ||
772 		    stream->stats.frame.nb_scr > 0)
773 			stream->stats.stream.scr_sof_count +=
774 				(scr_sof - stream->stats.stream.scr_sof) % 2048;
775 		stream->stats.stream.scr_sof = scr_sof;
776 
777 		stream->stats.frame.nb_scr++;
778 		stream->stats.frame.scr_stc = scr_stc;
779 		stream->stats.frame.scr_sof = scr_sof;
780 
781 		if (scr_sof < stream->stats.stream.min_sof)
782 			stream->stats.stream.min_sof = scr_sof;
783 		if (scr_sof > stream->stats.stream.max_sof)
784 			stream->stats.stream.max_sof = scr_sof;
785 	}
786 
787 	/* Record the first non-empty packet number. */
788 	if (stream->stats.frame.size == 0 && len > header_size)
789 		stream->stats.frame.first_data = stream->stats.frame.nb_packets;
790 
791 	/* Update the frame size. */
792 	stream->stats.frame.size += len - header_size;
793 
794 	/* Update the packets counters. */
795 	stream->stats.frame.nb_packets++;
796 	if (len > header_size)
797 		stream->stats.frame.nb_empty++;
798 
799 	if (data[1] & UVC_STREAM_ERR)
800 		stream->stats.frame.nb_errors++;
801 }
802 
uvc_video_stats_update(struct uvc_streaming * stream)803 static void uvc_video_stats_update(struct uvc_streaming *stream)
804 {
805 	struct uvc_stats_frame *frame = &stream->stats.frame;
806 
807 	uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
808 		  "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
809 		  "last pts/stc/sof %u/%u/%u\n",
810 		  stream->sequence, frame->first_data,
811 		  frame->nb_packets - frame->nb_empty, frame->nb_packets,
812 		  frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
813 		  frame->has_early_pts ? "" : "!",
814 		  frame->has_initial_pts ? "" : "!",
815 		  frame->nb_scr_diffs, frame->nb_scr,
816 		  frame->pts, frame->scr_stc, frame->scr_sof);
817 
818 	stream->stats.stream.nb_frames++;
819 	stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
820 	stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
821 	stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
822 	stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
823 
824 	if (frame->has_early_pts)
825 		stream->stats.stream.nb_pts_early++;
826 	if (frame->has_initial_pts)
827 		stream->stats.stream.nb_pts_initial++;
828 	if (frame->last_pts_diff <= frame->first_data)
829 		stream->stats.stream.nb_pts_constant++;
830 	if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
831 		stream->stats.stream.nb_scr_count_ok++;
832 	if (frame->nb_scr_diffs + 1 == frame->nb_scr)
833 		stream->stats.stream.nb_scr_diffs_ok++;
834 
835 	memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
836 }
837 
uvc_video_stats_dump(struct uvc_streaming * stream,char * buf,size_t size)838 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
839 			    size_t size)
840 {
841 	unsigned int scr_sof_freq;
842 	unsigned int duration;
843 	struct timespec ts;
844 	size_t count = 0;
845 
846 	ts.tv_sec = stream->stats.stream.stop_ts.tv_sec
847 		  - stream->stats.stream.start_ts.tv_sec;
848 	ts.tv_nsec = stream->stats.stream.stop_ts.tv_nsec
849 		   - stream->stats.stream.start_ts.tv_nsec;
850 	if (ts.tv_nsec < 0) {
851 		ts.tv_sec--;
852 		ts.tv_nsec += 1000000000;
853 	}
854 
855 	/* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
856 	 * frequency this will not overflow before more than 1h.
857 	 */
858 	duration = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
859 	if (duration != 0)
860 		scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
861 			     / duration;
862 	else
863 		scr_sof_freq = 0;
864 
865 	count += scnprintf(buf + count, size - count,
866 			   "frames:  %u\npackets: %u\nempty:   %u\n"
867 			   "errors:  %u\ninvalid: %u\n",
868 			   stream->stats.stream.nb_frames,
869 			   stream->stats.stream.nb_packets,
870 			   stream->stats.stream.nb_empty,
871 			   stream->stats.stream.nb_errors,
872 			   stream->stats.stream.nb_invalid);
873 	count += scnprintf(buf + count, size - count,
874 			   "pts: %u early, %u initial, %u ok\n",
875 			   stream->stats.stream.nb_pts_early,
876 			   stream->stats.stream.nb_pts_initial,
877 			   stream->stats.stream.nb_pts_constant);
878 	count += scnprintf(buf + count, size - count,
879 			   "scr: %u count ok, %u diff ok\n",
880 			   stream->stats.stream.nb_scr_count_ok,
881 			   stream->stats.stream.nb_scr_diffs_ok);
882 	count += scnprintf(buf + count, size - count,
883 			   "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
884 			   stream->stats.stream.min_sof,
885 			   stream->stats.stream.max_sof,
886 			   scr_sof_freq / 1000, scr_sof_freq % 1000);
887 
888 	return count;
889 }
890 
uvc_video_stats_start(struct uvc_streaming * stream)891 static void uvc_video_stats_start(struct uvc_streaming *stream)
892 {
893 	memset(&stream->stats, 0, sizeof(stream->stats));
894 	stream->stats.stream.min_sof = 2048;
895 }
896 
uvc_video_stats_stop(struct uvc_streaming * stream)897 static void uvc_video_stats_stop(struct uvc_streaming *stream)
898 {
899 	ktime_get_ts(&stream->stats.stream.stop_ts);
900 }
901 
902 /* ------------------------------------------------------------------------
903  * Video codecs
904  */
905 
906 /* Video payload decoding is handled by uvc_video_decode_start(),
907  * uvc_video_decode_data() and uvc_video_decode_end().
908  *
909  * uvc_video_decode_start is called with URB data at the start of a bulk or
910  * isochronous payload. It processes header data and returns the header size
911  * in bytes if successful. If an error occurs, it returns a negative error
912  * code. The following error codes have special meanings.
913  *
914  * - EAGAIN informs the caller that the current video buffer should be marked
915  *   as done, and that the function should be called again with the same data
916  *   and a new video buffer. This is used when end of frame conditions can be
917  *   reliably detected at the beginning of the next frame only.
918  *
919  * If an error other than -EAGAIN is returned, the caller will drop the current
920  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
921  * made until the next payload. -ENODATA can be used to drop the current
922  * payload if no other error code is appropriate.
923  *
924  * uvc_video_decode_data is called for every URB with URB data. It copies the
925  * data to the video buffer.
926  *
927  * uvc_video_decode_end is called with header data at the end of a bulk or
928  * isochronous payload. It performs any additional header data processing and
929  * returns 0 or a negative error code if an error occurred. As header data have
930  * already been processed by uvc_video_decode_start, this functions isn't
931  * required to perform sanity checks a second time.
932  *
933  * For isochronous transfers where a payload is always transferred in a single
934  * URB, the three functions will be called in a row.
935  *
936  * To let the decoder process header data and update its internal state even
937  * when no video buffer is available, uvc_video_decode_start must be prepared
938  * to be called with a NULL buf parameter. uvc_video_decode_data and
939  * uvc_video_decode_end will never be called with a NULL buffer.
940  */
uvc_video_decode_start(struct uvc_streaming * stream,struct uvc_buffer * buf,const __u8 * data,int len)941 static int uvc_video_decode_start(struct uvc_streaming *stream,
942 		struct uvc_buffer *buf, const __u8 *data, int len)
943 {
944 	__u8 fid;
945 
946 	/* Sanity checks:
947 	 * - packet must be at least 2 bytes long
948 	 * - bHeaderLength value must be at least 2 bytes (see above)
949 	 * - bHeaderLength value can't be larger than the packet size.
950 	 */
951 	if (len < 2 || data[0] < 2 || data[0] > len) {
952 		stream->stats.frame.nb_invalid++;
953 		return -EINVAL;
954 	}
955 
956 	fid = data[1] & UVC_STREAM_FID;
957 
958 	/* Increase the sequence number regardless of any buffer states, so
959 	 * that discontinuous sequence numbers always indicate lost frames.
960 	 */
961 	if (stream->last_fid != fid) {
962 		stream->sequence++;
963 		if (stream->sequence)
964 			uvc_video_stats_update(stream);
965 	}
966 
967 	uvc_video_clock_decode(stream, buf, data, len);
968 	uvc_video_stats_decode(stream, data, len);
969 
970 	/* Store the payload FID bit and return immediately when the buffer is
971 	 * NULL.
972 	 */
973 	if (buf == NULL) {
974 		stream->last_fid = fid;
975 		return -ENODATA;
976 	}
977 
978 	/* Mark the buffer as bad if the error bit is set. */
979 	if (data[1] & UVC_STREAM_ERR) {
980 		uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
981 			  "set).\n");
982 		buf->error = 1;
983 	}
984 
985 	/* Synchronize to the input stream by waiting for the FID bit to be
986 	 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
987 	 * stream->last_fid is initialized to -1, so the first isochronous
988 	 * frame will always be in sync.
989 	 *
990 	 * If the device doesn't toggle the FID bit, invert stream->last_fid
991 	 * when the EOF bit is set to force synchronisation on the next packet.
992 	 */
993 	if (buf->state != UVC_BUF_STATE_ACTIVE) {
994 		struct timespec ts;
995 
996 		if (fid == stream->last_fid) {
997 			uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
998 				"sync).\n");
999 			if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1000 			    (data[1] & UVC_STREAM_EOF))
1001 				stream->last_fid ^= UVC_STREAM_FID;
1002 			return -ENODATA;
1003 		}
1004 
1005 		if (uvc_clock_param == CLOCK_MONOTONIC)
1006 			ktime_get_ts(&ts);
1007 		else
1008 			ktime_get_real_ts(&ts);
1009 
1010 		buf->buf.v4l2_buf.sequence = stream->sequence;
1011 		buf->buf.v4l2_buf.timestamp.tv_sec = ts.tv_sec;
1012 		buf->buf.v4l2_buf.timestamp.tv_usec =
1013 			ts.tv_nsec / NSEC_PER_USEC;
1014 
1015 		/* TODO: Handle PTS and SCR. */
1016 		buf->state = UVC_BUF_STATE_ACTIVE;
1017 	}
1018 
1019 	/* Mark the buffer as done if we're at the beginning of a new frame.
1020 	 * End of frame detection is better implemented by checking the EOF
1021 	 * bit (FID bit toggling is delayed by one frame compared to the EOF
1022 	 * bit), but some devices don't set the bit at end of frame (and the
1023 	 * last payload can be lost anyway). We thus must check if the FID has
1024 	 * been toggled.
1025 	 *
1026 	 * stream->last_fid is initialized to -1, so the first isochronous
1027 	 * frame will never trigger an end of frame detection.
1028 	 *
1029 	 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1030 	 * as it doesn't make sense to return an empty buffer. This also
1031 	 * avoids detecting end of frame conditions at FID toggling if the
1032 	 * previous payload had the EOF bit set.
1033 	 */
1034 	if (fid != stream->last_fid && buf->bytesused != 0) {
1035 		uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1036 				"toggled).\n");
1037 		buf->state = UVC_BUF_STATE_READY;
1038 		return -EAGAIN;
1039 	}
1040 
1041 	stream->last_fid = fid;
1042 
1043 	return data[0];
1044 }
1045 
uvc_video_decode_data(struct uvc_streaming * stream,struct uvc_buffer * buf,const __u8 * data,int len)1046 static void uvc_video_decode_data(struct uvc_streaming *stream,
1047 		struct uvc_buffer *buf, const __u8 *data, int len)
1048 {
1049 	unsigned int maxlen, nbytes;
1050 	void *mem;
1051 
1052 	if (len <= 0)
1053 		return;
1054 
1055 	/* Copy the video data to the buffer. */
1056 	maxlen = buf->length - buf->bytesused;
1057 	mem = buf->mem + buf->bytesused;
1058 	nbytes = min((unsigned int)len, maxlen);
1059 	memcpy(mem, data, nbytes);
1060 	buf->bytesused += nbytes;
1061 
1062 	/* Complete the current frame if the buffer size was exceeded. */
1063 	if (len > maxlen) {
1064 		uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1065 		buf->state = UVC_BUF_STATE_READY;
1066 	}
1067 }
1068 
uvc_video_decode_end(struct uvc_streaming * stream,struct uvc_buffer * buf,const __u8 * data,int len)1069 static void uvc_video_decode_end(struct uvc_streaming *stream,
1070 		struct uvc_buffer *buf, const __u8 *data, int len)
1071 {
1072 	/* Mark the buffer as done if the EOF marker is set. */
1073 	if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1074 		uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1075 		if (data[0] == len)
1076 			uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1077 		buf->state = UVC_BUF_STATE_READY;
1078 		if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1079 			stream->last_fid ^= UVC_STREAM_FID;
1080 	}
1081 }
1082 
1083 /* Video payload encoding is handled by uvc_video_encode_header() and
1084  * uvc_video_encode_data(). Only bulk transfers are currently supported.
1085  *
1086  * uvc_video_encode_header is called at the start of a payload. It adds header
1087  * data to the transfer buffer and returns the header size. As the only known
1088  * UVC output device transfers a whole frame in a single payload, the EOF bit
1089  * is always set in the header.
1090  *
1091  * uvc_video_encode_data is called for every URB and copies the data from the
1092  * video buffer to the transfer buffer.
1093  */
uvc_video_encode_header(struct uvc_streaming * stream,struct uvc_buffer * buf,__u8 * data,int len)1094 static int uvc_video_encode_header(struct uvc_streaming *stream,
1095 		struct uvc_buffer *buf, __u8 *data, int len)
1096 {
1097 	data[0] = 2;	/* Header length */
1098 	data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1099 		| (stream->last_fid & UVC_STREAM_FID);
1100 	return 2;
1101 }
1102 
uvc_video_encode_data(struct uvc_streaming * stream,struct uvc_buffer * buf,__u8 * data,int len)1103 static int uvc_video_encode_data(struct uvc_streaming *stream,
1104 		struct uvc_buffer *buf, __u8 *data, int len)
1105 {
1106 	struct uvc_video_queue *queue = &stream->queue;
1107 	unsigned int nbytes;
1108 	void *mem;
1109 
1110 	/* Copy video data to the URB buffer. */
1111 	mem = buf->mem + queue->buf_used;
1112 	nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1113 	nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1114 			nbytes);
1115 	memcpy(data, mem, nbytes);
1116 
1117 	queue->buf_used += nbytes;
1118 
1119 	return nbytes;
1120 }
1121 
1122 /* ------------------------------------------------------------------------
1123  * URB handling
1124  */
1125 
1126 /*
1127  * Completion handler for video URBs.
1128  */
uvc_video_decode_isoc(struct urb * urb,struct uvc_streaming * stream,struct uvc_buffer * buf)1129 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1130 	struct uvc_buffer *buf)
1131 {
1132 	u8 *mem;
1133 	int ret, i;
1134 
1135 	for (i = 0; i < urb->number_of_packets; ++i) {
1136 		if (urb->iso_frame_desc[i].status < 0) {
1137 			uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1138 				"lost (%d).\n", urb->iso_frame_desc[i].status);
1139 			/* Mark the buffer as faulty. */
1140 			if (buf != NULL)
1141 				buf->error = 1;
1142 			continue;
1143 		}
1144 
1145 		/* Decode the payload header. */
1146 		mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1147 		do {
1148 			ret = uvc_video_decode_start(stream, buf, mem,
1149 				urb->iso_frame_desc[i].actual_length);
1150 			if (ret == -EAGAIN)
1151 				buf = uvc_queue_next_buffer(&stream->queue,
1152 							    buf);
1153 		} while (ret == -EAGAIN);
1154 
1155 		if (ret < 0)
1156 			continue;
1157 
1158 		/* Decode the payload data. */
1159 		uvc_video_decode_data(stream, buf, mem + ret,
1160 			urb->iso_frame_desc[i].actual_length - ret);
1161 
1162 		/* Process the header again. */
1163 		uvc_video_decode_end(stream, buf, mem,
1164 			urb->iso_frame_desc[i].actual_length);
1165 
1166 		if (buf->state == UVC_BUF_STATE_READY) {
1167 			if (buf->length != buf->bytesused &&
1168 			    !(stream->cur_format->flags &
1169 			      UVC_FMT_FLAG_COMPRESSED))
1170 				buf->error = 1;
1171 
1172 			buf = uvc_queue_next_buffer(&stream->queue, buf);
1173 		}
1174 	}
1175 }
1176 
uvc_video_decode_bulk(struct urb * urb,struct uvc_streaming * stream,struct uvc_buffer * buf)1177 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1178 	struct uvc_buffer *buf)
1179 {
1180 	u8 *mem;
1181 	int len, ret;
1182 
1183 	if (urb->actual_length == 0)
1184 		return;
1185 
1186 	mem = urb->transfer_buffer;
1187 	len = urb->actual_length;
1188 	stream->bulk.payload_size += len;
1189 
1190 	/* If the URB is the first of its payload, decode and save the
1191 	 * header.
1192 	 */
1193 	if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1194 		do {
1195 			ret = uvc_video_decode_start(stream, buf, mem, len);
1196 			if (ret == -EAGAIN)
1197 				buf = uvc_queue_next_buffer(&stream->queue,
1198 							    buf);
1199 		} while (ret == -EAGAIN);
1200 
1201 		/* If an error occurred skip the rest of the payload. */
1202 		if (ret < 0 || buf == NULL) {
1203 			stream->bulk.skip_payload = 1;
1204 		} else {
1205 			memcpy(stream->bulk.header, mem, ret);
1206 			stream->bulk.header_size = ret;
1207 
1208 			mem += ret;
1209 			len -= ret;
1210 		}
1211 	}
1212 
1213 	/* The buffer queue might have been cancelled while a bulk transfer
1214 	 * was in progress, so we can reach here with buf equal to NULL. Make
1215 	 * sure buf is never dereferenced if NULL.
1216 	 */
1217 
1218 	/* Process video data. */
1219 	if (!stream->bulk.skip_payload && buf != NULL)
1220 		uvc_video_decode_data(stream, buf, mem, len);
1221 
1222 	/* Detect the payload end by a URB smaller than the maximum size (or
1223 	 * a payload size equal to the maximum) and process the header again.
1224 	 */
1225 	if (urb->actual_length < urb->transfer_buffer_length ||
1226 	    stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1227 		if (!stream->bulk.skip_payload && buf != NULL) {
1228 			uvc_video_decode_end(stream, buf, stream->bulk.header,
1229 				stream->bulk.payload_size);
1230 			if (buf->state == UVC_BUF_STATE_READY)
1231 				buf = uvc_queue_next_buffer(&stream->queue,
1232 							    buf);
1233 		}
1234 
1235 		stream->bulk.header_size = 0;
1236 		stream->bulk.skip_payload = 0;
1237 		stream->bulk.payload_size = 0;
1238 	}
1239 }
1240 
uvc_video_encode_bulk(struct urb * urb,struct uvc_streaming * stream,struct uvc_buffer * buf)1241 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1242 	struct uvc_buffer *buf)
1243 {
1244 	u8 *mem = urb->transfer_buffer;
1245 	int len = stream->urb_size, ret;
1246 
1247 	if (buf == NULL) {
1248 		urb->transfer_buffer_length = 0;
1249 		return;
1250 	}
1251 
1252 	/* If the URB is the first of its payload, add the header. */
1253 	if (stream->bulk.header_size == 0) {
1254 		ret = uvc_video_encode_header(stream, buf, mem, len);
1255 		stream->bulk.header_size = ret;
1256 		stream->bulk.payload_size += ret;
1257 		mem += ret;
1258 		len -= ret;
1259 	}
1260 
1261 	/* Process video data. */
1262 	ret = uvc_video_encode_data(stream, buf, mem, len);
1263 
1264 	stream->bulk.payload_size += ret;
1265 	len -= ret;
1266 
1267 	if (buf->bytesused == stream->queue.buf_used ||
1268 	    stream->bulk.payload_size == stream->bulk.max_payload_size) {
1269 		if (buf->bytesused == stream->queue.buf_used) {
1270 			stream->queue.buf_used = 0;
1271 			buf->state = UVC_BUF_STATE_READY;
1272 			buf->buf.v4l2_buf.sequence = ++stream->sequence;
1273 			uvc_queue_next_buffer(&stream->queue, buf);
1274 			stream->last_fid ^= UVC_STREAM_FID;
1275 		}
1276 
1277 		stream->bulk.header_size = 0;
1278 		stream->bulk.payload_size = 0;
1279 	}
1280 
1281 	urb->transfer_buffer_length = stream->urb_size - len;
1282 }
1283 
uvc_video_complete(struct urb * urb)1284 static void uvc_video_complete(struct urb *urb)
1285 {
1286 	struct uvc_streaming *stream = urb->context;
1287 	struct uvc_video_queue *queue = &stream->queue;
1288 	struct uvc_buffer *buf = NULL;
1289 	unsigned long flags;
1290 	int ret;
1291 
1292 	switch (urb->status) {
1293 	case 0:
1294 		break;
1295 
1296 	default:
1297 		uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1298 			"completion handler.\n", urb->status);
1299 
1300 	case -ENOENT:		/* usb_kill_urb() called. */
1301 		if (stream->frozen)
1302 			return;
1303 
1304 	case -ECONNRESET:	/* usb_unlink_urb() called. */
1305 	case -ESHUTDOWN:	/* The endpoint is being disabled. */
1306 		uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1307 		return;
1308 	}
1309 
1310 	spin_lock_irqsave(&queue->irqlock, flags);
1311 	if (!list_empty(&queue->irqqueue))
1312 		buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
1313 				       queue);
1314 	spin_unlock_irqrestore(&queue->irqlock, flags);
1315 
1316 	stream->decode(urb, stream, buf);
1317 
1318 	if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
1319 		uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1320 			ret);
1321 	}
1322 }
1323 
1324 /*
1325  * Free transfer buffers.
1326  */
uvc_free_urb_buffers(struct uvc_streaming * stream)1327 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1328 {
1329 	unsigned int i;
1330 
1331 	for (i = 0; i < UVC_URBS; ++i) {
1332 		if (stream->urb_buffer[i]) {
1333 #ifndef CONFIG_DMA_NONCOHERENT
1334 			usb_free_coherent(stream->dev->udev, stream->urb_size,
1335 				stream->urb_buffer[i], stream->urb_dma[i]);
1336 #else
1337 			kfree(stream->urb_buffer[i]);
1338 #endif
1339 			stream->urb_buffer[i] = NULL;
1340 		}
1341 	}
1342 
1343 	stream->urb_size = 0;
1344 }
1345 
1346 /*
1347  * Allocate transfer buffers. This function can be called with buffers
1348  * already allocated when resuming from suspend, in which case it will
1349  * return without touching the buffers.
1350  *
1351  * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1352  * system is too low on memory try successively smaller numbers of packets
1353  * until allocation succeeds.
1354  *
1355  * Return the number of allocated packets on success or 0 when out of memory.
1356  */
uvc_alloc_urb_buffers(struct uvc_streaming * stream,unsigned int size,unsigned int psize,gfp_t gfp_flags)1357 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1358 	unsigned int size, unsigned int psize, gfp_t gfp_flags)
1359 {
1360 	unsigned int npackets;
1361 	unsigned int i;
1362 
1363 	/* Buffers are already allocated, bail out. */
1364 	if (stream->urb_size)
1365 		return stream->urb_size / psize;
1366 
1367 	/* Compute the number of packets. Bulk endpoints might transfer UVC
1368 	 * payloads across multiple URBs.
1369 	 */
1370 	npackets = DIV_ROUND_UP(size, psize);
1371 	if (npackets > UVC_MAX_PACKETS)
1372 		npackets = UVC_MAX_PACKETS;
1373 
1374 	/* Retry allocations until one succeed. */
1375 	for (; npackets > 1; npackets /= 2) {
1376 		for (i = 0; i < UVC_URBS; ++i) {
1377 			stream->urb_size = psize * npackets;
1378 #ifndef CONFIG_DMA_NONCOHERENT
1379 			stream->urb_buffer[i] = usb_alloc_coherent(
1380 				stream->dev->udev, stream->urb_size,
1381 				gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1382 #else
1383 			stream->urb_buffer[i] =
1384 			    kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1385 #endif
1386 			if (!stream->urb_buffer[i]) {
1387 				uvc_free_urb_buffers(stream);
1388 				break;
1389 			}
1390 		}
1391 
1392 		if (i == UVC_URBS) {
1393 			uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1394 				"of %ux%u bytes each.\n", UVC_URBS, npackets,
1395 				psize);
1396 			return npackets;
1397 		}
1398 	}
1399 
1400 	uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1401 		"per packet).\n", psize);
1402 	return 0;
1403 }
1404 
1405 /*
1406  * Uninitialize isochronous/bulk URBs and free transfer buffers.
1407  */
uvc_uninit_video(struct uvc_streaming * stream,int free_buffers)1408 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1409 {
1410 	struct urb *urb;
1411 	unsigned int i;
1412 
1413 	uvc_video_stats_stop(stream);
1414 
1415 	for (i = 0; i < UVC_URBS; ++i) {
1416 		urb = stream->urb[i];
1417 		if (urb == NULL)
1418 			continue;
1419 
1420 		usb_kill_urb(urb);
1421 		usb_free_urb(urb);
1422 		stream->urb[i] = NULL;
1423 	}
1424 
1425 	if (free_buffers)
1426 		uvc_free_urb_buffers(stream);
1427 
1428 	uvc_video_clock_cleanup(stream);
1429 }
1430 
1431 /*
1432  * Initialize isochronous URBs and allocate transfer buffers. The packet size
1433  * is given by the endpoint.
1434  */
uvc_init_video_isoc(struct uvc_streaming * stream,struct usb_host_endpoint * ep,gfp_t gfp_flags)1435 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1436 	struct usb_host_endpoint *ep, gfp_t gfp_flags)
1437 {
1438 	struct urb *urb;
1439 	unsigned int npackets, i, j;
1440 	u16 psize;
1441 	u32 size;
1442 
1443 	psize = le16_to_cpu(ep->desc.wMaxPacketSize);
1444 	psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1445 	size = stream->ctrl.dwMaxVideoFrameSize;
1446 
1447 	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1448 	if (npackets == 0)
1449 		return -ENOMEM;
1450 
1451 	size = npackets * psize;
1452 
1453 	for (i = 0; i < UVC_URBS; ++i) {
1454 		urb = usb_alloc_urb(npackets, gfp_flags);
1455 		if (urb == NULL) {
1456 			uvc_uninit_video(stream, 1);
1457 			return -ENOMEM;
1458 		}
1459 
1460 		urb->dev = stream->dev->udev;
1461 		urb->context = stream;
1462 		urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1463 				ep->desc.bEndpointAddress);
1464 #ifndef CONFIG_DMA_NONCOHERENT
1465 		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1466 		urb->transfer_dma = stream->urb_dma[i];
1467 #else
1468 		urb->transfer_flags = URB_ISO_ASAP;
1469 #endif
1470 		urb->interval = ep->desc.bInterval;
1471 		urb->transfer_buffer = stream->urb_buffer[i];
1472 		urb->complete = uvc_video_complete;
1473 		urb->number_of_packets = npackets;
1474 		urb->transfer_buffer_length = size;
1475 
1476 		for (j = 0; j < npackets; ++j) {
1477 			urb->iso_frame_desc[j].offset = j * psize;
1478 			urb->iso_frame_desc[j].length = psize;
1479 		}
1480 
1481 		stream->urb[i] = urb;
1482 	}
1483 
1484 	return 0;
1485 }
1486 
1487 /*
1488  * Initialize bulk URBs and allocate transfer buffers. The packet size is
1489  * given by the endpoint.
1490  */
uvc_init_video_bulk(struct uvc_streaming * stream,struct usb_host_endpoint * ep,gfp_t gfp_flags)1491 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1492 	struct usb_host_endpoint *ep, gfp_t gfp_flags)
1493 {
1494 	struct urb *urb;
1495 	unsigned int npackets, pipe, i;
1496 	u16 psize;
1497 	u32 size;
1498 
1499 	psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
1500 	size = stream->ctrl.dwMaxPayloadTransferSize;
1501 	stream->bulk.max_payload_size = size;
1502 
1503 	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1504 	if (npackets == 0)
1505 		return -ENOMEM;
1506 
1507 	size = npackets * psize;
1508 
1509 	if (usb_endpoint_dir_in(&ep->desc))
1510 		pipe = usb_rcvbulkpipe(stream->dev->udev,
1511 				       ep->desc.bEndpointAddress);
1512 	else
1513 		pipe = usb_sndbulkpipe(stream->dev->udev,
1514 				       ep->desc.bEndpointAddress);
1515 
1516 	if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1517 		size = 0;
1518 
1519 	for (i = 0; i < UVC_URBS; ++i) {
1520 		urb = usb_alloc_urb(0, gfp_flags);
1521 		if (urb == NULL) {
1522 			uvc_uninit_video(stream, 1);
1523 			return -ENOMEM;
1524 		}
1525 
1526 		usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1527 			stream->urb_buffer[i], size, uvc_video_complete,
1528 			stream);
1529 #ifndef CONFIG_DMA_NONCOHERENT
1530 		urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1531 		urb->transfer_dma = stream->urb_dma[i];
1532 #endif
1533 
1534 		stream->urb[i] = urb;
1535 	}
1536 
1537 	return 0;
1538 }
1539 
1540 /*
1541  * Initialize isochronous/bulk URBs and allocate transfer buffers.
1542  */
uvc_init_video(struct uvc_streaming * stream,gfp_t gfp_flags)1543 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1544 {
1545 	struct usb_interface *intf = stream->intf;
1546 	struct usb_host_endpoint *ep;
1547 	unsigned int i;
1548 	int ret;
1549 
1550 	stream->sequence = -1;
1551 	stream->last_fid = -1;
1552 	stream->bulk.header_size = 0;
1553 	stream->bulk.skip_payload = 0;
1554 	stream->bulk.payload_size = 0;
1555 
1556 	uvc_video_stats_start(stream);
1557 
1558 	ret = uvc_video_clock_init(stream);
1559 	if (ret < 0)
1560 		return ret;
1561 
1562 	if (intf->num_altsetting > 1) {
1563 		struct usb_host_endpoint *best_ep = NULL;
1564 		unsigned int best_psize = 3 * 1024;
1565 		unsigned int bandwidth;
1566 		unsigned int uninitialized_var(altsetting);
1567 		int intfnum = stream->intfnum;
1568 
1569 		/* Isochronous endpoint, select the alternate setting. */
1570 		bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1571 
1572 		if (bandwidth == 0) {
1573 			uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1574 				"bandwidth, defaulting to lowest.\n");
1575 			bandwidth = 1;
1576 		} else {
1577 			uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1578 				"B/frame bandwidth.\n", bandwidth);
1579 		}
1580 
1581 		for (i = 0; i < intf->num_altsetting; ++i) {
1582 			struct usb_host_interface *alts;
1583 			unsigned int psize;
1584 
1585 			alts = &intf->altsetting[i];
1586 			ep = uvc_find_endpoint(alts,
1587 				stream->header.bEndpointAddress);
1588 			if (ep == NULL)
1589 				continue;
1590 
1591 			/* Check if the bandwidth is high enough. */
1592 			psize = le16_to_cpu(ep->desc.wMaxPacketSize);
1593 			psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1594 			if (psize >= bandwidth && psize <= best_psize) {
1595 				altsetting = i;
1596 				best_psize = psize;
1597 				best_ep = ep;
1598 			}
1599 		}
1600 
1601 		if (best_ep == NULL) {
1602 			uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1603 				"for requested bandwidth.\n");
1604 			return -EIO;
1605 		}
1606 
1607 		uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1608 			"(%u B/frame bandwidth).\n", altsetting, best_psize);
1609 
1610 		ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1611 		if (ret < 0)
1612 			return ret;
1613 
1614 		ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1615 	} else {
1616 		/* Bulk endpoint, proceed to URB initialization. */
1617 		ep = uvc_find_endpoint(&intf->altsetting[0],
1618 				stream->header.bEndpointAddress);
1619 		if (ep == NULL)
1620 			return -EIO;
1621 
1622 		ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1623 	}
1624 
1625 	if (ret < 0)
1626 		return ret;
1627 
1628 	/* Submit the URBs. */
1629 	for (i = 0; i < UVC_URBS; ++i) {
1630 		ret = usb_submit_urb(stream->urb[i], gfp_flags);
1631 		if (ret < 0) {
1632 			uvc_printk(KERN_ERR, "Failed to submit URB %u "
1633 					"(%d).\n", i, ret);
1634 			uvc_uninit_video(stream, 1);
1635 			return ret;
1636 		}
1637 	}
1638 
1639 	return 0;
1640 }
1641 
1642 /* --------------------------------------------------------------------------
1643  * Suspend/resume
1644  */
1645 
1646 /*
1647  * Stop streaming without disabling the video queue.
1648  *
1649  * To let userspace applications resume without trouble, we must not touch the
1650  * video buffers in any way. We mark the device as frozen to make sure the URB
1651  * completion handler won't try to cancel the queue when we kill the URBs.
1652  */
uvc_video_suspend(struct uvc_streaming * stream)1653 int uvc_video_suspend(struct uvc_streaming *stream)
1654 {
1655 	if (!uvc_queue_streaming(&stream->queue))
1656 		return 0;
1657 
1658 	stream->frozen = 1;
1659 	uvc_uninit_video(stream, 0);
1660 	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1661 	return 0;
1662 }
1663 
1664 /*
1665  * Reconfigure the video interface and restart streaming if it was enabled
1666  * before suspend.
1667  *
1668  * If an error occurs, disable the video queue. This will wake all pending
1669  * buffers, making sure userspace applications are notified of the problem
1670  * instead of waiting forever.
1671  */
uvc_video_resume(struct uvc_streaming * stream,int reset)1672 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1673 {
1674 	int ret;
1675 
1676 	/* If the bus has been reset on resume, set the alternate setting to 0.
1677 	 * This should be the default value, but some devices crash or otherwise
1678 	 * misbehave if they don't receive a SET_INTERFACE request before any
1679 	 * other video control request.
1680 	 */
1681 	if (reset)
1682 		usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1683 
1684 	stream->frozen = 0;
1685 
1686 	ret = uvc_commit_video(stream, &stream->ctrl);
1687 	if (ret < 0) {
1688 		uvc_queue_enable(&stream->queue, 0);
1689 		return ret;
1690 	}
1691 
1692 	if (!uvc_queue_streaming(&stream->queue))
1693 		return 0;
1694 
1695 	ret = uvc_init_video(stream, GFP_NOIO);
1696 	if (ret < 0)
1697 		uvc_queue_enable(&stream->queue, 0);
1698 
1699 	return ret;
1700 }
1701 
1702 /* ------------------------------------------------------------------------
1703  * Video device
1704  */
1705 
1706 /*
1707  * Initialize the UVC video device by switching to alternate setting 0 and
1708  * retrieve the default format.
1709  *
1710  * Some cameras (namely the Fuji Finepix) set the format and frame
1711  * indexes to zero. The UVC standard doesn't clearly make this a spec
1712  * violation, so try to silently fix the values if possible.
1713  *
1714  * This function is called before registering the device with V4L.
1715  */
uvc_video_init(struct uvc_streaming * stream)1716 int uvc_video_init(struct uvc_streaming *stream)
1717 {
1718 	struct uvc_streaming_control *probe = &stream->ctrl;
1719 	struct uvc_format *format = NULL;
1720 	struct uvc_frame *frame = NULL;
1721 	unsigned int i;
1722 	int ret;
1723 
1724 	if (stream->nformats == 0) {
1725 		uvc_printk(KERN_INFO, "No supported video formats found.\n");
1726 		return -EINVAL;
1727 	}
1728 
1729 	atomic_set(&stream->active, 0);
1730 
1731 	/* Initialize the video buffers queue. */
1732 	uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1733 
1734 	/* Alternate setting 0 should be the default, yet the XBox Live Vision
1735 	 * Cam (and possibly other devices) crash or otherwise misbehave if
1736 	 * they don't receive a SET_INTERFACE request before any other video
1737 	 * control request.
1738 	 */
1739 	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1740 
1741 	/* Set the streaming probe control with default streaming parameters
1742 	 * retrieved from the device. Webcams that don't suport GET_DEF
1743 	 * requests on the probe control will just keep their current streaming
1744 	 * parameters.
1745 	 */
1746 	if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1747 		uvc_set_video_ctrl(stream, probe, 1);
1748 
1749 	/* Initialize the streaming parameters with the probe control current
1750 	 * value. This makes sure SET_CUR requests on the streaming commit
1751 	 * control will always use values retrieved from a successful GET_CUR
1752 	 * request on the probe control, as required by the UVC specification.
1753 	 */
1754 	ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1755 	if (ret < 0)
1756 		return ret;
1757 
1758 	/* Check if the default format descriptor exists. Use the first
1759 	 * available format otherwise.
1760 	 */
1761 	for (i = stream->nformats; i > 0; --i) {
1762 		format = &stream->format[i-1];
1763 		if (format->index == probe->bFormatIndex)
1764 			break;
1765 	}
1766 
1767 	if (format->nframes == 0) {
1768 		uvc_printk(KERN_INFO, "No frame descriptor found for the "
1769 			"default format.\n");
1770 		return -EINVAL;
1771 	}
1772 
1773 	/* Zero bFrameIndex might be correct. Stream-based formats (including
1774 	 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1775 	 * descriptor with bFrameIndex set to zero. If the default frame
1776 	 * descriptor is not found, use the first available frame.
1777 	 */
1778 	for (i = format->nframes; i > 0; --i) {
1779 		frame = &format->frame[i-1];
1780 		if (frame->bFrameIndex == probe->bFrameIndex)
1781 			break;
1782 	}
1783 
1784 	probe->bFormatIndex = format->index;
1785 	probe->bFrameIndex = frame->bFrameIndex;
1786 
1787 	stream->cur_format = format;
1788 	stream->cur_frame = frame;
1789 
1790 	/* Select the video decoding function */
1791 	if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1792 		if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1793 			stream->decode = uvc_video_decode_isight;
1794 		else if (stream->intf->num_altsetting > 1)
1795 			stream->decode = uvc_video_decode_isoc;
1796 		else
1797 			stream->decode = uvc_video_decode_bulk;
1798 	} else {
1799 		if (stream->intf->num_altsetting == 1)
1800 			stream->decode = uvc_video_encode_bulk;
1801 		else {
1802 			uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1803 				"supported for video output devices.\n");
1804 			return -EINVAL;
1805 		}
1806 	}
1807 
1808 	return 0;
1809 }
1810 
1811 /*
1812  * Enable or disable the video stream.
1813  */
uvc_video_enable(struct uvc_streaming * stream,int enable)1814 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1815 {
1816 	int ret;
1817 
1818 	if (!enable) {
1819 		uvc_uninit_video(stream, 1);
1820 		usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1821 		uvc_queue_enable(&stream->queue, 0);
1822 		return 0;
1823 	}
1824 
1825 	ret = uvc_queue_enable(&stream->queue, 1);
1826 	if (ret < 0)
1827 		return ret;
1828 
1829 	/* Commit the streaming parameters. */
1830 	ret = uvc_commit_video(stream, &stream->ctrl);
1831 	if (ret < 0) {
1832 		uvc_queue_enable(&stream->queue, 0);
1833 		return ret;
1834 	}
1835 
1836 	ret = uvc_init_video(stream, GFP_KERNEL);
1837 	if (ret < 0) {
1838 		usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1839 		uvc_queue_enable(&stream->queue, 0);
1840 	}
1841 
1842 	return ret;
1843 }
1844