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