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