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