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