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