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