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