xref: /openbmc/linux/drivers/media/usb/uvc/uvc_video.c (revision e42dd3ee)
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 	/*
680 	 * We will get called from __vb2_queue_cancel() if there are buffers
681 	 * done but not dequeued by the user, but the sample array has already
682 	 * been released at that time. Just bail out in that case.
683 	 */
684 	if (!clock->samples)
685 		return;
686 
687 	spin_lock_irqsave(&clock->lock, flags);
688 
689 	if (clock->count < clock->size)
690 		goto done;
691 
692 	first = &clock->samples[clock->head];
693 	last = &clock->samples[(clock->head - 1) % clock->size];
694 
695 	/* First step, PTS to SOF conversion. */
696 	delta_stc = buf->pts - (1UL << 31);
697 	x1 = first->dev_stc - delta_stc;
698 	x2 = last->dev_stc - delta_stc;
699 	if (x1 == x2)
700 		goto done;
701 
702 	y1 = (first->dev_sof + 2048) << 16;
703 	y2 = (last->dev_sof + 2048) << 16;
704 	if (y2 < y1)
705 		y2 += 2048 << 16;
706 
707 	y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
708 	  - (u64)y2 * (u64)x1;
709 	y = div_u64(y, x2 - x1);
710 
711 	sof = y;
712 
713 	uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
714 		  "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
715 		  stream->dev->name, buf->pts,
716 		  y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
717 		  sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
718 		  x1, x2, y1, y2, clock->sof_offset);
719 
720 	/* Second step, SOF to host clock conversion. */
721 	x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
722 	x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
723 	if (x2 < x1)
724 		x2 += 2048 << 16;
725 	if (x1 == x2)
726 		goto done;
727 
728 	y1 = NSEC_PER_SEC;
729 	y2 = (u32)ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
730 
731 	/* Interpolated and host SOF timestamps can wrap around at slightly
732 	 * different times. Handle this by adding or removing 2048 to or from
733 	 * the computed SOF value to keep it close to the SOF samples mean
734 	 * value.
735 	 */
736 	mean = (x1 + x2) / 2;
737 	if (mean - (1024 << 16) > sof)
738 		sof += 2048 << 16;
739 	else if (sof > mean + (1024 << 16))
740 		sof -= 2048 << 16;
741 
742 	y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
743 	  - (u64)y2 * (u64)x1;
744 	y = div_u64(y, x2 - x1);
745 
746 	timestamp = ktime_to_ns(first->host_time) + y - y1;
747 
748 	uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %llu "
749 		  "buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
750 		  stream->dev->name,
751 		  sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
752 		  y, timestamp, vbuf->vb2_buf.timestamp,
753 		  x1, first->host_sof, first->dev_sof,
754 		  x2, last->host_sof, last->dev_sof, y1, y2);
755 
756 	/* Update the V4L2 buffer. */
757 	vbuf->vb2_buf.timestamp = timestamp;
758 
759 done:
760 	spin_unlock_irqrestore(&clock->lock, flags);
761 }
762 
763 /* ------------------------------------------------------------------------
764  * Stream statistics
765  */
766 
767 static void uvc_video_stats_decode(struct uvc_streaming *stream,
768 		const u8 *data, int len)
769 {
770 	unsigned int header_size;
771 	bool has_pts = false;
772 	bool has_scr = false;
773 	u16 uninitialized_var(scr_sof);
774 	u32 uninitialized_var(scr_stc);
775 	u32 uninitialized_var(pts);
776 
777 	if (stream->stats.stream.nb_frames == 0 &&
778 	    stream->stats.frame.nb_packets == 0)
779 		stream->stats.stream.start_ts = ktime_get();
780 
781 	switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
782 	case UVC_STREAM_PTS | UVC_STREAM_SCR:
783 		header_size = 12;
784 		has_pts = true;
785 		has_scr = true;
786 		break;
787 	case UVC_STREAM_PTS:
788 		header_size = 6;
789 		has_pts = true;
790 		break;
791 	case UVC_STREAM_SCR:
792 		header_size = 8;
793 		has_scr = true;
794 		break;
795 	default:
796 		header_size = 2;
797 		break;
798 	}
799 
800 	/* Check for invalid headers. */
801 	if (len < header_size || data[0] < header_size) {
802 		stream->stats.frame.nb_invalid++;
803 		return;
804 	}
805 
806 	/* Extract the timestamps. */
807 	if (has_pts)
808 		pts = get_unaligned_le32(&data[2]);
809 
810 	if (has_scr) {
811 		scr_stc = get_unaligned_le32(&data[header_size - 6]);
812 		scr_sof = get_unaligned_le16(&data[header_size - 2]);
813 	}
814 
815 	/* Is PTS constant through the whole frame ? */
816 	if (has_pts && stream->stats.frame.nb_pts) {
817 		if (stream->stats.frame.pts != pts) {
818 			stream->stats.frame.nb_pts_diffs++;
819 			stream->stats.frame.last_pts_diff =
820 				stream->stats.frame.nb_packets;
821 		}
822 	}
823 
824 	if (has_pts) {
825 		stream->stats.frame.nb_pts++;
826 		stream->stats.frame.pts = pts;
827 	}
828 
829 	/* Do all frames have a PTS in their first non-empty packet, or before
830 	 * their first empty packet ?
831 	 */
832 	if (stream->stats.frame.size == 0) {
833 		if (len > header_size)
834 			stream->stats.frame.has_initial_pts = has_pts;
835 		if (len == header_size && has_pts)
836 			stream->stats.frame.has_early_pts = true;
837 	}
838 
839 	/* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
840 	if (has_scr && stream->stats.frame.nb_scr) {
841 		if (stream->stats.frame.scr_stc != scr_stc)
842 			stream->stats.frame.nb_scr_diffs++;
843 	}
844 
845 	if (has_scr) {
846 		/* Expand the SOF counter to 32 bits and store its value. */
847 		if (stream->stats.stream.nb_frames > 0 ||
848 		    stream->stats.frame.nb_scr > 0)
849 			stream->stats.stream.scr_sof_count +=
850 				(scr_sof - stream->stats.stream.scr_sof) % 2048;
851 		stream->stats.stream.scr_sof = scr_sof;
852 
853 		stream->stats.frame.nb_scr++;
854 		stream->stats.frame.scr_stc = scr_stc;
855 		stream->stats.frame.scr_sof = scr_sof;
856 
857 		if (scr_sof < stream->stats.stream.min_sof)
858 			stream->stats.stream.min_sof = scr_sof;
859 		if (scr_sof > stream->stats.stream.max_sof)
860 			stream->stats.stream.max_sof = scr_sof;
861 	}
862 
863 	/* Record the first non-empty packet number. */
864 	if (stream->stats.frame.size == 0 && len > header_size)
865 		stream->stats.frame.first_data = stream->stats.frame.nb_packets;
866 
867 	/* Update the frame size. */
868 	stream->stats.frame.size += len - header_size;
869 
870 	/* Update the packets counters. */
871 	stream->stats.frame.nb_packets++;
872 	if (len <= header_size)
873 		stream->stats.frame.nb_empty++;
874 
875 	if (data[1] & UVC_STREAM_ERR)
876 		stream->stats.frame.nb_errors++;
877 }
878 
879 static void uvc_video_stats_update(struct uvc_streaming *stream)
880 {
881 	struct uvc_stats_frame *frame = &stream->stats.frame;
882 
883 	uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
884 		  "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
885 		  "last pts/stc/sof %u/%u/%u\n",
886 		  stream->sequence, frame->first_data,
887 		  frame->nb_packets - frame->nb_empty, frame->nb_packets,
888 		  frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
889 		  frame->has_early_pts ? "" : "!",
890 		  frame->has_initial_pts ? "" : "!",
891 		  frame->nb_scr_diffs, frame->nb_scr,
892 		  frame->pts, frame->scr_stc, frame->scr_sof);
893 
894 	stream->stats.stream.nb_frames++;
895 	stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
896 	stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
897 	stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
898 	stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
899 
900 	if (frame->has_early_pts)
901 		stream->stats.stream.nb_pts_early++;
902 	if (frame->has_initial_pts)
903 		stream->stats.stream.nb_pts_initial++;
904 	if (frame->last_pts_diff <= frame->first_data)
905 		stream->stats.stream.nb_pts_constant++;
906 	if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
907 		stream->stats.stream.nb_scr_count_ok++;
908 	if (frame->nb_scr_diffs + 1 == frame->nb_scr)
909 		stream->stats.stream.nb_scr_diffs_ok++;
910 
911 	memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
912 }
913 
914 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
915 			    size_t size)
916 {
917 	unsigned int scr_sof_freq;
918 	unsigned int duration;
919 	size_t count = 0;
920 
921 	/* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
922 	 * frequency this will not overflow before more than 1h.
923 	 */
924 	duration = ktime_ms_delta(stream->stats.stream.stop_ts,
925 				  stream->stats.stream.start_ts);
926 	if (duration != 0)
927 		scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
928 			     / duration;
929 	else
930 		scr_sof_freq = 0;
931 
932 	count += scnprintf(buf + count, size - count,
933 			   "frames:  %u\npackets: %u\nempty:   %u\n"
934 			   "errors:  %u\ninvalid: %u\n",
935 			   stream->stats.stream.nb_frames,
936 			   stream->stats.stream.nb_packets,
937 			   stream->stats.stream.nb_empty,
938 			   stream->stats.stream.nb_errors,
939 			   stream->stats.stream.nb_invalid);
940 	count += scnprintf(buf + count, size - count,
941 			   "pts: %u early, %u initial, %u ok\n",
942 			   stream->stats.stream.nb_pts_early,
943 			   stream->stats.stream.nb_pts_initial,
944 			   stream->stats.stream.nb_pts_constant);
945 	count += scnprintf(buf + count, size - count,
946 			   "scr: %u count ok, %u diff ok\n",
947 			   stream->stats.stream.nb_scr_count_ok,
948 			   stream->stats.stream.nb_scr_diffs_ok);
949 	count += scnprintf(buf + count, size - count,
950 			   "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
951 			   stream->stats.stream.min_sof,
952 			   stream->stats.stream.max_sof,
953 			   scr_sof_freq / 1000, scr_sof_freq % 1000);
954 
955 	return count;
956 }
957 
958 static void uvc_video_stats_start(struct uvc_streaming *stream)
959 {
960 	memset(&stream->stats, 0, sizeof(stream->stats));
961 	stream->stats.stream.min_sof = 2048;
962 }
963 
964 static void uvc_video_stats_stop(struct uvc_streaming *stream)
965 {
966 	stream->stats.stream.stop_ts = ktime_get();
967 }
968 
969 /* ------------------------------------------------------------------------
970  * Video codecs
971  */
972 
973 /* Video payload decoding is handled by uvc_video_decode_start(),
974  * uvc_video_decode_data() and uvc_video_decode_end().
975  *
976  * uvc_video_decode_start is called with URB data at the start of a bulk or
977  * isochronous payload. It processes header data and returns the header size
978  * in bytes if successful. If an error occurs, it returns a negative error
979  * code. The following error codes have special meanings.
980  *
981  * - EAGAIN informs the caller that the current video buffer should be marked
982  *   as done, and that the function should be called again with the same data
983  *   and a new video buffer. This is used when end of frame conditions can be
984  *   reliably detected at the beginning of the next frame only.
985  *
986  * If an error other than -EAGAIN is returned, the caller will drop the current
987  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
988  * made until the next payload. -ENODATA can be used to drop the current
989  * payload if no other error code is appropriate.
990  *
991  * uvc_video_decode_data is called for every URB with URB data. It copies the
992  * data to the video buffer.
993  *
994  * uvc_video_decode_end is called with header data at the end of a bulk or
995  * isochronous payload. It performs any additional header data processing and
996  * returns 0 or a negative error code if an error occurred. As header data have
997  * already been processed by uvc_video_decode_start, this functions isn't
998  * required to perform sanity checks a second time.
999  *
1000  * For isochronous transfers where a payload is always transferred in a single
1001  * URB, the three functions will be called in a row.
1002  *
1003  * To let the decoder process header data and update its internal state even
1004  * when no video buffer is available, uvc_video_decode_start must be prepared
1005  * to be called with a NULL buf parameter. uvc_video_decode_data and
1006  * uvc_video_decode_end will never be called with a NULL buffer.
1007  */
1008 static int uvc_video_decode_start(struct uvc_streaming *stream,
1009 		struct uvc_buffer *buf, const u8 *data, int len)
1010 {
1011 	u8 fid;
1012 
1013 	/* Sanity checks:
1014 	 * - packet must be at least 2 bytes long
1015 	 * - bHeaderLength value must be at least 2 bytes (see above)
1016 	 * - bHeaderLength value can't be larger than the packet size.
1017 	 */
1018 	if (len < 2 || data[0] < 2 || data[0] > len) {
1019 		stream->stats.frame.nb_invalid++;
1020 		return -EINVAL;
1021 	}
1022 
1023 	fid = data[1] & UVC_STREAM_FID;
1024 
1025 	/* Increase the sequence number regardless of any buffer states, so
1026 	 * that discontinuous sequence numbers always indicate lost frames.
1027 	 */
1028 	if (stream->last_fid != fid) {
1029 		stream->sequence++;
1030 		if (stream->sequence)
1031 			uvc_video_stats_update(stream);
1032 	}
1033 
1034 	uvc_video_clock_decode(stream, buf, data, len);
1035 	uvc_video_stats_decode(stream, data, len);
1036 
1037 	/* Store the payload FID bit and return immediately when the buffer is
1038 	 * NULL.
1039 	 */
1040 	if (buf == NULL) {
1041 		stream->last_fid = fid;
1042 		return -ENODATA;
1043 	}
1044 
1045 	/* Mark the buffer as bad if the error bit is set. */
1046 	if (data[1] & UVC_STREAM_ERR) {
1047 		uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1048 			  "set).\n");
1049 		buf->error = 1;
1050 	}
1051 
1052 	/* Synchronize to the input stream by waiting for the FID bit to be
1053 	 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1054 	 * stream->last_fid is initialized to -1, so the first isochronous
1055 	 * frame will always be in sync.
1056 	 *
1057 	 * If the device doesn't toggle the FID bit, invert stream->last_fid
1058 	 * when the EOF bit is set to force synchronisation on the next packet.
1059 	 */
1060 	if (buf->state != UVC_BUF_STATE_ACTIVE) {
1061 		if (fid == stream->last_fid) {
1062 			uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1063 				"sync).\n");
1064 			if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1065 			    (data[1] & UVC_STREAM_EOF))
1066 				stream->last_fid ^= UVC_STREAM_FID;
1067 			return -ENODATA;
1068 		}
1069 
1070 		buf->buf.field = V4L2_FIELD_NONE;
1071 		buf->buf.sequence = stream->sequence;
1072 		buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time());
1073 
1074 		/* TODO: Handle PTS and SCR. */
1075 		buf->state = UVC_BUF_STATE_ACTIVE;
1076 	}
1077 
1078 	/* Mark the buffer as done if we're at the beginning of a new frame.
1079 	 * End of frame detection is better implemented by checking the EOF
1080 	 * bit (FID bit toggling is delayed by one frame compared to the EOF
1081 	 * bit), but some devices don't set the bit at end of frame (and the
1082 	 * last payload can be lost anyway). We thus must check if the FID has
1083 	 * been toggled.
1084 	 *
1085 	 * stream->last_fid is initialized to -1, so the first isochronous
1086 	 * frame will never trigger an end of frame detection.
1087 	 *
1088 	 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1089 	 * as it doesn't make sense to return an empty buffer. This also
1090 	 * avoids detecting end of frame conditions at FID toggling if the
1091 	 * previous payload had the EOF bit set.
1092 	 */
1093 	if (fid != stream->last_fid && buf->bytesused != 0) {
1094 		uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1095 				"toggled).\n");
1096 		buf->state = UVC_BUF_STATE_READY;
1097 		return -EAGAIN;
1098 	}
1099 
1100 	stream->last_fid = fid;
1101 
1102 	return data[0];
1103 }
1104 
1105 /*
1106  * uvc_video_decode_data_work: Asynchronous memcpy processing
1107  *
1108  * Copy URB data to video buffers in process context, releasing buffer
1109  * references and requeuing the URB when done.
1110  */
1111 static void uvc_video_copy_data_work(struct work_struct *work)
1112 {
1113 	struct uvc_urb *uvc_urb = container_of(work, struct uvc_urb, work);
1114 	unsigned int i;
1115 	int ret;
1116 
1117 	for (i = 0; i < uvc_urb->async_operations; i++) {
1118 		struct uvc_copy_op *op = &uvc_urb->copy_operations[i];
1119 
1120 		memcpy(op->dst, op->src, op->len);
1121 
1122 		/* Release reference taken on this buffer. */
1123 		uvc_queue_buffer_release(op->buf);
1124 	}
1125 
1126 	ret = usb_submit_urb(uvc_urb->urb, GFP_KERNEL);
1127 	if (ret < 0)
1128 		uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1129 			   ret);
1130 }
1131 
1132 static void uvc_video_decode_data(struct uvc_urb *uvc_urb,
1133 		struct uvc_buffer *buf, const u8 *data, int len)
1134 {
1135 	unsigned int active_op = uvc_urb->async_operations;
1136 	struct uvc_copy_op *op = &uvc_urb->copy_operations[active_op];
1137 	unsigned int maxlen;
1138 
1139 	if (len <= 0)
1140 		return;
1141 
1142 	maxlen = buf->length - buf->bytesused;
1143 
1144 	/* Take a buffer reference for async work. */
1145 	kref_get(&buf->ref);
1146 
1147 	op->buf = buf;
1148 	op->src = data;
1149 	op->dst = buf->mem + buf->bytesused;
1150 	op->len = min_t(unsigned int, len, maxlen);
1151 
1152 	buf->bytesused += op->len;
1153 
1154 	/* Complete the current frame if the buffer size was exceeded. */
1155 	if (len > maxlen) {
1156 		uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1157 		buf->error = 1;
1158 		buf->state = UVC_BUF_STATE_READY;
1159 	}
1160 
1161 	uvc_urb->async_operations++;
1162 }
1163 
1164 static void uvc_video_decode_end(struct uvc_streaming *stream,
1165 		struct uvc_buffer *buf, const u8 *data, int len)
1166 {
1167 	/* Mark the buffer as done if the EOF marker is set. */
1168 	if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1169 		uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1170 		if (data[0] == len)
1171 			uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1172 		buf->state = UVC_BUF_STATE_READY;
1173 		if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1174 			stream->last_fid ^= UVC_STREAM_FID;
1175 	}
1176 }
1177 
1178 /* Video payload encoding is handled by uvc_video_encode_header() and
1179  * uvc_video_encode_data(). Only bulk transfers are currently supported.
1180  *
1181  * uvc_video_encode_header is called at the start of a payload. It adds header
1182  * data to the transfer buffer and returns the header size. As the only known
1183  * UVC output device transfers a whole frame in a single payload, the EOF bit
1184  * is always set in the header.
1185  *
1186  * uvc_video_encode_data is called for every URB and copies the data from the
1187  * video buffer to the transfer buffer.
1188  */
1189 static int uvc_video_encode_header(struct uvc_streaming *stream,
1190 		struct uvc_buffer *buf, u8 *data, int len)
1191 {
1192 	data[0] = 2;	/* Header length */
1193 	data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1194 		| (stream->last_fid & UVC_STREAM_FID);
1195 	return 2;
1196 }
1197 
1198 static int uvc_video_encode_data(struct uvc_streaming *stream,
1199 		struct uvc_buffer *buf, u8 *data, int len)
1200 {
1201 	struct uvc_video_queue *queue = &stream->queue;
1202 	unsigned int nbytes;
1203 	void *mem;
1204 
1205 	/* Copy video data to the URB buffer. */
1206 	mem = buf->mem + queue->buf_used;
1207 	nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1208 	nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1209 			nbytes);
1210 	memcpy(data, mem, nbytes);
1211 
1212 	queue->buf_used += nbytes;
1213 
1214 	return nbytes;
1215 }
1216 
1217 /* ------------------------------------------------------------------------
1218  * Metadata
1219  */
1220 
1221 /*
1222  * Additionally to the payload headers we also want to provide the user with USB
1223  * Frame Numbers and system time values. The resulting buffer is thus composed
1224  * of blocks, containing a 64-bit timestamp in  nanoseconds, a 16-bit USB Frame
1225  * Number, and a copy of the payload header.
1226  *
1227  * Ideally we want to capture all payload headers for each frame. However, their
1228  * number is unknown and unbound. We thus drop headers that contain no vendor
1229  * data and that either contain no SCR value or an SCR value identical to the
1230  * previous header.
1231  */
1232 static void uvc_video_decode_meta(struct uvc_streaming *stream,
1233 				  struct uvc_buffer *meta_buf,
1234 				  const u8 *mem, unsigned int length)
1235 {
1236 	struct uvc_meta_buf *meta;
1237 	size_t len_std = 2;
1238 	bool has_pts, has_scr;
1239 	unsigned long flags;
1240 	unsigned int sof;
1241 	ktime_t time;
1242 	const u8 *scr;
1243 
1244 	if (!meta_buf || length == 2)
1245 		return;
1246 
1247 	if (meta_buf->length - meta_buf->bytesused <
1248 	    length + sizeof(meta->ns) + sizeof(meta->sof)) {
1249 		meta_buf->error = 1;
1250 		return;
1251 	}
1252 
1253 	has_pts = mem[1] & UVC_STREAM_PTS;
1254 	has_scr = mem[1] & UVC_STREAM_SCR;
1255 
1256 	if (has_pts) {
1257 		len_std += 4;
1258 		scr = mem + 6;
1259 	} else {
1260 		scr = mem + 2;
1261 	}
1262 
1263 	if (has_scr)
1264 		len_std += 6;
1265 
1266 	if (stream->meta.format == V4L2_META_FMT_UVC)
1267 		length = len_std;
1268 
1269 	if (length == len_std && (!has_scr ||
1270 				  !memcmp(scr, stream->clock.last_scr, 6)))
1271 		return;
1272 
1273 	meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
1274 	local_irq_save(flags);
1275 	time = uvc_video_get_time();
1276 	sof = usb_get_current_frame_number(stream->dev->udev);
1277 	local_irq_restore(flags);
1278 	put_unaligned(ktime_to_ns(time), &meta->ns);
1279 	put_unaligned(sof, &meta->sof);
1280 
1281 	if (has_scr)
1282 		memcpy(stream->clock.last_scr, scr, 6);
1283 
1284 	memcpy(&meta->length, mem, length);
1285 	meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);
1286 
1287 	uvc_trace(UVC_TRACE_FRAME,
1288 		  "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
1289 		  __func__, ktime_to_ns(time), meta->sof, meta->length,
1290 		  meta->flags,
1291 		  has_pts ? *(u32 *)meta->buf : 0,
1292 		  has_scr ? *(u32 *)scr : 0,
1293 		  has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
1294 }
1295 
1296 /* ------------------------------------------------------------------------
1297  * URB handling
1298  */
1299 
1300 /*
1301  * Set error flag for incomplete buffer.
1302  */
1303 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1304 				      struct uvc_buffer *buf)
1305 {
1306 	if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1307 	    !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1308 		buf->error = 1;
1309 }
1310 
1311 /*
1312  * Completion handler for video URBs.
1313  */
1314 
1315 static void uvc_video_next_buffers(struct uvc_streaming *stream,
1316 		struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
1317 {
1318 	uvc_video_validate_buffer(stream, *video_buf);
1319 
1320 	if (*meta_buf) {
1321 		struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
1322 		const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;
1323 
1324 		vb2_meta->sequence = vb2_video->sequence;
1325 		vb2_meta->field = vb2_video->field;
1326 		vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;
1327 
1328 		(*meta_buf)->state = UVC_BUF_STATE_READY;
1329 		if (!(*meta_buf)->error)
1330 			(*meta_buf)->error = (*video_buf)->error;
1331 		*meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
1332 						  *meta_buf);
1333 	}
1334 	*video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
1335 }
1336 
1337 static void uvc_video_decode_isoc(struct uvc_urb *uvc_urb,
1338 			struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1339 {
1340 	struct urb *urb = uvc_urb->urb;
1341 	struct uvc_streaming *stream = uvc_urb->stream;
1342 	u8 *mem;
1343 	int ret, i;
1344 
1345 	for (i = 0; i < urb->number_of_packets; ++i) {
1346 		if (urb->iso_frame_desc[i].status < 0) {
1347 			uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1348 				"lost (%d).\n", urb->iso_frame_desc[i].status);
1349 			/* Mark the buffer as faulty. */
1350 			if (buf != NULL)
1351 				buf->error = 1;
1352 			continue;
1353 		}
1354 
1355 		/* Decode the payload header. */
1356 		mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1357 		do {
1358 			ret = uvc_video_decode_start(stream, buf, mem,
1359 				urb->iso_frame_desc[i].actual_length);
1360 			if (ret == -EAGAIN)
1361 				uvc_video_next_buffers(stream, &buf, &meta_buf);
1362 		} while (ret == -EAGAIN);
1363 
1364 		if (ret < 0)
1365 			continue;
1366 
1367 		uvc_video_decode_meta(stream, meta_buf, mem, ret);
1368 
1369 		/* Decode the payload data. */
1370 		uvc_video_decode_data(uvc_urb, buf, mem + ret,
1371 			urb->iso_frame_desc[i].actual_length - ret);
1372 
1373 		/* Process the header again. */
1374 		uvc_video_decode_end(stream, buf, mem,
1375 			urb->iso_frame_desc[i].actual_length);
1376 
1377 		if (buf->state == UVC_BUF_STATE_READY)
1378 			uvc_video_next_buffers(stream, &buf, &meta_buf);
1379 	}
1380 }
1381 
1382 static void uvc_video_decode_bulk(struct uvc_urb *uvc_urb,
1383 			struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1384 {
1385 	struct urb *urb = uvc_urb->urb;
1386 	struct uvc_streaming *stream = uvc_urb->stream;
1387 	u8 *mem;
1388 	int len, ret;
1389 
1390 	/*
1391 	 * Ignore ZLPs if they're not part of a frame, otherwise process them
1392 	 * to trigger the end of payload detection.
1393 	 */
1394 	if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1395 		return;
1396 
1397 	mem = urb->transfer_buffer;
1398 	len = urb->actual_length;
1399 	stream->bulk.payload_size += len;
1400 
1401 	/* If the URB is the first of its payload, decode and save the
1402 	 * header.
1403 	 */
1404 	if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1405 		do {
1406 			ret = uvc_video_decode_start(stream, buf, mem, len);
1407 			if (ret == -EAGAIN)
1408 				uvc_video_next_buffers(stream, &buf, &meta_buf);
1409 		} while (ret == -EAGAIN);
1410 
1411 		/* If an error occurred skip the rest of the payload. */
1412 		if (ret < 0 || buf == NULL) {
1413 			stream->bulk.skip_payload = 1;
1414 		} else {
1415 			memcpy(stream->bulk.header, mem, ret);
1416 			stream->bulk.header_size = ret;
1417 
1418 			uvc_video_decode_meta(stream, meta_buf, mem, ret);
1419 
1420 			mem += ret;
1421 			len -= ret;
1422 		}
1423 	}
1424 
1425 	/* The buffer queue might have been cancelled while a bulk transfer
1426 	 * was in progress, so we can reach here with buf equal to NULL. Make
1427 	 * sure buf is never dereferenced if NULL.
1428 	 */
1429 
1430 	/* Prepare video data for processing. */
1431 	if (!stream->bulk.skip_payload && buf != NULL)
1432 		uvc_video_decode_data(uvc_urb, buf, mem, len);
1433 
1434 	/* Detect the payload end by a URB smaller than the maximum size (or
1435 	 * a payload size equal to the maximum) and process the header again.
1436 	 */
1437 	if (urb->actual_length < urb->transfer_buffer_length ||
1438 	    stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1439 		if (!stream->bulk.skip_payload && buf != NULL) {
1440 			uvc_video_decode_end(stream, buf, stream->bulk.header,
1441 				stream->bulk.payload_size);
1442 			if (buf->state == UVC_BUF_STATE_READY)
1443 				uvc_video_next_buffers(stream, &buf, &meta_buf);
1444 		}
1445 
1446 		stream->bulk.header_size = 0;
1447 		stream->bulk.skip_payload = 0;
1448 		stream->bulk.payload_size = 0;
1449 	}
1450 }
1451 
1452 static void uvc_video_encode_bulk(struct uvc_urb *uvc_urb,
1453 	struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1454 {
1455 	struct urb *urb = uvc_urb->urb;
1456 	struct uvc_streaming *stream = uvc_urb->stream;
1457 
1458 	u8 *mem = urb->transfer_buffer;
1459 	int len = stream->urb_size, ret;
1460 
1461 	if (buf == NULL) {
1462 		urb->transfer_buffer_length = 0;
1463 		return;
1464 	}
1465 
1466 	/* If the URB is the first of its payload, add the header. */
1467 	if (stream->bulk.header_size == 0) {
1468 		ret = uvc_video_encode_header(stream, buf, mem, len);
1469 		stream->bulk.header_size = ret;
1470 		stream->bulk.payload_size += ret;
1471 		mem += ret;
1472 		len -= ret;
1473 	}
1474 
1475 	/* Process video data. */
1476 	ret = uvc_video_encode_data(stream, buf, mem, len);
1477 
1478 	stream->bulk.payload_size += ret;
1479 	len -= ret;
1480 
1481 	if (buf->bytesused == stream->queue.buf_used ||
1482 	    stream->bulk.payload_size == stream->bulk.max_payload_size) {
1483 		if (buf->bytesused == stream->queue.buf_used) {
1484 			stream->queue.buf_used = 0;
1485 			buf->state = UVC_BUF_STATE_READY;
1486 			buf->buf.sequence = ++stream->sequence;
1487 			uvc_queue_next_buffer(&stream->queue, buf);
1488 			stream->last_fid ^= UVC_STREAM_FID;
1489 		}
1490 
1491 		stream->bulk.header_size = 0;
1492 		stream->bulk.payload_size = 0;
1493 	}
1494 
1495 	urb->transfer_buffer_length = stream->urb_size - len;
1496 }
1497 
1498 static void uvc_video_complete(struct urb *urb)
1499 {
1500 	struct uvc_urb *uvc_urb = urb->context;
1501 	struct uvc_streaming *stream = uvc_urb->stream;
1502 	struct uvc_video_queue *queue = &stream->queue;
1503 	struct uvc_video_queue *qmeta = &stream->meta.queue;
1504 	struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
1505 	struct uvc_buffer *buf = NULL;
1506 	struct uvc_buffer *buf_meta = NULL;
1507 	unsigned long flags;
1508 	int ret;
1509 
1510 	switch (urb->status) {
1511 	case 0:
1512 		break;
1513 
1514 	default:
1515 		uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1516 			"completion handler.\n", urb->status);
1517 		/* fall through */
1518 	case -ENOENT:		/* usb_poison_urb() called. */
1519 		if (stream->frozen)
1520 			return;
1521 		/* fall through */
1522 	case -ECONNRESET:	/* usb_unlink_urb() called. */
1523 	case -ESHUTDOWN:	/* The endpoint is being disabled. */
1524 		uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1525 		if (vb2_qmeta)
1526 			uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
1527 		return;
1528 	}
1529 
1530 	buf = uvc_queue_get_current_buffer(queue);
1531 
1532 	if (vb2_qmeta) {
1533 		spin_lock_irqsave(&qmeta->irqlock, flags);
1534 		if (!list_empty(&qmeta->irqqueue))
1535 			buf_meta = list_first_entry(&qmeta->irqqueue,
1536 						    struct uvc_buffer, queue);
1537 		spin_unlock_irqrestore(&qmeta->irqlock, flags);
1538 	}
1539 
1540 	/* Re-initialise the URB async work. */
1541 	uvc_urb->async_operations = 0;
1542 
1543 	/*
1544 	 * Process the URB headers, and optionally queue expensive memcpy tasks
1545 	 * to be deferred to a work queue.
1546 	 */
1547 	stream->decode(uvc_urb, buf, buf_meta);
1548 
1549 	/* If no async work is needed, resubmit the URB immediately. */
1550 	if (!uvc_urb->async_operations) {
1551 		ret = usb_submit_urb(uvc_urb->urb, GFP_ATOMIC);
1552 		if (ret < 0)
1553 			uvc_printk(KERN_ERR,
1554 				   "Failed to resubmit video URB (%d).\n",
1555 				   ret);
1556 		return;
1557 	}
1558 
1559 	queue_work(stream->async_wq, &uvc_urb->work);
1560 }
1561 
1562 /*
1563  * Free transfer buffers.
1564  */
1565 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1566 {
1567 	struct uvc_urb *uvc_urb;
1568 
1569 	for_each_uvc_urb(uvc_urb, stream) {
1570 		if (!uvc_urb->buffer)
1571 			continue;
1572 
1573 #ifndef CONFIG_DMA_NONCOHERENT
1574 		usb_free_coherent(stream->dev->udev, stream->urb_size,
1575 				  uvc_urb->buffer, uvc_urb->dma);
1576 #else
1577 		kfree(uvc_urb->buffer);
1578 #endif
1579 		uvc_urb->buffer = NULL;
1580 	}
1581 
1582 	stream->urb_size = 0;
1583 }
1584 
1585 /*
1586  * Allocate transfer buffers. This function can be called with buffers
1587  * already allocated when resuming from suspend, in which case it will
1588  * return without touching the buffers.
1589  *
1590  * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1591  * system is too low on memory try successively smaller numbers of packets
1592  * until allocation succeeds.
1593  *
1594  * Return the number of allocated packets on success or 0 when out of memory.
1595  */
1596 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1597 	unsigned int size, unsigned int psize, gfp_t gfp_flags)
1598 {
1599 	unsigned int npackets;
1600 	unsigned int i;
1601 
1602 	/* Buffers are already allocated, bail out. */
1603 	if (stream->urb_size)
1604 		return stream->urb_size / psize;
1605 
1606 	/* Compute the number of packets. Bulk endpoints might transfer UVC
1607 	 * payloads across multiple URBs.
1608 	 */
1609 	npackets = DIV_ROUND_UP(size, psize);
1610 	if (npackets > UVC_MAX_PACKETS)
1611 		npackets = UVC_MAX_PACKETS;
1612 
1613 	/* Retry allocations until one succeed. */
1614 	for (; npackets > 1; npackets /= 2) {
1615 		for (i = 0; i < UVC_URBS; ++i) {
1616 			struct uvc_urb *uvc_urb = &stream->uvc_urb[i];
1617 
1618 			stream->urb_size = psize * npackets;
1619 #ifndef CONFIG_DMA_NONCOHERENT
1620 			uvc_urb->buffer = usb_alloc_coherent(
1621 				stream->dev->udev, stream->urb_size,
1622 				gfp_flags | __GFP_NOWARN, &uvc_urb->dma);
1623 #else
1624 			uvc_urb->buffer =
1625 			    kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1626 #endif
1627 			if (!uvc_urb->buffer) {
1628 				uvc_free_urb_buffers(stream);
1629 				break;
1630 			}
1631 
1632 			uvc_urb->stream = stream;
1633 		}
1634 
1635 		if (i == UVC_URBS) {
1636 			uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1637 				"of %ux%u bytes each.\n", UVC_URBS, npackets,
1638 				psize);
1639 			return npackets;
1640 		}
1641 	}
1642 
1643 	uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1644 		"per packet).\n", psize);
1645 	return 0;
1646 }
1647 
1648 /*
1649  * Uninitialize isochronous/bulk URBs and free transfer buffers.
1650  */
1651 static void uvc_video_stop_transfer(struct uvc_streaming *stream,
1652 				    int free_buffers)
1653 {
1654 	struct uvc_urb *uvc_urb;
1655 
1656 	uvc_video_stats_stop(stream);
1657 
1658 	/*
1659 	 * We must poison the URBs rather than kill them to ensure that even
1660 	 * after the completion handler returns, any asynchronous workqueues
1661 	 * will be prevented from resubmitting the URBs.
1662 	 */
1663 	for_each_uvc_urb(uvc_urb, stream)
1664 		usb_poison_urb(uvc_urb->urb);
1665 
1666 	flush_workqueue(stream->async_wq);
1667 
1668 	for_each_uvc_urb(uvc_urb, stream) {
1669 		usb_free_urb(uvc_urb->urb);
1670 		uvc_urb->urb = NULL;
1671 	}
1672 
1673 	if (free_buffers)
1674 		uvc_free_urb_buffers(stream);
1675 }
1676 
1677 /*
1678  * Compute the maximum number of bytes per interval for an endpoint.
1679  */
1680 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1681 					 struct usb_host_endpoint *ep)
1682 {
1683 	u16 psize;
1684 	u16 mult;
1685 
1686 	switch (dev->speed) {
1687 	case USB_SPEED_SUPER:
1688 	case USB_SPEED_SUPER_PLUS:
1689 		return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1690 	case USB_SPEED_HIGH:
1691 		psize = usb_endpoint_maxp(&ep->desc);
1692 		mult = usb_endpoint_maxp_mult(&ep->desc);
1693 		return psize * mult;
1694 	case USB_SPEED_WIRELESS:
1695 		psize = usb_endpoint_maxp(&ep->desc);
1696 		return psize;
1697 	default:
1698 		psize = usb_endpoint_maxp(&ep->desc);
1699 		return psize;
1700 	}
1701 }
1702 
1703 /*
1704  * Initialize isochronous URBs and allocate transfer buffers. The packet size
1705  * is given by the endpoint.
1706  */
1707 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1708 	struct usb_host_endpoint *ep, gfp_t gfp_flags)
1709 {
1710 	struct urb *urb;
1711 	struct uvc_urb *uvc_urb;
1712 	unsigned int npackets, i;
1713 	u16 psize;
1714 	u32 size;
1715 
1716 	psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1717 	size = stream->ctrl.dwMaxVideoFrameSize;
1718 
1719 	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1720 	if (npackets == 0)
1721 		return -ENOMEM;
1722 
1723 	size = npackets * psize;
1724 
1725 	for_each_uvc_urb(uvc_urb, stream) {
1726 		urb = usb_alloc_urb(npackets, gfp_flags);
1727 		if (urb == NULL) {
1728 			uvc_video_stop_transfer(stream, 1);
1729 			return -ENOMEM;
1730 		}
1731 
1732 		urb->dev = stream->dev->udev;
1733 		urb->context = uvc_urb;
1734 		urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1735 				ep->desc.bEndpointAddress);
1736 #ifndef CONFIG_DMA_NONCOHERENT
1737 		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1738 		urb->transfer_dma = uvc_urb->dma;
1739 #else
1740 		urb->transfer_flags = URB_ISO_ASAP;
1741 #endif
1742 		urb->interval = ep->desc.bInterval;
1743 		urb->transfer_buffer = uvc_urb->buffer;
1744 		urb->complete = uvc_video_complete;
1745 		urb->number_of_packets = npackets;
1746 		urb->transfer_buffer_length = size;
1747 
1748 		for (i = 0; i < npackets; ++i) {
1749 			urb->iso_frame_desc[i].offset = i * psize;
1750 			urb->iso_frame_desc[i].length = psize;
1751 		}
1752 
1753 		uvc_urb->urb = urb;
1754 	}
1755 
1756 	return 0;
1757 }
1758 
1759 /*
1760  * Initialize bulk URBs and allocate transfer buffers. The packet size is
1761  * given by the endpoint.
1762  */
1763 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1764 	struct usb_host_endpoint *ep, gfp_t gfp_flags)
1765 {
1766 	struct urb *urb;
1767 	struct uvc_urb *uvc_urb;
1768 	unsigned int npackets, pipe;
1769 	u16 psize;
1770 	u32 size;
1771 
1772 	psize = usb_endpoint_maxp(&ep->desc);
1773 	size = stream->ctrl.dwMaxPayloadTransferSize;
1774 	stream->bulk.max_payload_size = size;
1775 
1776 	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1777 	if (npackets == 0)
1778 		return -ENOMEM;
1779 
1780 	size = npackets * psize;
1781 
1782 	if (usb_endpoint_dir_in(&ep->desc))
1783 		pipe = usb_rcvbulkpipe(stream->dev->udev,
1784 				       ep->desc.bEndpointAddress);
1785 	else
1786 		pipe = usb_sndbulkpipe(stream->dev->udev,
1787 				       ep->desc.bEndpointAddress);
1788 
1789 	if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1790 		size = 0;
1791 
1792 	for_each_uvc_urb(uvc_urb, stream) {
1793 		urb = usb_alloc_urb(0, gfp_flags);
1794 		if (urb == NULL) {
1795 			uvc_video_stop_transfer(stream, 1);
1796 			return -ENOMEM;
1797 		}
1798 
1799 		usb_fill_bulk_urb(urb, stream->dev->udev, pipe,	uvc_urb->buffer,
1800 				  size, uvc_video_complete, uvc_urb);
1801 #ifndef CONFIG_DMA_NONCOHERENT
1802 		urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1803 		urb->transfer_dma = uvc_urb->dma;
1804 #endif
1805 
1806 		uvc_urb->urb = urb;
1807 	}
1808 
1809 	return 0;
1810 }
1811 
1812 /*
1813  * Initialize isochronous/bulk URBs and allocate transfer buffers.
1814  */
1815 static int uvc_video_start_transfer(struct uvc_streaming *stream,
1816 				    gfp_t gfp_flags)
1817 {
1818 	struct usb_interface *intf = stream->intf;
1819 	struct usb_host_endpoint *ep;
1820 	struct uvc_urb *uvc_urb;
1821 	unsigned int i;
1822 	int ret;
1823 
1824 	stream->sequence = -1;
1825 	stream->last_fid = -1;
1826 	stream->bulk.header_size = 0;
1827 	stream->bulk.skip_payload = 0;
1828 	stream->bulk.payload_size = 0;
1829 
1830 	uvc_video_stats_start(stream);
1831 
1832 	if (intf->num_altsetting > 1) {
1833 		struct usb_host_endpoint *best_ep = NULL;
1834 		unsigned int best_psize = UINT_MAX;
1835 		unsigned int bandwidth;
1836 		unsigned int uninitialized_var(altsetting);
1837 		int intfnum = stream->intfnum;
1838 
1839 		/* Isochronous endpoint, select the alternate setting. */
1840 		bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1841 
1842 		if (bandwidth == 0) {
1843 			uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1844 				"bandwidth, defaulting to lowest.\n");
1845 			bandwidth = 1;
1846 		} else {
1847 			uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1848 				"B/frame bandwidth.\n", bandwidth);
1849 		}
1850 
1851 		for (i = 0; i < intf->num_altsetting; ++i) {
1852 			struct usb_host_interface *alts;
1853 			unsigned int psize;
1854 
1855 			alts = &intf->altsetting[i];
1856 			ep = uvc_find_endpoint(alts,
1857 				stream->header.bEndpointAddress);
1858 			if (ep == NULL)
1859 				continue;
1860 
1861 			/* Check if the bandwidth is high enough. */
1862 			psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1863 			if (psize >= bandwidth && psize <= best_psize) {
1864 				altsetting = alts->desc.bAlternateSetting;
1865 				best_psize = psize;
1866 				best_ep = ep;
1867 			}
1868 		}
1869 
1870 		if (best_ep == NULL) {
1871 			uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1872 				"for requested bandwidth.\n");
1873 			return -EIO;
1874 		}
1875 
1876 		uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1877 			"(%u B/frame bandwidth).\n", altsetting, best_psize);
1878 
1879 		ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1880 		if (ret < 0)
1881 			return ret;
1882 
1883 		ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1884 	} else {
1885 		/* Bulk endpoint, proceed to URB initialization. */
1886 		ep = uvc_find_endpoint(&intf->altsetting[0],
1887 				stream->header.bEndpointAddress);
1888 		if (ep == NULL)
1889 			return -EIO;
1890 
1891 		ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1892 	}
1893 
1894 	if (ret < 0)
1895 		return ret;
1896 
1897 	/* Submit the URBs. */
1898 	for_each_uvc_urb(uvc_urb, stream) {
1899 		ret = usb_submit_urb(uvc_urb->urb, gfp_flags);
1900 		if (ret < 0) {
1901 			uvc_printk(KERN_ERR, "Failed to submit URB %u (%d).\n",
1902 				   uvc_urb_index(uvc_urb), ret);
1903 			uvc_video_stop_transfer(stream, 1);
1904 			return ret;
1905 		}
1906 	}
1907 
1908 	/* The Logitech C920 temporarily forgets that it should not be adjusting
1909 	 * Exposure Absolute during init so restore controls to stored values.
1910 	 */
1911 	if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1912 		uvc_ctrl_restore_values(stream->dev);
1913 
1914 	return 0;
1915 }
1916 
1917 /* --------------------------------------------------------------------------
1918  * Suspend/resume
1919  */
1920 
1921 /*
1922  * Stop streaming without disabling the video queue.
1923  *
1924  * To let userspace applications resume without trouble, we must not touch the
1925  * video buffers in any way. We mark the device as frozen to make sure the URB
1926  * completion handler won't try to cancel the queue when we kill the URBs.
1927  */
1928 int uvc_video_suspend(struct uvc_streaming *stream)
1929 {
1930 	if (!uvc_queue_streaming(&stream->queue))
1931 		return 0;
1932 
1933 	stream->frozen = 1;
1934 	uvc_video_stop_transfer(stream, 0);
1935 	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1936 	return 0;
1937 }
1938 
1939 /*
1940  * Reconfigure the video interface and restart streaming if it was enabled
1941  * before suspend.
1942  *
1943  * If an error occurs, disable the video queue. This will wake all pending
1944  * buffers, making sure userspace applications are notified of the problem
1945  * instead of waiting forever.
1946  */
1947 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1948 {
1949 	int ret;
1950 
1951 	/* If the bus has been reset on resume, set the alternate setting to 0.
1952 	 * This should be the default value, but some devices crash or otherwise
1953 	 * misbehave if they don't receive a SET_INTERFACE request before any
1954 	 * other video control request.
1955 	 */
1956 	if (reset)
1957 		usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1958 
1959 	stream->frozen = 0;
1960 
1961 	uvc_video_clock_reset(stream);
1962 
1963 	if (!uvc_queue_streaming(&stream->queue))
1964 		return 0;
1965 
1966 	ret = uvc_commit_video(stream, &stream->ctrl);
1967 	if (ret < 0)
1968 		return ret;
1969 
1970 	return uvc_video_start_transfer(stream, GFP_NOIO);
1971 }
1972 
1973 /* ------------------------------------------------------------------------
1974  * Video device
1975  */
1976 
1977 /*
1978  * Initialize the UVC video device by switching to alternate setting 0 and
1979  * retrieve the default format.
1980  *
1981  * Some cameras (namely the Fuji Finepix) set the format and frame
1982  * indexes to zero. The UVC standard doesn't clearly make this a spec
1983  * violation, so try to silently fix the values if possible.
1984  *
1985  * This function is called before registering the device with V4L.
1986  */
1987 int uvc_video_init(struct uvc_streaming *stream)
1988 {
1989 	struct uvc_streaming_control *probe = &stream->ctrl;
1990 	struct uvc_format *format = NULL;
1991 	struct uvc_frame *frame = NULL;
1992 	struct uvc_urb *uvc_urb;
1993 	unsigned int i;
1994 	int ret;
1995 
1996 	if (stream->nformats == 0) {
1997 		uvc_printk(KERN_INFO, "No supported video formats found.\n");
1998 		return -EINVAL;
1999 	}
2000 
2001 	atomic_set(&stream->active, 0);
2002 
2003 	/* Alternate setting 0 should be the default, yet the XBox Live Vision
2004 	 * Cam (and possibly other devices) crash or otherwise misbehave if
2005 	 * they don't receive a SET_INTERFACE request before any other video
2006 	 * control request.
2007 	 */
2008 	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2009 
2010 	/* Set the streaming probe control with default streaming parameters
2011 	 * retrieved from the device. Webcams that don't support GET_DEF
2012 	 * requests on the probe control will just keep their current streaming
2013 	 * parameters.
2014 	 */
2015 	if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
2016 		uvc_set_video_ctrl(stream, probe, 1);
2017 
2018 	/* Initialize the streaming parameters with the probe control current
2019 	 * value. This makes sure SET_CUR requests on the streaming commit
2020 	 * control will always use values retrieved from a successful GET_CUR
2021 	 * request on the probe control, as required by the UVC specification.
2022 	 */
2023 	ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
2024 	if (ret < 0)
2025 		return ret;
2026 
2027 	/* Check if the default format descriptor exists. Use the first
2028 	 * available format otherwise.
2029 	 */
2030 	for (i = stream->nformats; i > 0; --i) {
2031 		format = &stream->format[i-1];
2032 		if (format->index == probe->bFormatIndex)
2033 			break;
2034 	}
2035 
2036 	if (format->nframes == 0) {
2037 		uvc_printk(KERN_INFO, "No frame descriptor found for the "
2038 			"default format.\n");
2039 		return -EINVAL;
2040 	}
2041 
2042 	/* Zero bFrameIndex might be correct. Stream-based formats (including
2043 	 * MPEG-2 TS and DV) do not support frames but have a dummy frame
2044 	 * descriptor with bFrameIndex set to zero. If the default frame
2045 	 * descriptor is not found, use the first available frame.
2046 	 */
2047 	for (i = format->nframes; i > 0; --i) {
2048 		frame = &format->frame[i-1];
2049 		if (frame->bFrameIndex == probe->bFrameIndex)
2050 			break;
2051 	}
2052 
2053 	probe->bFormatIndex = format->index;
2054 	probe->bFrameIndex = frame->bFrameIndex;
2055 
2056 	stream->def_format = format;
2057 	stream->cur_format = format;
2058 	stream->cur_frame = frame;
2059 
2060 	/* Select the video decoding function */
2061 	if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2062 		if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
2063 			stream->decode = uvc_video_decode_isight;
2064 		else if (stream->intf->num_altsetting > 1)
2065 			stream->decode = uvc_video_decode_isoc;
2066 		else
2067 			stream->decode = uvc_video_decode_bulk;
2068 	} else {
2069 		if (stream->intf->num_altsetting == 1)
2070 			stream->decode = uvc_video_encode_bulk;
2071 		else {
2072 			uvc_printk(KERN_INFO, "Isochronous endpoints are not "
2073 				"supported for video output devices.\n");
2074 			return -EINVAL;
2075 		}
2076 	}
2077 
2078 	/* Prepare asynchronous work items. */
2079 	for_each_uvc_urb(uvc_urb, stream)
2080 		INIT_WORK(&uvc_urb->work, uvc_video_copy_data_work);
2081 
2082 	return 0;
2083 }
2084 
2085 int uvc_video_start_streaming(struct uvc_streaming *stream)
2086 {
2087 	int ret;
2088 
2089 	ret = uvc_video_clock_init(stream);
2090 	if (ret < 0)
2091 		return ret;
2092 
2093 	/* Commit the streaming parameters. */
2094 	ret = uvc_commit_video(stream, &stream->ctrl);
2095 	if (ret < 0)
2096 		goto error_commit;
2097 
2098 	ret = uvc_video_start_transfer(stream, GFP_KERNEL);
2099 	if (ret < 0)
2100 		goto error_video;
2101 
2102 	return 0;
2103 
2104 error_video:
2105 	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2106 error_commit:
2107 	uvc_video_clock_cleanup(stream);
2108 
2109 	return ret;
2110 }
2111 
2112 void uvc_video_stop_streaming(struct uvc_streaming *stream)
2113 {
2114 	uvc_video_stop_transfer(stream, 1);
2115 
2116 	if (stream->intf->num_altsetting > 1) {
2117 		usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2118 	} else {
2119 		/* UVC doesn't specify how to inform a bulk-based device
2120 		 * when the video stream is stopped. Windows sends a
2121 		 * CLEAR_FEATURE(HALT) request to the video streaming
2122 		 * bulk endpoint, mimic the same behaviour.
2123 		 */
2124 		unsigned int epnum = stream->header.bEndpointAddress
2125 				   & USB_ENDPOINT_NUMBER_MASK;
2126 		unsigned int dir = stream->header.bEndpointAddress
2127 				 & USB_ENDPOINT_DIR_MASK;
2128 		unsigned int pipe;
2129 
2130 		pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
2131 		usb_clear_halt(stream->dev->udev, pipe);
2132 	}
2133 
2134 	uvc_video_clock_cleanup(stream);
2135 }
2136