[media] uvcvideo: Extract video stream statistics
[firefly-linux-kernel-4.4.55.git] / drivers / media / video / uvc / uvc_video.c
1 /*
2  *      uvc_video.c  --  USB Video Class driver - Video handling
3  *
4  *      Copyright (C) 2005-2010
5  *          Laurent Pinchart (laurent.pinchart@ideasonboard.com)
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>
15 #include <linux/list.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18 #include <linux/usb.h>
19 #include <linux/videodev2.h>
20 #include <linux/vmalloc.h>
21 #include <linux/wait.h>
22 #include <linux/atomic.h>
23 #include <asm/unaligned.h>
24
25 #include <media/v4l2-common.h>
26
27 #include "uvcvideo.h"
28
29 /* ------------------------------------------------------------------------
30  * UVC Controls
31  */
32
33 static 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;
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
44         return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
45                         unit << 8 | intfnum, data, size, timeout);
46 }
47
48 static 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
72 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
73                         __u8 intfnum, __u8 cs, void *data, __u16 size)
74 {
75         int ret;
76
77         ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
78                                 UVC_CTRL_CONTROL_TIMEOUT);
79         if (ret != size) {
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);
83                 return -EIO;
84         }
85
86         return 0;
87 }
88
89 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
90         struct uvc_streaming_control *ctrl)
91 {
92         struct uvc_format *format = NULL;
93         struct uvc_frame *frame = NULL;
94         unsigned int i;
95
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         }
102
103         if (format == NULL)
104                 return;
105
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         }
112
113         if (frame == NULL)
114                 return;
115
116         if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
117              (ctrl->dwMaxVideoFrameSize == 0 &&
118               stream->dev->uvc_version < 0x0110))
119                 ctrl->dwMaxVideoFrameSize =
120                         frame->dwMaxVideoFrameBufferSize;
121
122         if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
123             stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
124             stream->intf->num_altsetting > 1) {
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;
141                 if (stream->dev->udev->speed == USB_SPEED_HIGH)
142                         bandwidth /= 8;
143                 bandwidth += 12;
144
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
154                 ctrl->dwMaxPayloadTransferSize = bandwidth;
155         }
156 }
157
158 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
159         struct uvc_streaming_control *ctrl, int probe, __u8 query)
160 {
161         __u8 *data;
162         __u16 size;
163         int ret;
164
165         size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
166         if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
167                         query == UVC_GET_DEF)
168                 return -EIO;
169
170         data = kmalloc(size, GFP_KERNEL);
171         if (data == NULL)
172                 return -ENOMEM;
173
174         ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
175                 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
176                 size, uvc_timeout_param);
177
178         if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
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                  */
183                 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
184                         "compliance - GET_MIN/MAX(PROBE) incorrectly "
185                         "supported. Enabling workaround.\n");
186                 memset(ctrl, 0, sizeof *ctrl);
187                 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
188                 ret = 0;
189                 goto out;
190         } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
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                  */
195                 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
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         }
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]);
217         ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
218         ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
219
220         if (size == 34) {
221                 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
222                 ctrl->bmFramingInfo = data[30];
223                 ctrl->bPreferedVersion = data[31];
224                 ctrl->bMinVersion = data[32];
225                 ctrl->bMaxVersion = data[33];
226         } else {
227                 ctrl->dwClockFrequency = stream->dev->clock_frequency;
228                 ctrl->bmFramingInfo = 0;
229                 ctrl->bPreferedVersion = 0;
230                 ctrl->bMinVersion = 0;
231                 ctrl->bMaxVersion = 0;
232         }
233
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.
237          */
238         uvc_fixup_video_ctrl(stream, ctrl);
239         ret = 0;
240
241 out:
242         kfree(data);
243         return ret;
244 }
245
246 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
247         struct uvc_streaming_control *ctrl, int probe)
248 {
249         __u8 *data;
250         __u16 size;
251         int ret;
252
253         size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
254         data = kzalloc(size, GFP_KERNEL);
255         if (data == NULL)
256                 return -ENOMEM;
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);
267         put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
268         put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
269
270         if (size == 34) {
271                 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
272                 data[30] = ctrl->bmFramingInfo;
273                 data[31] = ctrl->bPreferedVersion;
274                 data[32] = ctrl->bMinVersion;
275                 data[33] = ctrl->bMaxVersion;
276         }
277
278         ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
279                 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
280                 size, uvc_timeout_param);
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         }
287
288         kfree(data);
289         return ret;
290 }
291
292 int uvc_probe_video(struct uvc_streaming *stream,
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
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          */
307         ret = uvc_set_video_ctrl(stream, probe, 1);
308         if (ret < 0)
309                 goto done;
310
311         /* Get the minimum and maximum values for compression settings. */
312         if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
313                 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
314                 if (ret < 0)
315                         goto done;
316                 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
317                 if (ret < 0)
318                         goto done;
319
320                 probe->wCompQuality = probe_max.wCompQuality;
321         }
322
323         for (i = 0; i < 2; ++i) {
324                 ret = uvc_set_video_ctrl(stream, probe, 1);
325                 if (ret < 0)
326                         goto done;
327                 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
328                 if (ret < 0)
329                         goto done;
330
331                 if (stream->intf->num_altsetting == 1)
332                         break;
333
334                 bandwidth = probe->dwMaxPayloadTransferSize;
335                 if (bandwidth <= stream->maxpsize)
336                         break;
337
338                 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
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
350 done:
351         return ret;
352 }
353
354 static int uvc_commit_video(struct uvc_streaming *stream,
355                             struct uvc_streaming_control *probe)
356 {
357         return uvc_set_video_ctrl(stream, probe, 0);
358 }
359
360 /* ------------------------------------------------------------------------
361  * Stream statistics
362  */
363
364 static void uvc_video_stats_decode(struct uvc_streaming *stream,
365                 const __u8 *data, int len)
366 {
367         unsigned int header_size;
368
369         if (stream->stats.stream.nb_frames == 0 &&
370             stream->stats.frame.nb_packets == 0)
371                 ktime_get_ts(&stream->stats.stream.start_ts);
372
373         switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
374         case UVC_STREAM_PTS | UVC_STREAM_SCR:
375                 header_size = 12;
376                 break;
377         case UVC_STREAM_PTS:
378                 header_size = 6;
379                 break;
380         case UVC_STREAM_SCR:
381                 header_size = 8;
382                 break;
383         default:
384                 header_size = 2;
385                 break;
386         }
387
388         /* Check for invalid headers. */
389         if (len < header_size || data[0] < header_size) {
390                 stream->stats.frame.nb_invalid++;
391                 return;
392         }
393
394         /* Record the first non-empty packet number. */
395         if (stream->stats.frame.size == 0 && len > header_size)
396                 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
397
398         /* Update the frame size. */
399         stream->stats.frame.size += len - header_size;
400
401         /* Update the packets counters. */
402         stream->stats.frame.nb_packets++;
403         if (len > header_size)
404                 stream->stats.frame.nb_empty++;
405
406         if (data[1] & UVC_STREAM_ERR)
407                 stream->stats.frame.nb_errors++;
408 }
409
410 static void uvc_video_stats_update(struct uvc_streaming *stream)
411 {
412         struct uvc_stats_frame *frame = &stream->stats.frame;
413
414         uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets\n",
415                   stream->sequence, frame->first_data,
416                   frame->nb_packets - frame->nb_empty, frame->nb_packets);
417
418         stream->stats.stream.nb_frames++;
419         stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
420         stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
421         stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
422         stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
423
424         memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
425 }
426
427 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
428                             size_t size)
429 {
430         size_t count = 0;
431
432         count += scnprintf(buf + count, size - count,
433                            "frames:  %u\npackets: %u\nempty:   %u\n"
434                            "errors:  %u\ninvalid: %u\n",
435                            stream->stats.stream.nb_frames,
436                            stream->stats.stream.nb_packets,
437                            stream->stats.stream.nb_empty,
438                            stream->stats.stream.nb_errors,
439                            stream->stats.stream.nb_invalid);
440
441         return count;
442 }
443
444 static void uvc_video_stats_start(struct uvc_streaming *stream)
445 {
446         memset(&stream->stats, 0, sizeof(stream->stats));
447 }
448
449 static void uvc_video_stats_stop(struct uvc_streaming *stream)
450 {
451         ktime_get_ts(&stream->stats.stream.stop_ts);
452 }
453
454 /* ------------------------------------------------------------------------
455  * Video codecs
456  */
457
458 /* Video payload decoding is handled by uvc_video_decode_start(),
459  * uvc_video_decode_data() and uvc_video_decode_end().
460  *
461  * uvc_video_decode_start is called with URB data at the start of a bulk or
462  * isochronous payload. It processes header data and returns the header size
463  * in bytes if successful. If an error occurs, it returns a negative error
464  * code. The following error codes have special meanings.
465  *
466  * - EAGAIN informs the caller that the current video buffer should be marked
467  *   as done, and that the function should be called again with the same data
468  *   and a new video buffer. This is used when end of frame conditions can be
469  *   reliably detected at the beginning of the next frame only.
470  *
471  * If an error other than -EAGAIN is returned, the caller will drop the current
472  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
473  * made until the next payload. -ENODATA can be used to drop the current
474  * payload if no other error code is appropriate.
475  *
476  * uvc_video_decode_data is called for every URB with URB data. It copies the
477  * data to the video buffer.
478  *
479  * uvc_video_decode_end is called with header data at the end of a bulk or
480  * isochronous payload. It performs any additional header data processing and
481  * returns 0 or a negative error code if an error occurred. As header data have
482  * already been processed by uvc_video_decode_start, this functions isn't
483  * required to perform sanity checks a second time.
484  *
485  * For isochronous transfers where a payload is always transferred in a single
486  * URB, the three functions will be called in a row.
487  *
488  * To let the decoder process header data and update its internal state even
489  * when no video buffer is available, uvc_video_decode_start must be prepared
490  * to be called with a NULL buf parameter. uvc_video_decode_data and
491  * uvc_video_decode_end will never be called with a NULL buffer.
492  */
493 static int uvc_video_decode_start(struct uvc_streaming *stream,
494                 struct uvc_buffer *buf, const __u8 *data, int len)
495 {
496         __u8 fid;
497
498         /* Sanity checks:
499          * - packet must be at least 2 bytes long
500          * - bHeaderLength value must be at least 2 bytes (see above)
501          * - bHeaderLength value can't be larger than the packet size.
502          */
503         if (len < 2 || data[0] < 2 || data[0] > len) {
504                 stream->stats.frame.nb_invalid++;
505                 return -EINVAL;
506         }
507
508         fid = data[1] & UVC_STREAM_FID;
509
510         /* Increase the sequence number regardless of any buffer states, so
511          * that discontinuous sequence numbers always indicate lost frames.
512          */
513         if (stream->last_fid != fid) {
514                 stream->sequence++;
515                 if (stream->sequence)
516                         uvc_video_stats_update(stream);
517         }
518
519         uvc_video_stats_decode(stream, data, len);
520
521         /* Store the payload FID bit and return immediately when the buffer is
522          * NULL.
523          */
524         if (buf == NULL) {
525                 stream->last_fid = fid;
526                 return -ENODATA;
527         }
528
529         /* Mark the buffer as bad if the error bit is set. */
530         if (data[1] & UVC_STREAM_ERR) {
531                 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
532                           "set).\n");
533                 buf->error = 1;
534         }
535
536         /* Synchronize to the input stream by waiting for the FID bit to be
537          * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
538          * stream->last_fid is initialized to -1, so the first isochronous
539          * frame will always be in sync.
540          *
541          * If the device doesn't toggle the FID bit, invert stream->last_fid
542          * when the EOF bit is set to force synchronisation on the next packet.
543          */
544         if (buf->state != UVC_BUF_STATE_ACTIVE) {
545                 struct timespec ts;
546
547                 if (fid == stream->last_fid) {
548                         uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
549                                 "sync).\n");
550                         if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
551                             (data[1] & UVC_STREAM_EOF))
552                                 stream->last_fid ^= UVC_STREAM_FID;
553                         return -ENODATA;
554                 }
555
556                 if (uvc_clock_param == CLOCK_MONOTONIC)
557                         ktime_get_ts(&ts);
558                 else
559                         ktime_get_real_ts(&ts);
560
561                 buf->buf.v4l2_buf.sequence = stream->sequence;
562                 buf->buf.v4l2_buf.timestamp.tv_sec = ts.tv_sec;
563                 buf->buf.v4l2_buf.timestamp.tv_usec =
564                         ts.tv_nsec / NSEC_PER_USEC;
565
566                 /* TODO: Handle PTS and SCR. */
567                 buf->state = UVC_BUF_STATE_ACTIVE;
568         }
569
570         /* Mark the buffer as done if we're at the beginning of a new frame.
571          * End of frame detection is better implemented by checking the EOF
572          * bit (FID bit toggling is delayed by one frame compared to the EOF
573          * bit), but some devices don't set the bit at end of frame (and the
574          * last payload can be lost anyway). We thus must check if the FID has
575          * been toggled.
576          *
577          * stream->last_fid is initialized to -1, so the first isochronous
578          * frame will never trigger an end of frame detection.
579          *
580          * Empty buffers (bytesused == 0) don't trigger end of frame detection
581          * as it doesn't make sense to return an empty buffer. This also
582          * avoids detecting end of frame conditions at FID toggling if the
583          * previous payload had the EOF bit set.
584          */
585         if (fid != stream->last_fid && buf->bytesused != 0) {
586                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
587                                 "toggled).\n");
588                 buf->state = UVC_BUF_STATE_READY;
589                 return -EAGAIN;
590         }
591
592         stream->last_fid = fid;
593
594         return data[0];
595 }
596
597 static void uvc_video_decode_data(struct uvc_streaming *stream,
598                 struct uvc_buffer *buf, const __u8 *data, int len)
599 {
600         unsigned int maxlen, nbytes;
601         void *mem;
602
603         if (len <= 0)
604                 return;
605
606         /* Copy the video data to the buffer. */
607         maxlen = buf->length - buf->bytesused;
608         mem = buf->mem + buf->bytesused;
609         nbytes = min((unsigned int)len, maxlen);
610         memcpy(mem, data, nbytes);
611         buf->bytesused += nbytes;
612
613         /* Complete the current frame if the buffer size was exceeded. */
614         if (len > maxlen) {
615                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
616                 buf->state = UVC_BUF_STATE_READY;
617         }
618 }
619
620 static void uvc_video_decode_end(struct uvc_streaming *stream,
621                 struct uvc_buffer *buf, const __u8 *data, int len)
622 {
623         /* Mark the buffer as done if the EOF marker is set. */
624         if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
625                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
626                 if (data[0] == len)
627                         uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
628                 buf->state = UVC_BUF_STATE_READY;
629                 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
630                         stream->last_fid ^= UVC_STREAM_FID;
631         }
632 }
633
634 /* Video payload encoding is handled by uvc_video_encode_header() and
635  * uvc_video_encode_data(). Only bulk transfers are currently supported.
636  *
637  * uvc_video_encode_header is called at the start of a payload. It adds header
638  * data to the transfer buffer and returns the header size. As the only known
639  * UVC output device transfers a whole frame in a single payload, the EOF bit
640  * is always set in the header.
641  *
642  * uvc_video_encode_data is called for every URB and copies the data from the
643  * video buffer to the transfer buffer.
644  */
645 static int uvc_video_encode_header(struct uvc_streaming *stream,
646                 struct uvc_buffer *buf, __u8 *data, int len)
647 {
648         data[0] = 2;    /* Header length */
649         data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
650                 | (stream->last_fid & UVC_STREAM_FID);
651         return 2;
652 }
653
654 static int uvc_video_encode_data(struct uvc_streaming *stream,
655                 struct uvc_buffer *buf, __u8 *data, int len)
656 {
657         struct uvc_video_queue *queue = &stream->queue;
658         unsigned int nbytes;
659         void *mem;
660
661         /* Copy video data to the URB buffer. */
662         mem = buf->mem + queue->buf_used;
663         nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
664         nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
665                         nbytes);
666         memcpy(data, mem, nbytes);
667
668         queue->buf_used += nbytes;
669
670         return nbytes;
671 }
672
673 /* ------------------------------------------------------------------------
674  * URB handling
675  */
676
677 /*
678  * Completion handler for video URBs.
679  */
680 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
681         struct uvc_buffer *buf)
682 {
683         u8 *mem;
684         int ret, i;
685
686         for (i = 0; i < urb->number_of_packets; ++i) {
687                 if (urb->iso_frame_desc[i].status < 0) {
688                         uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
689                                 "lost (%d).\n", urb->iso_frame_desc[i].status);
690                         /* Mark the buffer as faulty. */
691                         if (buf != NULL)
692                                 buf->error = 1;
693                         continue;
694                 }
695
696                 /* Decode the payload header. */
697                 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
698                 do {
699                         ret = uvc_video_decode_start(stream, buf, mem,
700                                 urb->iso_frame_desc[i].actual_length);
701                         if (ret == -EAGAIN)
702                                 buf = uvc_queue_next_buffer(&stream->queue,
703                                                             buf);
704                 } while (ret == -EAGAIN);
705
706                 if (ret < 0)
707                         continue;
708
709                 /* Decode the payload data. */
710                 uvc_video_decode_data(stream, buf, mem + ret,
711                         urb->iso_frame_desc[i].actual_length - ret);
712
713                 /* Process the header again. */
714                 uvc_video_decode_end(stream, buf, mem,
715                         urb->iso_frame_desc[i].actual_length);
716
717                 if (buf->state == UVC_BUF_STATE_READY) {
718                         if (buf->length != buf->bytesused &&
719                             !(stream->cur_format->flags &
720                               UVC_FMT_FLAG_COMPRESSED))
721                                 buf->error = 1;
722
723                         buf = uvc_queue_next_buffer(&stream->queue, buf);
724                 }
725         }
726 }
727
728 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
729         struct uvc_buffer *buf)
730 {
731         u8 *mem;
732         int len, ret;
733
734         if (urb->actual_length == 0)
735                 return;
736
737         mem = urb->transfer_buffer;
738         len = urb->actual_length;
739         stream->bulk.payload_size += len;
740
741         /* If the URB is the first of its payload, decode and save the
742          * header.
743          */
744         if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
745                 do {
746                         ret = uvc_video_decode_start(stream, buf, mem, len);
747                         if (ret == -EAGAIN)
748                                 buf = uvc_queue_next_buffer(&stream->queue,
749                                                             buf);
750                 } while (ret == -EAGAIN);
751
752                 /* If an error occurred skip the rest of the payload. */
753                 if (ret < 0 || buf == NULL) {
754                         stream->bulk.skip_payload = 1;
755                 } else {
756                         memcpy(stream->bulk.header, mem, ret);
757                         stream->bulk.header_size = ret;
758
759                         mem += ret;
760                         len -= ret;
761                 }
762         }
763
764         /* The buffer queue might have been cancelled while a bulk transfer
765          * was in progress, so we can reach here with buf equal to NULL. Make
766          * sure buf is never dereferenced if NULL.
767          */
768
769         /* Process video data. */
770         if (!stream->bulk.skip_payload && buf != NULL)
771                 uvc_video_decode_data(stream, buf, mem, len);
772
773         /* Detect the payload end by a URB smaller than the maximum size (or
774          * a payload size equal to the maximum) and process the header again.
775          */
776         if (urb->actual_length < urb->transfer_buffer_length ||
777             stream->bulk.payload_size >= stream->bulk.max_payload_size) {
778                 if (!stream->bulk.skip_payload && buf != NULL) {
779                         uvc_video_decode_end(stream, buf, stream->bulk.header,
780                                 stream->bulk.payload_size);
781                         if (buf->state == UVC_BUF_STATE_READY)
782                                 buf = uvc_queue_next_buffer(&stream->queue,
783                                                             buf);
784                 }
785
786                 stream->bulk.header_size = 0;
787                 stream->bulk.skip_payload = 0;
788                 stream->bulk.payload_size = 0;
789         }
790 }
791
792 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
793         struct uvc_buffer *buf)
794 {
795         u8 *mem = urb->transfer_buffer;
796         int len = stream->urb_size, ret;
797
798         if (buf == NULL) {
799                 urb->transfer_buffer_length = 0;
800                 return;
801         }
802
803         /* If the URB is the first of its payload, add the header. */
804         if (stream->bulk.header_size == 0) {
805                 ret = uvc_video_encode_header(stream, buf, mem, len);
806                 stream->bulk.header_size = ret;
807                 stream->bulk.payload_size += ret;
808                 mem += ret;
809                 len -= ret;
810         }
811
812         /* Process video data. */
813         ret = uvc_video_encode_data(stream, buf, mem, len);
814
815         stream->bulk.payload_size += ret;
816         len -= ret;
817
818         if (buf->bytesused == stream->queue.buf_used ||
819             stream->bulk.payload_size == stream->bulk.max_payload_size) {
820                 if (buf->bytesused == stream->queue.buf_used) {
821                         stream->queue.buf_used = 0;
822                         buf->state = UVC_BUF_STATE_READY;
823                         buf->buf.v4l2_buf.sequence = ++stream->sequence;
824                         uvc_queue_next_buffer(&stream->queue, buf);
825                         stream->last_fid ^= UVC_STREAM_FID;
826                 }
827
828                 stream->bulk.header_size = 0;
829                 stream->bulk.payload_size = 0;
830         }
831
832         urb->transfer_buffer_length = stream->urb_size - len;
833 }
834
835 static void uvc_video_complete(struct urb *urb)
836 {
837         struct uvc_streaming *stream = urb->context;
838         struct uvc_video_queue *queue = &stream->queue;
839         struct uvc_buffer *buf = NULL;
840         unsigned long flags;
841         int ret;
842
843         switch (urb->status) {
844         case 0:
845                 break;
846
847         default:
848                 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
849                         "completion handler.\n", urb->status);
850
851         case -ENOENT:           /* usb_kill_urb() called. */
852                 if (stream->frozen)
853                         return;
854
855         case -ECONNRESET:       /* usb_unlink_urb() called. */
856         case -ESHUTDOWN:        /* The endpoint is being disabled. */
857                 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
858                 return;
859         }
860
861         spin_lock_irqsave(&queue->irqlock, flags);
862         if (!list_empty(&queue->irqqueue))
863                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
864                                        queue);
865         spin_unlock_irqrestore(&queue->irqlock, flags);
866
867         stream->decode(urb, stream, buf);
868
869         if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
870                 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
871                         ret);
872         }
873 }
874
875 /*
876  * Free transfer buffers.
877  */
878 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
879 {
880         unsigned int i;
881
882         for (i = 0; i < UVC_URBS; ++i) {
883                 if (stream->urb_buffer[i]) {
884 #ifndef CONFIG_DMA_NONCOHERENT
885                         usb_free_coherent(stream->dev->udev, stream->urb_size,
886                                 stream->urb_buffer[i], stream->urb_dma[i]);
887 #else
888                         kfree(stream->urb_buffer[i]);
889 #endif
890                         stream->urb_buffer[i] = NULL;
891                 }
892         }
893
894         stream->urb_size = 0;
895 }
896
897 /*
898  * Allocate transfer buffers. This function can be called with buffers
899  * already allocated when resuming from suspend, in which case it will
900  * return without touching the buffers.
901  *
902  * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
903  * system is too low on memory try successively smaller numbers of packets
904  * until allocation succeeds.
905  *
906  * Return the number of allocated packets on success or 0 when out of memory.
907  */
908 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
909         unsigned int size, unsigned int psize, gfp_t gfp_flags)
910 {
911         unsigned int npackets;
912         unsigned int i;
913
914         /* Buffers are already allocated, bail out. */
915         if (stream->urb_size)
916                 return stream->urb_size / psize;
917
918         /* Compute the number of packets. Bulk endpoints might transfer UVC
919          * payloads across multiple URBs.
920          */
921         npackets = DIV_ROUND_UP(size, psize);
922         if (npackets > UVC_MAX_PACKETS)
923                 npackets = UVC_MAX_PACKETS;
924
925         /* Retry allocations until one succeed. */
926         for (; npackets > 1; npackets /= 2) {
927                 for (i = 0; i < UVC_URBS; ++i) {
928                         stream->urb_size = psize * npackets;
929 #ifndef CONFIG_DMA_NONCOHERENT
930                         stream->urb_buffer[i] = usb_alloc_coherent(
931                                 stream->dev->udev, stream->urb_size,
932                                 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
933 #else
934                         stream->urb_buffer[i] =
935                             kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
936 #endif
937                         if (!stream->urb_buffer[i]) {
938                                 uvc_free_urb_buffers(stream);
939                                 break;
940                         }
941                 }
942
943                 if (i == UVC_URBS) {
944                         uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
945                                 "of %ux%u bytes each.\n", UVC_URBS, npackets,
946                                 psize);
947                         return npackets;
948                 }
949         }
950
951         uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
952                 "per packet).\n", psize);
953         return 0;
954 }
955
956 /*
957  * Uninitialize isochronous/bulk URBs and free transfer buffers.
958  */
959 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
960 {
961         struct urb *urb;
962         unsigned int i;
963
964         uvc_video_stats_stop(stream);
965
966         for (i = 0; i < UVC_URBS; ++i) {
967                 urb = stream->urb[i];
968                 if (urb == NULL)
969                         continue;
970
971                 usb_kill_urb(urb);
972                 usb_free_urb(urb);
973                 stream->urb[i] = NULL;
974         }
975
976         if (free_buffers)
977                 uvc_free_urb_buffers(stream);
978 }
979
980 /*
981  * Initialize isochronous URBs and allocate transfer buffers. The packet size
982  * is given by the endpoint.
983  */
984 static int uvc_init_video_isoc(struct uvc_streaming *stream,
985         struct usb_host_endpoint *ep, gfp_t gfp_flags)
986 {
987         struct urb *urb;
988         unsigned int npackets, i, j;
989         u16 psize;
990         u32 size;
991
992         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
993         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
994         size = stream->ctrl.dwMaxVideoFrameSize;
995
996         npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
997         if (npackets == 0)
998                 return -ENOMEM;
999
1000         size = npackets * psize;
1001
1002         for (i = 0; i < UVC_URBS; ++i) {
1003                 urb = usb_alloc_urb(npackets, gfp_flags);
1004                 if (urb == NULL) {
1005                         uvc_uninit_video(stream, 1);
1006                         return -ENOMEM;
1007                 }
1008
1009                 urb->dev = stream->dev->udev;
1010                 urb->context = stream;
1011                 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1012                                 ep->desc.bEndpointAddress);
1013 #ifndef CONFIG_DMA_NONCOHERENT
1014                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1015                 urb->transfer_dma = stream->urb_dma[i];
1016 #else
1017                 urb->transfer_flags = URB_ISO_ASAP;
1018 #endif
1019                 urb->interval = ep->desc.bInterval;
1020                 urb->transfer_buffer = stream->urb_buffer[i];
1021                 urb->complete = uvc_video_complete;
1022                 urb->number_of_packets = npackets;
1023                 urb->transfer_buffer_length = size;
1024
1025                 for (j = 0; j < npackets; ++j) {
1026                         urb->iso_frame_desc[j].offset = j * psize;
1027                         urb->iso_frame_desc[j].length = psize;
1028                 }
1029
1030                 stream->urb[i] = urb;
1031         }
1032
1033         return 0;
1034 }
1035
1036 /*
1037  * Initialize bulk URBs and allocate transfer buffers. The packet size is
1038  * given by the endpoint.
1039  */
1040 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1041         struct usb_host_endpoint *ep, gfp_t gfp_flags)
1042 {
1043         struct urb *urb;
1044         unsigned int npackets, pipe, i;
1045         u16 psize;
1046         u32 size;
1047
1048         psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
1049         size = stream->ctrl.dwMaxPayloadTransferSize;
1050         stream->bulk.max_payload_size = size;
1051
1052         npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1053         if (npackets == 0)
1054                 return -ENOMEM;
1055
1056         size = npackets * psize;
1057
1058         if (usb_endpoint_dir_in(&ep->desc))
1059                 pipe = usb_rcvbulkpipe(stream->dev->udev,
1060                                        ep->desc.bEndpointAddress);
1061         else
1062                 pipe = usb_sndbulkpipe(stream->dev->udev,
1063                                        ep->desc.bEndpointAddress);
1064
1065         if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1066                 size = 0;
1067
1068         for (i = 0; i < UVC_URBS; ++i) {
1069                 urb = usb_alloc_urb(0, gfp_flags);
1070                 if (urb == NULL) {
1071                         uvc_uninit_video(stream, 1);
1072                         return -ENOMEM;
1073                 }
1074
1075                 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1076                         stream->urb_buffer[i], size, uvc_video_complete,
1077                         stream);
1078 #ifndef CONFIG_DMA_NONCOHERENT
1079                 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1080                 urb->transfer_dma = stream->urb_dma[i];
1081 #endif
1082
1083                 stream->urb[i] = urb;
1084         }
1085
1086         return 0;
1087 }
1088
1089 /*
1090  * Initialize isochronous/bulk URBs and allocate transfer buffers.
1091  */
1092 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1093 {
1094         struct usb_interface *intf = stream->intf;
1095         struct usb_host_endpoint *ep;
1096         unsigned int i;
1097         int ret;
1098
1099         stream->sequence = -1;
1100         stream->last_fid = -1;
1101         stream->bulk.header_size = 0;
1102         stream->bulk.skip_payload = 0;
1103         stream->bulk.payload_size = 0;
1104
1105         uvc_video_stats_start(stream);
1106
1107         if (intf->num_altsetting > 1) {
1108                 struct usb_host_endpoint *best_ep = NULL;
1109                 unsigned int best_psize = 3 * 1024;
1110                 unsigned int bandwidth;
1111                 unsigned int uninitialized_var(altsetting);
1112                 int intfnum = stream->intfnum;
1113
1114                 /* Isochronous endpoint, select the alternate setting. */
1115                 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1116
1117                 if (bandwidth == 0) {
1118                         uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1119                                 "bandwidth, defaulting to lowest.\n");
1120                         bandwidth = 1;
1121                 } else {
1122                         uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1123                                 "B/frame bandwidth.\n", bandwidth);
1124                 }
1125
1126                 for (i = 0; i < intf->num_altsetting; ++i) {
1127                         struct usb_host_interface *alts;
1128                         unsigned int psize;
1129
1130                         alts = &intf->altsetting[i];
1131                         ep = uvc_find_endpoint(alts,
1132                                 stream->header.bEndpointAddress);
1133                         if (ep == NULL)
1134                                 continue;
1135
1136                         /* Check if the bandwidth is high enough. */
1137                         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
1138                         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1139                         if (psize >= bandwidth && psize <= best_psize) {
1140                                 altsetting = i;
1141                                 best_psize = psize;
1142                                 best_ep = ep;
1143                         }
1144                 }
1145
1146                 if (best_ep == NULL) {
1147                         uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1148                                 "for requested bandwidth.\n");
1149                         return -EIO;
1150                 }
1151
1152                 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1153                         "(%u B/frame bandwidth).\n", altsetting, best_psize);
1154
1155                 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1156                 if (ret < 0)
1157                         return ret;
1158
1159                 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1160         } else {
1161                 /* Bulk endpoint, proceed to URB initialization. */
1162                 ep = uvc_find_endpoint(&intf->altsetting[0],
1163                                 stream->header.bEndpointAddress);
1164                 if (ep == NULL)
1165                         return -EIO;
1166
1167                 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1168         }
1169
1170         if (ret < 0)
1171                 return ret;
1172
1173         /* Submit the URBs. */
1174         for (i = 0; i < UVC_URBS; ++i) {
1175                 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1176                 if (ret < 0) {
1177                         uvc_printk(KERN_ERR, "Failed to submit URB %u "
1178                                         "(%d).\n", i, ret);
1179                         uvc_uninit_video(stream, 1);
1180                         return ret;
1181                 }
1182         }
1183
1184         return 0;
1185 }
1186
1187 /* --------------------------------------------------------------------------
1188  * Suspend/resume
1189  */
1190
1191 /*
1192  * Stop streaming without disabling the video queue.
1193  *
1194  * To let userspace applications resume without trouble, we must not touch the
1195  * video buffers in any way. We mark the device as frozen to make sure the URB
1196  * completion handler won't try to cancel the queue when we kill the URBs.
1197  */
1198 int uvc_video_suspend(struct uvc_streaming *stream)
1199 {
1200         if (!uvc_queue_streaming(&stream->queue))
1201                 return 0;
1202
1203         stream->frozen = 1;
1204         uvc_uninit_video(stream, 0);
1205         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1206         return 0;
1207 }
1208
1209 /*
1210  * Reconfigure the video interface and restart streaming if it was enabled
1211  * before suspend.
1212  *
1213  * If an error occurs, disable the video queue. This will wake all pending
1214  * buffers, making sure userspace applications are notified of the problem
1215  * instead of waiting forever.
1216  */
1217 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1218 {
1219         int ret;
1220
1221         /* If the bus has been reset on resume, set the alternate setting to 0.
1222          * This should be the default value, but some devices crash or otherwise
1223          * misbehave if they don't receive a SET_INTERFACE request before any
1224          * other video control request.
1225          */
1226         if (reset)
1227                 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1228
1229         stream->frozen = 0;
1230
1231         ret = uvc_commit_video(stream, &stream->ctrl);
1232         if (ret < 0) {
1233                 uvc_queue_enable(&stream->queue, 0);
1234                 return ret;
1235         }
1236
1237         if (!uvc_queue_streaming(&stream->queue))
1238                 return 0;
1239
1240         ret = uvc_init_video(stream, GFP_NOIO);
1241         if (ret < 0)
1242                 uvc_queue_enable(&stream->queue, 0);
1243
1244         return ret;
1245 }
1246
1247 /* ------------------------------------------------------------------------
1248  * Video device
1249  */
1250
1251 /*
1252  * Initialize the UVC video device by switching to alternate setting 0 and
1253  * retrieve the default format.
1254  *
1255  * Some cameras (namely the Fuji Finepix) set the format and frame
1256  * indexes to zero. The UVC standard doesn't clearly make this a spec
1257  * violation, so try to silently fix the values if possible.
1258  *
1259  * This function is called before registering the device with V4L.
1260  */
1261 int uvc_video_init(struct uvc_streaming *stream)
1262 {
1263         struct uvc_streaming_control *probe = &stream->ctrl;
1264         struct uvc_format *format = NULL;
1265         struct uvc_frame *frame = NULL;
1266         unsigned int i;
1267         int ret;
1268
1269         if (stream->nformats == 0) {
1270                 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1271                 return -EINVAL;
1272         }
1273
1274         atomic_set(&stream->active, 0);
1275
1276         /* Initialize the video buffers queue. */
1277         uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1278
1279         /* Alternate setting 0 should be the default, yet the XBox Live Vision
1280          * Cam (and possibly other devices) crash or otherwise misbehave if
1281          * they don't receive a SET_INTERFACE request before any other video
1282          * control request.
1283          */
1284         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1285
1286         /* Set the streaming probe control with default streaming parameters
1287          * retrieved from the device. Webcams that don't suport GET_DEF
1288          * requests on the probe control will just keep their current streaming
1289          * parameters.
1290          */
1291         if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1292                 uvc_set_video_ctrl(stream, probe, 1);
1293
1294         /* Initialize the streaming parameters with the probe control current
1295          * value. This makes sure SET_CUR requests on the streaming commit
1296          * control will always use values retrieved from a successful GET_CUR
1297          * request on the probe control, as required by the UVC specification.
1298          */
1299         ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1300         if (ret < 0)
1301                 return ret;
1302
1303         /* Check if the default format descriptor exists. Use the first
1304          * available format otherwise.
1305          */
1306         for (i = stream->nformats; i > 0; --i) {
1307                 format = &stream->format[i-1];
1308                 if (format->index == probe->bFormatIndex)
1309                         break;
1310         }
1311
1312         if (format->nframes == 0) {
1313                 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1314                         "default format.\n");
1315                 return -EINVAL;
1316         }
1317
1318         /* Zero bFrameIndex might be correct. Stream-based formats (including
1319          * MPEG-2 TS and DV) do not support frames but have a dummy frame
1320          * descriptor with bFrameIndex set to zero. If the default frame
1321          * descriptor is not found, use the first available frame.
1322          */
1323         for (i = format->nframes; i > 0; --i) {
1324                 frame = &format->frame[i-1];
1325                 if (frame->bFrameIndex == probe->bFrameIndex)
1326                         break;
1327         }
1328
1329         probe->bFormatIndex = format->index;
1330         probe->bFrameIndex = frame->bFrameIndex;
1331
1332         stream->cur_format = format;
1333         stream->cur_frame = frame;
1334
1335         /* Select the video decoding function */
1336         if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1337                 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1338                         stream->decode = uvc_video_decode_isight;
1339                 else if (stream->intf->num_altsetting > 1)
1340                         stream->decode = uvc_video_decode_isoc;
1341                 else
1342                         stream->decode = uvc_video_decode_bulk;
1343         } else {
1344                 if (stream->intf->num_altsetting == 1)
1345                         stream->decode = uvc_video_encode_bulk;
1346                 else {
1347                         uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1348                                 "supported for video output devices.\n");
1349                         return -EINVAL;
1350                 }
1351         }
1352
1353         return 0;
1354 }
1355
1356 /*
1357  * Enable or disable the video stream.
1358  */
1359 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1360 {
1361         int ret;
1362
1363         if (!enable) {
1364                 uvc_uninit_video(stream, 1);
1365                 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1366                 uvc_queue_enable(&stream->queue, 0);
1367                 return 0;
1368         }
1369
1370         ret = uvc_queue_enable(&stream->queue, 1);
1371         if (ret < 0)
1372                 return ret;
1373
1374         /* Commit the streaming parameters. */
1375         ret = uvc_commit_video(stream, &stream->ctrl);
1376         if (ret < 0) {
1377                 uvc_queue_enable(&stream->queue, 0);
1378                 return ret;
1379         }
1380
1381         ret = uvc_init_video(stream, GFP_KERNEL);
1382         if (ret < 0) {
1383                 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1384                 uvc_queue_enable(&stream->queue, 0);
1385         }
1386
1387         return ret;
1388 }