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