]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - drivers/media/video/uvc/uvc_video.c
[media] uvcvideo: Extract timestamp-related statistics
[mirror_ubuntu-hirsute-kernel.git] / drivers / media / video / 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
a2e35af6
LP
122 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
123 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
35f02a68 124 stream->intf->num_altsetting > 1) {
50144aee
LP
125 u32 interval;
126 u32 bandwidth;
127
128 interval = (ctrl->dwFrameInterval > 100000)
129 ? ctrl->dwFrameInterval
130 : frame->dwFrameInterval[0];
131
132 /* Compute a bandwidth estimation by multiplying the frame
133 * size by the number of video frames per second, divide the
134 * result by the number of USB frames (or micro-frames for
135 * high-speed devices) per second and add the UVC header size
136 * (assumed to be 12 bytes long).
137 */
138 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
139 bandwidth *= 10000000 / interval + 1;
140 bandwidth /= 1000;
35f02a68 141 if (stream->dev->udev->speed == USB_SPEED_HIGH)
50144aee
LP
142 bandwidth /= 8;
143 bandwidth += 12;
144
9bb7262d
LP
145 /* The bandwidth estimate is too low for many cameras. Don't use
146 * maximum packet sizes lower than 1024 bytes to try and work
147 * around the problem. According to measurements done on two
148 * different camera models, the value is high enough to get most
149 * resolutions working while not preventing two simultaneous
150 * VGA streams at 15 fps.
151 */
152 bandwidth = max_t(u32, bandwidth, 1024);
153
50144aee
LP
154 ctrl->dwMaxPayloadTransferSize = bandwidth;
155 }
c0efd232
LP
156}
157
35f02a68 158static int uvc_get_video_ctrl(struct uvc_streaming *stream,
c0efd232
LP
159 struct uvc_streaming_control *ctrl, int probe, __u8 query)
160{
04793dd0
LP
161 __u8 *data;
162 __u16 size;
c0efd232
LP
163 int ret;
164
35f02a68 165 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
d2be7643
JL
166 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
167 query == UVC_GET_DEF)
168 return -EIO;
169
04793dd0
LP
170 data = kmalloc(size, GFP_KERNEL);
171 if (data == NULL)
172 return -ENOMEM;
173
35f02a68 174 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
b482d923 175 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
b232a012 176 size, uvc_timeout_param);
44f0079e 177
b482d923 178 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
44f0079e
LP
179 /* Some cameras, mostly based on Bison Electronics chipsets,
180 * answer a GET_MIN or GET_MAX request with the wCompQuality
181 * field only.
182 */
35f02a68 183 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
44f0079e
LP
184 "compliance - GET_MIN/MAX(PROBE) incorrectly "
185 "supported. Enabling workaround.\n");
ddb0b34f 186 memset(ctrl, 0, sizeof *ctrl);
44f0079e
LP
187 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
188 ret = 0;
04793dd0 189 goto out;
b482d923 190 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
44f0079e
LP
191 /* Many cameras don't support the GET_DEF request on their
192 * video probe control. Warn once and return, the caller will
193 * fall back to GET_CUR.
194 */
35f02a68 195 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
44f0079e
LP
196 "compliance - GET_DEF(PROBE) not supported. "
197 "Enabling workaround.\n");
198 ret = -EIO;
199 goto out;
200 } else if (ret != size) {
201 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
202 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
203 ret, size);
204 ret = -EIO;
205 goto out;
206 }
c0efd232
LP
207
208 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
209 ctrl->bFormatIndex = data[2];
210 ctrl->bFrameIndex = data[3];
211 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
212 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
213 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
214 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
215 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
216 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
4d3939f6
LP
217 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
218 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
c0efd232
LP
219
220 if (size == 34) {
4d3939f6 221 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
c0efd232
LP
222 ctrl->bmFramingInfo = data[30];
223 ctrl->bPreferedVersion = data[31];
224 ctrl->bMinVersion = data[32];
225 ctrl->bMaxVersion = data[33];
226 } else {
35f02a68 227 ctrl->dwClockFrequency = stream->dev->clock_frequency;
c0efd232
LP
228 ctrl->bmFramingInfo = 0;
229 ctrl->bPreferedVersion = 0;
230 ctrl->bMinVersion = 0;
231 ctrl->bMaxVersion = 0;
232 }
233
50144aee
LP
234 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
235 * dwMaxPayloadTransferSize fields. Try to get the value from the
236 * format and frame descriptors.
c0efd232 237 */
35f02a68 238 uvc_fixup_video_ctrl(stream, ctrl);
44f0079e 239 ret = 0;
c0efd232 240
04793dd0
LP
241out:
242 kfree(data);
243 return ret;
c0efd232
LP
244}
245
35f02a68 246static int uvc_set_video_ctrl(struct uvc_streaming *stream,
c0efd232
LP
247 struct uvc_streaming_control *ctrl, int probe)
248{
04793dd0
LP
249 __u8 *data;
250 __u16 size;
251 int ret;
c0efd232 252
35f02a68 253 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
04793dd0
LP
254 data = kzalloc(size, GFP_KERNEL);
255 if (data == NULL)
256 return -ENOMEM;
c0efd232
LP
257
258 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
259 data[2] = ctrl->bFormatIndex;
260 data[3] = ctrl->bFrameIndex;
261 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
262 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
263 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
264 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
265 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
266 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
4d3939f6
LP
267 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
268 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
c0efd232
LP
269
270 if (size == 34) {
4d3939f6 271 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
c0efd232
LP
272 data[30] = ctrl->bmFramingInfo;
273 data[31] = ctrl->bPreferedVersion;
274 data[32] = ctrl->bMinVersion;
275 data[33] = ctrl->bMaxVersion;
276 }
277
35f02a68 278 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
b482d923 279 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
b232a012 280 size, uvc_timeout_param);
44f0079e
LP
281 if (ret != size) {
282 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
283 "%d (exp. %u).\n", probe ? "probe" : "commit",
284 ret, size);
285 ret = -EIO;
286 }
04793dd0
LP
287
288 kfree(data);
289 return ret;
c0efd232
LP
290}
291
35f02a68 292int uvc_probe_video(struct uvc_streaming *stream,
c0efd232
LP
293 struct uvc_streaming_control *probe)
294{
295 struct uvc_streaming_control probe_min, probe_max;
296 __u16 bandwidth;
297 unsigned int i;
298 int ret;
299
c0efd232
LP
300 /* Perform probing. The device should adjust the requested values
301 * according to its capabilities. However, some devices, namely the
302 * first generation UVC Logitech webcams, don't implement the Video
303 * Probe control properly, and just return the needed bandwidth. For
304 * that reason, if the needed bandwidth exceeds the maximum available
305 * bandwidth, try to lower the quality.
306 */
35f02a68
LP
307 ret = uvc_set_video_ctrl(stream, probe, 1);
308 if (ret < 0)
c0efd232
LP
309 goto done;
310
311 /* Get the minimum and maximum values for compression settings. */
35f02a68
LP
312 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
313 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
c0efd232
LP
314 if (ret < 0)
315 goto done;
35f02a68 316 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
c0efd232
LP
317 if (ret < 0)
318 goto done;
319
320 probe->wCompQuality = probe_max.wCompQuality;
321 }
322
323 for (i = 0; i < 2; ++i) {
35f02a68 324 ret = uvc_set_video_ctrl(stream, probe, 1);
b482d923
LP
325 if (ret < 0)
326 goto done;
35f02a68 327 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
b482d923 328 if (ret < 0)
c0efd232
LP
329 goto done;
330
35f02a68 331 if (stream->intf->num_altsetting == 1)
c0efd232
LP
332 break;
333
334 bandwidth = probe->dwMaxPayloadTransferSize;
35f02a68 335 if (bandwidth <= stream->maxpsize)
c0efd232
LP
336 break;
337
35f02a68 338 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
c0efd232
LP
339 ret = -ENOSPC;
340 goto done;
341 }
342
343 /* TODO: negotiate compression parameters */
344 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
345 probe->wPFrameRate = probe_min.wPFrameRate;
346 probe->wCompQuality = probe_max.wCompQuality;
347 probe->wCompWindowSize = probe_min.wCompWindowSize;
348 }
349
350done:
c0efd232
LP
351 return ret;
352}
353
0c6a3b26
LP
354static int uvc_commit_video(struct uvc_streaming *stream,
355 struct uvc_streaming_control *probe)
44f0079e 356{
35f02a68 357 return uvc_set_video_ctrl(stream, probe, 0);
44f0079e
LP
358}
359
7bc5edb0
OR
360/* ------------------------------------------------------------------------
361 * Stream statistics
362 */
363
364static void uvc_video_stats_decode(struct uvc_streaming *stream,
365 const __u8 *data, int len)
366{
367 unsigned int header_size;
25738cbd
LP
368 bool has_pts = false;
369 bool has_scr = false;
370 u16 uninitialized_var(scr_sof);
371 u32 uninitialized_var(scr_stc);
372 u32 uninitialized_var(pts);
7bc5edb0
OR
373
374 if (stream->stats.stream.nb_frames == 0 &&
375 stream->stats.frame.nb_packets == 0)
376 ktime_get_ts(&stream->stats.stream.start_ts);
377
378 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
379 case UVC_STREAM_PTS | UVC_STREAM_SCR:
380 header_size = 12;
25738cbd
LP
381 has_pts = true;
382 has_scr = true;
7bc5edb0
OR
383 break;
384 case UVC_STREAM_PTS:
385 header_size = 6;
25738cbd 386 has_pts = true;
7bc5edb0
OR
387 break;
388 case UVC_STREAM_SCR:
389 header_size = 8;
25738cbd 390 has_scr = true;
7bc5edb0
OR
391 break;
392 default:
393 header_size = 2;
394 break;
395 }
396
397 /* Check for invalid headers. */
398 if (len < header_size || data[0] < header_size) {
399 stream->stats.frame.nb_invalid++;
400 return;
401 }
402
25738cbd
LP
403 /* Extract the timestamps. */
404 if (has_pts)
405 pts = get_unaligned_le32(&data[2]);
406
407 if (has_scr) {
408 scr_stc = get_unaligned_le32(&data[header_size - 6]);
409 scr_sof = get_unaligned_le16(&data[header_size - 2]);
410 }
411
412 /* Is PTS constant through the whole frame ? */
413 if (has_pts && stream->stats.frame.nb_pts) {
414 if (stream->stats.frame.pts != pts) {
415 stream->stats.frame.nb_pts_diffs++;
416 stream->stats.frame.last_pts_diff =
417 stream->stats.frame.nb_packets;
418 }
419 }
420
421 if (has_pts) {
422 stream->stats.frame.nb_pts++;
423 stream->stats.frame.pts = pts;
424 }
425
426 /* Do all frames have a PTS in their first non-empty packet, or before
427 * their first empty packet ?
428 */
429 if (stream->stats.frame.size == 0) {
430 if (len > header_size)
431 stream->stats.frame.has_initial_pts = has_pts;
432 if (len == header_size && has_pts)
433 stream->stats.frame.has_early_pts = true;
434 }
435
436 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
437 if (has_scr && stream->stats.frame.nb_scr) {
438 if (stream->stats.frame.scr_stc != scr_stc)
439 stream->stats.frame.nb_scr_diffs++;
440 }
441
442 if (has_scr) {
443 /* Expand the SOF counter to 32 bits and store its value. */
444 if (stream->stats.stream.nb_frames > 0 ||
445 stream->stats.frame.nb_scr > 0)
446 stream->stats.stream.scr_sof_count +=
447 (scr_sof - stream->stats.stream.scr_sof) % 2048;
448 stream->stats.stream.scr_sof = scr_sof;
449
450 stream->stats.frame.nb_scr++;
451 stream->stats.frame.scr_stc = scr_stc;
452 stream->stats.frame.scr_sof = scr_sof;
453
454 if (scr_sof < stream->stats.stream.min_sof)
455 stream->stats.stream.min_sof = scr_sof;
456 if (scr_sof > stream->stats.stream.max_sof)
457 stream->stats.stream.max_sof = scr_sof;
458 }
459
7bc5edb0
OR
460 /* Record the first non-empty packet number. */
461 if (stream->stats.frame.size == 0 && len > header_size)
462 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
463
464 /* Update the frame size. */
465 stream->stats.frame.size += len - header_size;
466
467 /* Update the packets counters. */
468 stream->stats.frame.nb_packets++;
469 if (len > header_size)
470 stream->stats.frame.nb_empty++;
471
472 if (data[1] & UVC_STREAM_ERR)
473 stream->stats.frame.nb_errors++;
474}
475
476static void uvc_video_stats_update(struct uvc_streaming *stream)
477{
478 struct uvc_stats_frame *frame = &stream->stats.frame;
479
25738cbd
LP
480 uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
481 "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
482 "last pts/stc/sof %u/%u/%u\n",
7bc5edb0 483 stream->sequence, frame->first_data,
25738cbd
LP
484 frame->nb_packets - frame->nb_empty, frame->nb_packets,
485 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
486 frame->has_early_pts ? "" : "!",
487 frame->has_initial_pts ? "" : "!",
488 frame->nb_scr_diffs, frame->nb_scr,
489 frame->pts, frame->scr_stc, frame->scr_sof);
7bc5edb0
OR
490
491 stream->stats.stream.nb_frames++;
492 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
493 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
494 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
495 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
496
25738cbd
LP
497 if (frame->has_early_pts)
498 stream->stats.stream.nb_pts_early++;
499 if (frame->has_initial_pts)
500 stream->stats.stream.nb_pts_initial++;
501 if (frame->last_pts_diff <= frame->first_data)
502 stream->stats.stream.nb_pts_constant++;
503 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
504 stream->stats.stream.nb_scr_count_ok++;
505 if (frame->nb_scr_diffs + 1 == frame->nb_scr)
506 stream->stats.stream.nb_scr_diffs_ok++;
507
7bc5edb0
OR
508 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
509}
510
511size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
512 size_t size)
513{
25738cbd
LP
514 unsigned int scr_sof_freq;
515 unsigned int duration;
516 struct timespec ts;
7bc5edb0
OR
517 size_t count = 0;
518
25738cbd
LP
519 ts.tv_sec = stream->stats.stream.stop_ts.tv_sec
520 - stream->stats.stream.start_ts.tv_sec;
521 ts.tv_nsec = stream->stats.stream.stop_ts.tv_nsec
522 - stream->stats.stream.start_ts.tv_nsec;
523 if (ts.tv_nsec < 0) {
524 ts.tv_sec--;
525 ts.tv_nsec += 1000000000;
526 }
527
528 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
529 * frequency this will not overflow before more than 1h.
530 */
531 duration = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
532 if (duration != 0)
533 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
534 / duration;
535 else
536 scr_sof_freq = 0;
537
7bc5edb0
OR
538 count += scnprintf(buf + count, size - count,
539 "frames: %u\npackets: %u\nempty: %u\n"
540 "errors: %u\ninvalid: %u\n",
541 stream->stats.stream.nb_frames,
542 stream->stats.stream.nb_packets,
543 stream->stats.stream.nb_empty,
544 stream->stats.stream.nb_errors,
545 stream->stats.stream.nb_invalid);
25738cbd
LP
546 count += scnprintf(buf + count, size - count,
547 "pts: %u early, %u initial, %u ok\n",
548 stream->stats.stream.nb_pts_early,
549 stream->stats.stream.nb_pts_initial,
550 stream->stats.stream.nb_pts_constant);
551 count += scnprintf(buf + count, size - count,
552 "scr: %u count ok, %u diff ok\n",
553 stream->stats.stream.nb_scr_count_ok,
554 stream->stats.stream.nb_scr_diffs_ok);
555 count += scnprintf(buf + count, size - count,
556 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
557 stream->stats.stream.min_sof,
558 stream->stats.stream.max_sof,
559 scr_sof_freq / 1000, scr_sof_freq % 1000);
7bc5edb0
OR
560
561 return count;
562}
563
564static void uvc_video_stats_start(struct uvc_streaming *stream)
565{
566 memset(&stream->stats, 0, sizeof(stream->stats));
25738cbd 567 stream->stats.stream.min_sof = 2048;
7bc5edb0
OR
568}
569
570static void uvc_video_stats_stop(struct uvc_streaming *stream)
571{
572 ktime_get_ts(&stream->stats.stream.stop_ts);
573}
574
c0efd232
LP
575/* ------------------------------------------------------------------------
576 * Video codecs
577 */
578
c0efd232
LP
579/* Video payload decoding is handled by uvc_video_decode_start(),
580 * uvc_video_decode_data() and uvc_video_decode_end().
581 *
582 * uvc_video_decode_start is called with URB data at the start of a bulk or
583 * isochronous payload. It processes header data and returns the header size
584 * in bytes if successful. If an error occurs, it returns a negative error
585 * code. The following error codes have special meanings.
586 *
587 * - EAGAIN informs the caller that the current video buffer should be marked
588 * as done, and that the function should be called again with the same data
589 * and a new video buffer. This is used when end of frame conditions can be
590 * reliably detected at the beginning of the next frame only.
591 *
592 * If an error other than -EAGAIN is returned, the caller will drop the current
593 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
594 * made until the next payload. -ENODATA can be used to drop the current
595 * payload if no other error code is appropriate.
596 *
597 * uvc_video_decode_data is called for every URB with URB data. It copies the
598 * data to the video buffer.
599 *
600 * uvc_video_decode_end is called with header data at the end of a bulk or
601 * isochronous payload. It performs any additional header data processing and
25985edc 602 * returns 0 or a negative error code if an error occurred. As header data have
c0efd232
LP
603 * already been processed by uvc_video_decode_start, this functions isn't
604 * required to perform sanity checks a second time.
605 *
25985edc 606 * For isochronous transfers where a payload is always transferred in a single
c0efd232
LP
607 * URB, the three functions will be called in a row.
608 *
609 * To let the decoder process header data and update its internal state even
610 * when no video buffer is available, uvc_video_decode_start must be prepared
611 * to be called with a NULL buf parameter. uvc_video_decode_data and
612 * uvc_video_decode_end will never be called with a NULL buffer.
613 */
35f02a68 614static int uvc_video_decode_start(struct uvc_streaming *stream,
c0efd232
LP
615 struct uvc_buffer *buf, const __u8 *data, int len)
616{
617 __u8 fid;
618
619 /* Sanity checks:
620 * - packet must be at least 2 bytes long
621 * - bHeaderLength value must be at least 2 bytes (see above)
622 * - bHeaderLength value can't be larger than the packet size.
623 */
7bc5edb0
OR
624 if (len < 2 || data[0] < 2 || data[0] > len) {
625 stream->stats.frame.nb_invalid++;
c0efd232 626 return -EINVAL;
7bc5edb0 627 }
c0efd232 628
c0efd232
LP
629 fid = data[1] & UVC_STREAM_FID;
630
650b95fe
LP
631 /* Increase the sequence number regardless of any buffer states, so
632 * that discontinuous sequence numbers always indicate lost frames.
633 */
7bc5edb0 634 if (stream->last_fid != fid) {
650b95fe 635 stream->sequence++;
7bc5edb0
OR
636 if (stream->sequence)
637 uvc_video_stats_update(stream);
638 }
639
640 uvc_video_stats_decode(stream, data, len);
650b95fe 641
c0efd232
LP
642 /* Store the payload FID bit and return immediately when the buffer is
643 * NULL.
644 */
645 if (buf == NULL) {
35f02a68 646 stream->last_fid = fid;
c0efd232
LP
647 return -ENODATA;
648 }
649
3afedb95
LP
650 /* Mark the buffer as bad if the error bit is set. */
651 if (data[1] & UVC_STREAM_ERR) {
652 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
653 "set).\n");
654 buf->error = 1;
655 }
656
c0efd232
LP
657 /* Synchronize to the input stream by waiting for the FID bit to be
658 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
35f02a68 659 * stream->last_fid is initialized to -1, so the first isochronous
c0efd232
LP
660 * frame will always be in sync.
661 *
35f02a68 662 * If the device doesn't toggle the FID bit, invert stream->last_fid
c0efd232
LP
663 * when the EOF bit is set to force synchronisation on the next packet.
664 */
665 if (buf->state != UVC_BUF_STATE_ACTIVE) {
310fe524
LP
666 struct timespec ts;
667
35f02a68 668 if (fid == stream->last_fid) {
c0efd232
LP
669 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
670 "sync).\n");
35f02a68 671 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
c0efd232 672 (data[1] & UVC_STREAM_EOF))
35f02a68 673 stream->last_fid ^= UVC_STREAM_FID;
c0efd232
LP
674 return -ENODATA;
675 }
676
310fe524
LP
677 if (uvc_clock_param == CLOCK_MONOTONIC)
678 ktime_get_ts(&ts);
679 else
680 ktime_get_real_ts(&ts);
681
6998b6fb
LP
682 buf->buf.v4l2_buf.sequence = stream->sequence;
683 buf->buf.v4l2_buf.timestamp.tv_sec = ts.tv_sec;
684 buf->buf.v4l2_buf.timestamp.tv_usec =
685 ts.tv_nsec / NSEC_PER_USEC;
310fe524 686
c0efd232
LP
687 /* TODO: Handle PTS and SCR. */
688 buf->state = UVC_BUF_STATE_ACTIVE;
689 }
690
691 /* Mark the buffer as done if we're at the beginning of a new frame.
692 * End of frame detection is better implemented by checking the EOF
693 * bit (FID bit toggling is delayed by one frame compared to the EOF
694 * bit), but some devices don't set the bit at end of frame (and the
695 * last payload can be lost anyway). We thus must check if the FID has
696 * been toggled.
697 *
35f02a68 698 * stream->last_fid is initialized to -1, so the first isochronous
c0efd232
LP
699 * frame will never trigger an end of frame detection.
700 *
701 * Empty buffers (bytesused == 0) don't trigger end of frame detection
702 * as it doesn't make sense to return an empty buffer. This also
2c2d264b 703 * avoids detecting end of frame conditions at FID toggling if the
c0efd232
LP
704 * previous payload had the EOF bit set.
705 */
3d95e932 706 if (fid != stream->last_fid && buf->bytesused != 0) {
c0efd232
LP
707 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
708 "toggled).\n");
d7c0d439 709 buf->state = UVC_BUF_STATE_READY;
c0efd232
LP
710 return -EAGAIN;
711 }
712
35f02a68 713 stream->last_fid = fid;
c0efd232
LP
714
715 return data[0];
716}
717
35f02a68 718static void uvc_video_decode_data(struct uvc_streaming *stream,
c0efd232
LP
719 struct uvc_buffer *buf, const __u8 *data, int len)
720{
c0efd232
LP
721 unsigned int maxlen, nbytes;
722 void *mem;
723
724 if (len <= 0)
725 return;
726
727 /* Copy the video data to the buffer. */
3d95e932
LP
728 maxlen = buf->length - buf->bytesused;
729 mem = buf->mem + buf->bytesused;
c0efd232
LP
730 nbytes = min((unsigned int)len, maxlen);
731 memcpy(mem, data, nbytes);
3d95e932 732 buf->bytesused += nbytes;
c0efd232
LP
733
734 /* Complete the current frame if the buffer size was exceeded. */
735 if (len > maxlen) {
736 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
d7c0d439 737 buf->state = UVC_BUF_STATE_READY;
c0efd232
LP
738 }
739}
740
35f02a68 741static void uvc_video_decode_end(struct uvc_streaming *stream,
c0efd232
LP
742 struct uvc_buffer *buf, const __u8 *data, int len)
743{
744 /* Mark the buffer as done if the EOF marker is set. */
3d95e932 745 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
c0efd232
LP
746 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
747 if (data[0] == len)
748 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
d7c0d439 749 buf->state = UVC_BUF_STATE_READY;
35f02a68
LP
750 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
751 stream->last_fid ^= UVC_STREAM_FID;
c0efd232
LP
752 }
753}
754
2c2d264b
LP
755/* Video payload encoding is handled by uvc_video_encode_header() and
756 * uvc_video_encode_data(). Only bulk transfers are currently supported.
757 *
758 * uvc_video_encode_header is called at the start of a payload. It adds header
759 * data to the transfer buffer and returns the header size. As the only known
760 * UVC output device transfers a whole frame in a single payload, the EOF bit
761 * is always set in the header.
762 *
763 * uvc_video_encode_data is called for every URB and copies the data from the
764 * video buffer to the transfer buffer.
765 */
35f02a68 766static int uvc_video_encode_header(struct uvc_streaming *stream,
ff924203
LP
767 struct uvc_buffer *buf, __u8 *data, int len)
768{
769 data[0] = 2; /* Header length */
770 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
35f02a68 771 | (stream->last_fid & UVC_STREAM_FID);
ff924203
LP
772 return 2;
773}
774
35f02a68 775static int uvc_video_encode_data(struct uvc_streaming *stream,
ff924203
LP
776 struct uvc_buffer *buf, __u8 *data, int len)
777{
35f02a68 778 struct uvc_video_queue *queue = &stream->queue;
ff924203
LP
779 unsigned int nbytes;
780 void *mem;
781
782 /* Copy video data to the URB buffer. */
3d95e932
LP
783 mem = buf->mem + queue->buf_used;
784 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
35f02a68 785 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
ff924203
LP
786 nbytes);
787 memcpy(data, mem, nbytes);
788
789 queue->buf_used += nbytes;
790
791 return nbytes;
792}
793
c0efd232
LP
794/* ------------------------------------------------------------------------
795 * URB handling
796 */
797
798/*
799 * Completion handler for video URBs.
800 */
35f02a68
LP
801static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
802 struct uvc_buffer *buf)
c0efd232
LP
803{
804 u8 *mem;
805 int ret, i;
806
807 for (i = 0; i < urb->number_of_packets; ++i) {
808 if (urb->iso_frame_desc[i].status < 0) {
809 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
810 "lost (%d).\n", urb->iso_frame_desc[i].status);
9bde9f26
LP
811 /* Mark the buffer as faulty. */
812 if (buf != NULL)
813 buf->error = 1;
c0efd232
LP
814 continue;
815 }
816
817 /* Decode the payload header. */
818 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
819 do {
35f02a68 820 ret = uvc_video_decode_start(stream, buf, mem,
c0efd232
LP
821 urb->iso_frame_desc[i].actual_length);
822 if (ret == -EAGAIN)
35f02a68
LP
823 buf = uvc_queue_next_buffer(&stream->queue,
824 buf);
c0efd232
LP
825 } while (ret == -EAGAIN);
826
827 if (ret < 0)
828 continue;
829
830 /* Decode the payload data. */
35f02a68 831 uvc_video_decode_data(stream, buf, mem + ret,
c0efd232
LP
832 urb->iso_frame_desc[i].actual_length - ret);
833
834 /* Process the header again. */
35f02a68 835 uvc_video_decode_end(stream, buf, mem,
08ebd003 836 urb->iso_frame_desc[i].actual_length);
c0efd232 837
9bde9f26 838 if (buf->state == UVC_BUF_STATE_READY) {
3d95e932 839 if (buf->length != buf->bytesused &&
9bde9f26
LP
840 !(stream->cur_format->flags &
841 UVC_FMT_FLAG_COMPRESSED))
842 buf->error = 1;
843
35f02a68 844 buf = uvc_queue_next_buffer(&stream->queue, buf);
9bde9f26 845 }
c0efd232
LP
846 }
847}
848
35f02a68
LP
849static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
850 struct uvc_buffer *buf)
c0efd232
LP
851{
852 u8 *mem;
853 int len, ret;
854
c90e7779
LP
855 if (urb->actual_length == 0)
856 return;
857
c0efd232
LP
858 mem = urb->transfer_buffer;
859 len = urb->actual_length;
35f02a68 860 stream->bulk.payload_size += len;
c0efd232
LP
861
862 /* If the URB is the first of its payload, decode and save the
863 * header.
864 */
35f02a68 865 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
c0efd232 866 do {
35f02a68 867 ret = uvc_video_decode_start(stream, buf, mem, len);
c0efd232 868 if (ret == -EAGAIN)
35f02a68
LP
869 buf = uvc_queue_next_buffer(&stream->queue,
870 buf);
c0efd232
LP
871 } while (ret == -EAGAIN);
872
25985edc 873 /* If an error occurred skip the rest of the payload. */
c0efd232 874 if (ret < 0 || buf == NULL) {
35f02a68 875 stream->bulk.skip_payload = 1;
f8dd4af6 876 } else {
35f02a68
LP
877 memcpy(stream->bulk.header, mem, ret);
878 stream->bulk.header_size = ret;
c0efd232 879
f8dd4af6
LP
880 mem += ret;
881 len -= ret;
882 }
c0efd232
LP
883 }
884
885 /* The buffer queue might have been cancelled while a bulk transfer
886 * was in progress, so we can reach here with buf equal to NULL. Make
887 * sure buf is never dereferenced if NULL.
888 */
889
890 /* Process video data. */
35f02a68
LP
891 if (!stream->bulk.skip_payload && buf != NULL)
892 uvc_video_decode_data(stream, buf, mem, len);
c0efd232
LP
893
894 /* Detect the payload end by a URB smaller than the maximum size (or
895 * a payload size equal to the maximum) and process the header again.
896 */
897 if (urb->actual_length < urb->transfer_buffer_length ||
35f02a68
LP
898 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
899 if (!stream->bulk.skip_payload && buf != NULL) {
900 uvc_video_decode_end(stream, buf, stream->bulk.header,
901 stream->bulk.payload_size);
d7c0d439 902 if (buf->state == UVC_BUF_STATE_READY)
35f02a68
LP
903 buf = uvc_queue_next_buffer(&stream->queue,
904 buf);
c0efd232
LP
905 }
906
35f02a68
LP
907 stream->bulk.header_size = 0;
908 stream->bulk.skip_payload = 0;
909 stream->bulk.payload_size = 0;
c0efd232
LP
910 }
911}
912
35f02a68
LP
913static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
914 struct uvc_buffer *buf)
ff924203
LP
915{
916 u8 *mem = urb->transfer_buffer;
35f02a68 917 int len = stream->urb_size, ret;
ff924203
LP
918
919 if (buf == NULL) {
920 urb->transfer_buffer_length = 0;
921 return;
922 }
923
924 /* If the URB is the first of its payload, add the header. */
35f02a68
LP
925 if (stream->bulk.header_size == 0) {
926 ret = uvc_video_encode_header(stream, buf, mem, len);
927 stream->bulk.header_size = ret;
928 stream->bulk.payload_size += ret;
ff924203
LP
929 mem += ret;
930 len -= ret;
931 }
932
933 /* Process video data. */
35f02a68 934 ret = uvc_video_encode_data(stream, buf, mem, len);
ff924203 935
35f02a68 936 stream->bulk.payload_size += ret;
ff924203
LP
937 len -= ret;
938
3d95e932 939 if (buf->bytesused == stream->queue.buf_used ||
35f02a68 940 stream->bulk.payload_size == stream->bulk.max_payload_size) {
3d95e932 941 if (buf->bytesused == stream->queue.buf_used) {
35f02a68 942 stream->queue.buf_used = 0;
d7c0d439 943 buf->state = UVC_BUF_STATE_READY;
6998b6fb 944 buf->buf.v4l2_buf.sequence = ++stream->sequence;
35f02a68
LP
945 uvc_queue_next_buffer(&stream->queue, buf);
946 stream->last_fid ^= UVC_STREAM_FID;
ff924203
LP
947 }
948
35f02a68
LP
949 stream->bulk.header_size = 0;
950 stream->bulk.payload_size = 0;
ff924203
LP
951 }
952
35f02a68 953 urb->transfer_buffer_length = stream->urb_size - len;
ff924203
LP
954}
955
c0efd232
LP
956static void uvc_video_complete(struct urb *urb)
957{
35f02a68
LP
958 struct uvc_streaming *stream = urb->context;
959 struct uvc_video_queue *queue = &stream->queue;
c0efd232
LP
960 struct uvc_buffer *buf = NULL;
961 unsigned long flags;
962 int ret;
963
964 switch (urb->status) {
965 case 0:
966 break;
967
968 default:
969 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
970 "completion handler.\n", urb->status);
971
972 case -ENOENT: /* usb_kill_urb() called. */
35f02a68 973 if (stream->frozen)
c0efd232
LP
974 return;
975
976 case -ECONNRESET: /* usb_unlink_urb() called. */
977 case -ESHUTDOWN: /* The endpoint is being disabled. */
978 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
979 return;
980 }
981
982 spin_lock_irqsave(&queue->irqlock, flags);
983 if (!list_empty(&queue->irqqueue))
984 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
985 queue);
986 spin_unlock_irqrestore(&queue->irqlock, flags);
987
35f02a68 988 stream->decode(urb, stream, buf);
c0efd232
LP
989
990 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
991 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
992 ret);
993 }
994}
995
e01117c8
LP
996/*
997 * Free transfer buffers.
998 */
35f02a68 999static void uvc_free_urb_buffers(struct uvc_streaming *stream)
e01117c8
LP
1000{
1001 unsigned int i;
1002
1003 for (i = 0; i < UVC_URBS; ++i) {
35f02a68 1004 if (stream->urb_buffer[i]) {
3e0ac671 1005#ifndef CONFIG_DMA_NONCOHERENT
997ea58e 1006 usb_free_coherent(stream->dev->udev, stream->urb_size,
35f02a68 1007 stream->urb_buffer[i], stream->urb_dma[i]);
3e0ac671
AC
1008#else
1009 kfree(stream->urb_buffer[i]);
1010#endif
35f02a68 1011 stream->urb_buffer[i] = NULL;
e01117c8
LP
1012 }
1013 }
1014
35f02a68 1015 stream->urb_size = 0;
e01117c8
LP
1016}
1017
1018/*
1019 * Allocate transfer buffers. This function can be called with buffers
1020 * already allocated when resuming from suspend, in which case it will
1021 * return without touching the buffers.
1022 *
efdc8a95
LP
1023 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1024 * system is too low on memory try successively smaller numbers of packets
1025 * until allocation succeeds.
1026 *
1027 * Return the number of allocated packets on success or 0 when out of memory.
e01117c8 1028 */
35f02a68 1029static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
efdc8a95 1030 unsigned int size, unsigned int psize, gfp_t gfp_flags)
e01117c8 1031{
efdc8a95 1032 unsigned int npackets;
e01117c8
LP
1033 unsigned int i;
1034
1035 /* Buffers are already allocated, bail out. */
35f02a68
LP
1036 if (stream->urb_size)
1037 return stream->urb_size / psize;
e01117c8 1038
efdc8a95 1039 /* Compute the number of packets. Bulk endpoints might transfer UVC
25985edc 1040 * payloads across multiple URBs.
efdc8a95
LP
1041 */
1042 npackets = DIV_ROUND_UP(size, psize);
1043 if (npackets > UVC_MAX_PACKETS)
1044 npackets = UVC_MAX_PACKETS;
1045
1046 /* Retry allocations until one succeed. */
1047 for (; npackets > 1; npackets /= 2) {
1048 for (i = 0; i < UVC_URBS; ++i) {
fd1b6bbb 1049 stream->urb_size = psize * npackets;
3e0ac671 1050#ifndef CONFIG_DMA_NONCOHERENT
997ea58e 1051 stream->urb_buffer[i] = usb_alloc_coherent(
fd1b6bbb 1052 stream->dev->udev, stream->urb_size,
35f02a68 1053 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
3e0ac671
AC
1054#else
1055 stream->urb_buffer[i] =
1056 kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1057#endif
35f02a68
LP
1058 if (!stream->urb_buffer[i]) {
1059 uvc_free_urb_buffers(stream);
efdc8a95
LP
1060 break;
1061 }
1062 }
1063
1064 if (i == UVC_URBS) {
663a4192
LP
1065 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1066 "of %ux%u bytes each.\n", UVC_URBS, npackets,
1067 psize);
efdc8a95 1068 return npackets;
e01117c8
LP
1069 }
1070 }
1071
663a4192
LP
1072 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1073 "per packet).\n", psize);
e01117c8
LP
1074 return 0;
1075}
1076
c0efd232
LP
1077/*
1078 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1079 */
35f02a68 1080static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
c0efd232
LP
1081{
1082 struct urb *urb;
1083 unsigned int i;
1084
7bc5edb0
OR
1085 uvc_video_stats_stop(stream);
1086
c0efd232 1087 for (i = 0; i < UVC_URBS; ++i) {
35f02a68
LP
1088 urb = stream->urb[i];
1089 if (urb == NULL)
c0efd232
LP
1090 continue;
1091
1092 usb_kill_urb(urb);
c0efd232 1093 usb_free_urb(urb);
35f02a68 1094 stream->urb[i] = NULL;
c0efd232 1095 }
e01117c8
LP
1096
1097 if (free_buffers)
35f02a68 1098 uvc_free_urb_buffers(stream);
c0efd232
LP
1099}
1100
1101/*
1102 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1103 * is given by the endpoint.
1104 */
35f02a68 1105static int uvc_init_video_isoc(struct uvc_streaming *stream,
29135878 1106 struct usb_host_endpoint *ep, gfp_t gfp_flags)
c0efd232
LP
1107{
1108 struct urb *urb;
1109 unsigned int npackets, i, j;
efdc8a95
LP
1110 u16 psize;
1111 u32 size;
c0efd232 1112
c0efd232
LP
1113 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
1114 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
35f02a68 1115 size = stream->ctrl.dwMaxVideoFrameSize;
c0efd232 1116
35f02a68 1117 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
efdc8a95
LP
1118 if (npackets == 0)
1119 return -ENOMEM;
c0efd232
LP
1120
1121 size = npackets * psize;
1122
1123 for (i = 0; i < UVC_URBS; ++i) {
29135878 1124 urb = usb_alloc_urb(npackets, gfp_flags);
c0efd232 1125 if (urb == NULL) {
35f02a68 1126 uvc_uninit_video(stream, 1);
c0efd232
LP
1127 return -ENOMEM;
1128 }
1129
35f02a68
LP
1130 urb->dev = stream->dev->udev;
1131 urb->context = stream;
1132 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
c0efd232 1133 ep->desc.bEndpointAddress);
3e0ac671 1134#ifndef CONFIG_DMA_NONCOHERENT
c0efd232 1135 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
3e0ac671
AC
1136 urb->transfer_dma = stream->urb_dma[i];
1137#else
1138 urb->transfer_flags = URB_ISO_ASAP;
1139#endif
c0efd232 1140 urb->interval = ep->desc.bInterval;
35f02a68 1141 urb->transfer_buffer = stream->urb_buffer[i];
c0efd232
LP
1142 urb->complete = uvc_video_complete;
1143 urb->number_of_packets = npackets;
1144 urb->transfer_buffer_length = size;
1145
1146 for (j = 0; j < npackets; ++j) {
1147 urb->iso_frame_desc[j].offset = j * psize;
1148 urb->iso_frame_desc[j].length = psize;
1149 }
1150
35f02a68 1151 stream->urb[i] = urb;
c0efd232
LP
1152 }
1153
1154 return 0;
1155}
1156
1157/*
1158 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1159 * given by the endpoint.
1160 */
35f02a68 1161static int uvc_init_video_bulk(struct uvc_streaming *stream,
29135878 1162 struct usb_host_endpoint *ep, gfp_t gfp_flags)
c0efd232
LP
1163{
1164 struct urb *urb;
efdc8a95
LP
1165 unsigned int npackets, pipe, i;
1166 u16 psize;
1167 u32 size;
1168
c0efd232 1169 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
35f02a68
LP
1170 size = stream->ctrl.dwMaxPayloadTransferSize;
1171 stream->bulk.max_payload_size = size;
c0efd232 1172
35f02a68 1173 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
efdc8a95 1174 if (npackets == 0)
e01117c8
LP
1175 return -ENOMEM;
1176
efdc8a95
LP
1177 size = npackets * psize;
1178
ff924203 1179 if (usb_endpoint_dir_in(&ep->desc))
35f02a68 1180 pipe = usb_rcvbulkpipe(stream->dev->udev,
ff924203
LP
1181 ep->desc.bEndpointAddress);
1182 else
35f02a68 1183 pipe = usb_sndbulkpipe(stream->dev->udev,
ff924203
LP
1184 ep->desc.bEndpointAddress);
1185
35f02a68 1186 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
ff924203 1187 size = 0;
c0efd232
LP
1188
1189 for (i = 0; i < UVC_URBS; ++i) {
29135878 1190 urb = usb_alloc_urb(0, gfp_flags);
c0efd232 1191 if (urb == NULL) {
35f02a68 1192 uvc_uninit_video(stream, 1);
c0efd232
LP
1193 return -ENOMEM;
1194 }
1195
35f02a68
LP
1196 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1197 stream->urb_buffer[i], size, uvc_video_complete,
1198 stream);
3e0ac671 1199#ifndef CONFIG_DMA_NONCOHERENT
c0efd232 1200 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
35f02a68 1201 urb->transfer_dma = stream->urb_dma[i];
3e0ac671 1202#endif
c0efd232 1203
35f02a68 1204 stream->urb[i] = urb;
c0efd232
LP
1205 }
1206
1207 return 0;
1208}
1209
1210/*
1211 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1212 */
35f02a68 1213static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
c0efd232 1214{
35f02a68 1215 struct usb_interface *intf = stream->intf;
2c4d9de8
LP
1216 struct usb_host_endpoint *ep;
1217 unsigned int i;
c0efd232
LP
1218 int ret;
1219
650b95fe 1220 stream->sequence = -1;
35f02a68
LP
1221 stream->last_fid = -1;
1222 stream->bulk.header_size = 0;
1223 stream->bulk.skip_payload = 0;
1224 stream->bulk.payload_size = 0;
c0efd232 1225
7bc5edb0
OR
1226 uvc_video_stats_start(stream);
1227
c0efd232 1228 if (intf->num_altsetting > 1) {
2c4d9de8
LP
1229 struct usb_host_endpoint *best_ep = NULL;
1230 unsigned int best_psize = 3 * 1024;
1231 unsigned int bandwidth;
1232 unsigned int uninitialized_var(altsetting);
1233 int intfnum = stream->intfnum;
1234
c0efd232 1235 /* Isochronous endpoint, select the alternate setting. */
35f02a68 1236 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
c0efd232
LP
1237
1238 if (bandwidth == 0) {
663a4192
LP
1239 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1240 "bandwidth, defaulting to lowest.\n");
c0efd232 1241 bandwidth = 1;
663a4192
LP
1242 } else {
1243 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1244 "B/frame bandwidth.\n", bandwidth);
c0efd232
LP
1245 }
1246
1247 for (i = 0; i < intf->num_altsetting; ++i) {
2c4d9de8
LP
1248 struct usb_host_interface *alts;
1249 unsigned int psize;
1250
c0efd232
LP
1251 alts = &intf->altsetting[i];
1252 ep = uvc_find_endpoint(alts,
35f02a68 1253 stream->header.bEndpointAddress);
c0efd232
LP
1254 if (ep == NULL)
1255 continue;
1256
1257 /* Check if the bandwidth is high enough. */
1258 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
1259 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
2c4d9de8
LP
1260 if (psize >= bandwidth && psize <= best_psize) {
1261 altsetting = i;
1262 best_psize = psize;
1263 best_ep = ep;
1264 }
c0efd232
LP
1265 }
1266
2c4d9de8 1267 if (best_ep == NULL) {
663a4192
LP
1268 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1269 "for requested bandwidth.\n");
c0efd232 1270 return -EIO;
663a4192 1271 }
c0efd232 1272
2c4d9de8
LP
1273 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1274 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1275
1276 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
35f02a68 1277 if (ret < 0)
c0efd232
LP
1278 return ret;
1279
2c4d9de8 1280 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
c0efd232
LP
1281 } else {
1282 /* Bulk endpoint, proceed to URB initialization. */
1283 ep = uvc_find_endpoint(&intf->altsetting[0],
35f02a68 1284 stream->header.bEndpointAddress);
c0efd232
LP
1285 if (ep == NULL)
1286 return -EIO;
1287
35f02a68 1288 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
c0efd232
LP
1289 }
1290
1291 if (ret < 0)
1292 return ret;
1293
1294 /* Submit the URBs. */
1295 for (i = 0; i < UVC_URBS; ++i) {
35f02a68
LP
1296 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1297 if (ret < 0) {
c0efd232
LP
1298 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1299 "(%d).\n", i, ret);
35f02a68 1300 uvc_uninit_video(stream, 1);
c0efd232
LP
1301 return ret;
1302 }
1303 }
1304
1305 return 0;
1306}
1307
1308/* --------------------------------------------------------------------------
1309 * Suspend/resume
1310 */
1311
1312/*
1313 * Stop streaming without disabling the video queue.
1314 *
1315 * To let userspace applications resume without trouble, we must not touch the
1316 * video buffers in any way. We mark the device as frozen to make sure the URB
1317 * completion handler won't try to cancel the queue when we kill the URBs.
1318 */
35f02a68 1319int uvc_video_suspend(struct uvc_streaming *stream)
c0efd232 1320{
35f02a68 1321 if (!uvc_queue_streaming(&stream->queue))
c0efd232
LP
1322 return 0;
1323
35f02a68
LP
1324 stream->frozen = 1;
1325 uvc_uninit_video(stream, 0);
1326 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
c0efd232
LP
1327 return 0;
1328}
1329
1330/*
2c2d264b 1331 * Reconfigure the video interface and restart streaming if it was enabled
c0efd232
LP
1332 * before suspend.
1333 *
1334 * If an error occurs, disable the video queue. This will wake all pending
1335 * buffers, making sure userspace applications are notified of the problem
1336 * instead of waiting forever.
1337 */
d59a7b1d 1338int uvc_video_resume(struct uvc_streaming *stream, int reset)
c0efd232
LP
1339{
1340 int ret;
1341
d59a7b1d
ML
1342 /* If the bus has been reset on resume, set the alternate setting to 0.
1343 * This should be the default value, but some devices crash or otherwise
1344 * misbehave if they don't receive a SET_INTERFACE request before any
1345 * other video control request.
1346 */
1347 if (reset)
1348 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1349
35f02a68 1350 stream->frozen = 0;
c0efd232 1351
35f02a68
LP
1352 ret = uvc_commit_video(stream, &stream->ctrl);
1353 if (ret < 0) {
1354 uvc_queue_enable(&stream->queue, 0);
c0efd232
LP
1355 return ret;
1356 }
1357
35f02a68 1358 if (!uvc_queue_streaming(&stream->queue))
c0efd232
LP
1359 return 0;
1360
35f02a68
LP
1361 ret = uvc_init_video(stream, GFP_NOIO);
1362 if (ret < 0)
1363 uvc_queue_enable(&stream->queue, 0);
c0efd232
LP
1364
1365 return ret;
1366}
1367
1368/* ------------------------------------------------------------------------
1369 * Video device
1370 */
1371
1372/*
2c2d264b
LP
1373 * Initialize the UVC video device by switching to alternate setting 0 and
1374 * retrieve the default format.
c0efd232
LP
1375 *
1376 * Some cameras (namely the Fuji Finepix) set the format and frame
1377 * indexes to zero. The UVC standard doesn't clearly make this a spec
1378 * violation, so try to silently fix the values if possible.
1379 *
1380 * This function is called before registering the device with V4L.
1381 */
35f02a68 1382int uvc_video_init(struct uvc_streaming *stream)
c0efd232 1383{
35f02a68 1384 struct uvc_streaming_control *probe = &stream->ctrl;
c0efd232
LP
1385 struct uvc_format *format = NULL;
1386 struct uvc_frame *frame = NULL;
1387 unsigned int i;
1388 int ret;
1389
35f02a68 1390 if (stream->nformats == 0) {
c0efd232
LP
1391 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1392 return -EINVAL;
1393 }
1394
35f02a68
LP
1395 atomic_set(&stream->active, 0);
1396
1397 /* Initialize the video buffers queue. */
9bde9f26 1398 uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
35f02a68 1399
c0efd232
LP
1400 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1401 * Cam (and possibly other devices) crash or otherwise misbehave if
1402 * they don't receive a SET_INTERFACE request before any other video
1403 * control request.
1404 */
35f02a68 1405 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
c0efd232 1406
72362422
LP
1407 /* Set the streaming probe control with default streaming parameters
1408 * retrieved from the device. Webcams that don't suport GET_DEF
1409 * requests on the probe control will just keep their current streaming
1410 * parameters.
c0efd232 1411 */
35f02a68
LP
1412 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1413 uvc_set_video_ctrl(stream, probe, 1);
72362422
LP
1414
1415 /* Initialize the streaming parameters with the probe control current
1416 * value. This makes sure SET_CUR requests on the streaming commit
1417 * control will always use values retrieved from a successful GET_CUR
1418 * request on the probe control, as required by the UVC specification.
1419 */
35f02a68 1420 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
b482d923 1421 if (ret < 0)
c0efd232
LP
1422 return ret;
1423
1424 /* Check if the default format descriptor exists. Use the first
1425 * available format otherwise.
1426 */
35f02a68
LP
1427 for (i = stream->nformats; i > 0; --i) {
1428 format = &stream->format[i-1];
c0efd232
LP
1429 if (format->index == probe->bFormatIndex)
1430 break;
1431 }
1432
1433 if (format->nframes == 0) {
1434 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1435 "default format.\n");
1436 return -EINVAL;
1437 }
1438
1439 /* Zero bFrameIndex might be correct. Stream-based formats (including
1440 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1441 * descriptor with bFrameIndex set to zero. If the default frame
078f8947 1442 * descriptor is not found, use the first available frame.
c0efd232
LP
1443 */
1444 for (i = format->nframes; i > 0; --i) {
1445 frame = &format->frame[i-1];
1446 if (frame->bFrameIndex == probe->bFrameIndex)
1447 break;
1448 }
1449
c0efd232
LP
1450 probe->bFormatIndex = format->index;
1451 probe->bFrameIndex = frame->bFrameIndex;
c0efd232 1452
35f02a68
LP
1453 stream->cur_format = format;
1454 stream->cur_frame = frame;
c0efd232
LP
1455
1456 /* Select the video decoding function */
35f02a68
LP
1457 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1458 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1459 stream->decode = uvc_video_decode_isight;
1460 else if (stream->intf->num_altsetting > 1)
1461 stream->decode = uvc_video_decode_isoc;
ff924203 1462 else
35f02a68 1463 stream->decode = uvc_video_decode_bulk;
ff924203 1464 } else {
35f02a68
LP
1465 if (stream->intf->num_altsetting == 1)
1466 stream->decode = uvc_video_encode_bulk;
ff924203
LP
1467 else {
1468 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1469 "supported for video output devices.\n");
1470 return -EINVAL;
1471 }
1472 }
c0efd232
LP
1473
1474 return 0;
1475}
1476
1477/*
1478 * Enable or disable the video stream.
1479 */
35f02a68 1480int uvc_video_enable(struct uvc_streaming *stream, int enable)
c0efd232
LP
1481{
1482 int ret;
1483
1484 if (!enable) {
35f02a68
LP
1485 uvc_uninit_video(stream, 1);
1486 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1487 uvc_queue_enable(&stream->queue, 0);
c0efd232
LP
1488 return 0;
1489 }
1490
35f02a68
LP
1491 ret = uvc_queue_enable(&stream->queue, 1);
1492 if (ret < 0)
c0efd232
LP
1493 return ret;
1494
23867b25 1495 /* Commit the streaming parameters. */
35f02a68 1496 ret = uvc_commit_video(stream, &stream->ctrl);
aa122d42
SS
1497 if (ret < 0) {
1498 uvc_queue_enable(&stream->queue, 0);
23867b25 1499 return ret;
aa122d42 1500 }
23867b25 1501
24c3aae0
LP
1502 ret = uvc_init_video(stream, GFP_KERNEL);
1503 if (ret < 0) {
1504 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1505 uvc_queue_enable(&stream->queue, 0);
1506 }
f87086e3 1507
24c3aae0
LP
1508 return ret;
1509}