Merge branch 'topic/hda' into for-linus
[pandora-kernel.git] / drivers / media / video / uvc / uvc_video.c
1 /*
2  *      uvc_video.c  --  USB Video Class driver - Video handling
3  *
4  *      Copyright (C) 2005-2009
5  *          Laurent Pinchart (laurent.pinchart@skynet.be)
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/usb.h>
18 #include <linux/videodev2.h>
19 #include <linux/vmalloc.h>
20 #include <linux/wait.h>
21 #include <asm/atomic.h>
22 #include <asm/unaligned.h>
23
24 #include <media/v4l2-common.h>
25
26 #include "uvcvideo.h"
27
28 /* ------------------------------------------------------------------------
29  * UVC Controls
30  */
31
32 static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
33                         __u8 intfnum, __u8 cs, void *data, __u16 size,
34                         int timeout)
35 {
36         __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
37         unsigned int pipe;
38
39         pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
40                               : usb_sndctrlpipe(dev->udev, 0);
41         type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
42
43         return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
44                         unit << 8 | intfnum, data, size, timeout);
45 }
46
47 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
48                         __u8 intfnum, __u8 cs, void *data, __u16 size)
49 {
50         int ret;
51
52         ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
53                                 UVC_CTRL_CONTROL_TIMEOUT);
54         if (ret != size) {
55                 uvc_printk(KERN_ERR, "Failed to query (%u) UVC control %u "
56                         "(unit %u) : %d (exp. %u).\n", query, cs, unit, ret,
57                         size);
58                 return -EIO;
59         }
60
61         return 0;
62 }
63
64 static void uvc_fixup_video_ctrl(struct uvc_video_device *video,
65         struct uvc_streaming_control *ctrl)
66 {
67         struct uvc_format *format;
68         struct uvc_frame *frame;
69
70         if (ctrl->bFormatIndex <= 0 ||
71             ctrl->bFormatIndex > video->streaming->nformats)
72                 return;
73
74         format = &video->streaming->format[ctrl->bFormatIndex - 1];
75
76         if (ctrl->bFrameIndex <= 0 ||
77             ctrl->bFrameIndex > format->nframes)
78                 return;
79
80         frame = &format->frame[ctrl->bFrameIndex - 1];
81
82         if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
83              (ctrl->dwMaxVideoFrameSize == 0 &&
84               video->dev->uvc_version < 0x0110))
85                 ctrl->dwMaxVideoFrameSize =
86                         frame->dwMaxVideoFrameBufferSize;
87
88         if (video->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
89             video->streaming->intf->num_altsetting > 1) {
90                 u32 interval;
91                 u32 bandwidth;
92
93                 interval = (ctrl->dwFrameInterval > 100000)
94                          ? ctrl->dwFrameInterval
95                          : frame->dwFrameInterval[0];
96
97                 /* Compute a bandwidth estimation by multiplying the frame
98                  * size by the number of video frames per second, divide the
99                  * result by the number of USB frames (or micro-frames for
100                  * high-speed devices) per second and add the UVC header size
101                  * (assumed to be 12 bytes long).
102                  */
103                 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
104                 bandwidth *= 10000000 / interval + 1;
105                 bandwidth /= 1000;
106                 if (video->dev->udev->speed == USB_SPEED_HIGH)
107                         bandwidth /= 8;
108                 bandwidth += 12;
109
110                 ctrl->dwMaxPayloadTransferSize = bandwidth;
111         }
112 }
113
114 static int uvc_get_video_ctrl(struct uvc_video_device *video,
115         struct uvc_streaming_control *ctrl, int probe, __u8 query)
116 {
117         __u8 *data;
118         __u16 size;
119         int ret;
120
121         size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
122         data = kmalloc(size, GFP_KERNEL);
123         if (data == NULL)
124                 return -ENOMEM;
125
126         ret = __uvc_query_ctrl(video->dev, query, 0, video->streaming->intfnum,
127                 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
128                 UVC_CTRL_STREAMING_TIMEOUT);
129
130         if ((query == GET_MIN || query == GET_MAX) && ret == 2) {
131                 /* Some cameras, mostly based on Bison Electronics chipsets,
132                  * answer a GET_MIN or GET_MAX request with the wCompQuality
133                  * field only.
134                  */
135                 uvc_warn_once(video->dev, UVC_WARN_MINMAX, "UVC non "
136                         "compliance - GET_MIN/MAX(PROBE) incorrectly "
137                         "supported. Enabling workaround.\n");
138                 memset(ctrl, 0, sizeof ctrl);
139                 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
140                 ret = 0;
141                 goto out;
142         } else if (query == GET_DEF && probe == 1 && ret != size) {
143                 /* Many cameras don't support the GET_DEF request on their
144                  * video probe control. Warn once and return, the caller will
145                  * fall back to GET_CUR.
146                  */
147                 uvc_warn_once(video->dev, UVC_WARN_PROBE_DEF, "UVC non "
148                         "compliance - GET_DEF(PROBE) not supported. "
149                         "Enabling workaround.\n");
150                 ret = -EIO;
151                 goto out;
152         } else if (ret != size) {
153                 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
154                         "%d (exp. %u).\n", query, probe ? "probe" : "commit",
155                         ret, size);
156                 ret = -EIO;
157                 goto out;
158         }
159
160         ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
161         ctrl->bFormatIndex = data[2];
162         ctrl->bFrameIndex = data[3];
163         ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
164         ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
165         ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
166         ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
167         ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
168         ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
169         ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
170         ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
171
172         if (size == 34) {
173                 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
174                 ctrl->bmFramingInfo = data[30];
175                 ctrl->bPreferedVersion = data[31];
176                 ctrl->bMinVersion = data[32];
177                 ctrl->bMaxVersion = data[33];
178         } else {
179                 ctrl->dwClockFrequency = video->dev->clock_frequency;
180                 ctrl->bmFramingInfo = 0;
181                 ctrl->bPreferedVersion = 0;
182                 ctrl->bMinVersion = 0;
183                 ctrl->bMaxVersion = 0;
184         }
185
186         /* Some broken devices return null or wrong dwMaxVideoFrameSize and
187          * dwMaxPayloadTransferSize fields. Try to get the value from the
188          * format and frame descriptors.
189          */
190         uvc_fixup_video_ctrl(video, ctrl);
191         ret = 0;
192
193 out:
194         kfree(data);
195         return ret;
196 }
197
198 static int uvc_set_video_ctrl(struct uvc_video_device *video,
199         struct uvc_streaming_control *ctrl, int probe)
200 {
201         __u8 *data;
202         __u16 size;
203         int ret;
204
205         size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
206         data = kzalloc(size, GFP_KERNEL);
207         if (data == NULL)
208                 return -ENOMEM;
209
210         *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
211         data[2] = ctrl->bFormatIndex;
212         data[3] = ctrl->bFrameIndex;
213         *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
214         *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
215         *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
216         *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
217         *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
218         *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
219         put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
220         put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
221
222         if (size == 34) {
223                 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
224                 data[30] = ctrl->bmFramingInfo;
225                 data[31] = ctrl->bPreferedVersion;
226                 data[32] = ctrl->bMinVersion;
227                 data[33] = ctrl->bMaxVersion;
228         }
229
230         ret = __uvc_query_ctrl(video->dev, SET_CUR, 0,
231                 video->streaming->intfnum,
232                 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
233                 UVC_CTRL_STREAMING_TIMEOUT);
234         if (ret != size) {
235                 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
236                         "%d (exp. %u).\n", probe ? "probe" : "commit",
237                         ret, size);
238                 ret = -EIO;
239         }
240
241         kfree(data);
242         return ret;
243 }
244
245 int uvc_probe_video(struct uvc_video_device *video,
246         struct uvc_streaming_control *probe)
247 {
248         struct uvc_streaming_control probe_min, probe_max;
249         __u16 bandwidth;
250         unsigned int i;
251         int ret;
252
253         mutex_lock(&video->streaming->mutex);
254
255         /* Perform probing. The device should adjust the requested values
256          * according to its capabilities. However, some devices, namely the
257          * first generation UVC Logitech webcams, don't implement the Video
258          * Probe control properly, and just return the needed bandwidth. For
259          * that reason, if the needed bandwidth exceeds the maximum available
260          * bandwidth, try to lower the quality.
261          */
262         if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0)
263                 goto done;
264
265         /* Get the minimum and maximum values for compression settings. */
266         if (!(video->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
267                 ret = uvc_get_video_ctrl(video, &probe_min, 1, GET_MIN);
268                 if (ret < 0)
269                         goto done;
270                 ret = uvc_get_video_ctrl(video, &probe_max, 1, GET_MAX);
271                 if (ret < 0)
272                         goto done;
273
274                 probe->wCompQuality = probe_max.wCompQuality;
275         }
276
277         for (i = 0; i < 2; ++i) {
278                 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0 ||
279                     (ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
280                         goto done;
281
282                 if (video->streaming->intf->num_altsetting == 1)
283                         break;
284
285                 bandwidth = probe->dwMaxPayloadTransferSize;
286                 if (bandwidth <= video->streaming->maxpsize)
287                         break;
288
289                 if (video->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
290                         ret = -ENOSPC;
291                         goto done;
292                 }
293
294                 /* TODO: negotiate compression parameters */
295                 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
296                 probe->wPFrameRate = probe_min.wPFrameRate;
297                 probe->wCompQuality = probe_max.wCompQuality;
298                 probe->wCompWindowSize = probe_min.wCompWindowSize;
299         }
300
301 done:
302         mutex_unlock(&video->streaming->mutex);
303         return ret;
304 }
305
306 int uvc_commit_video(struct uvc_video_device *video,
307         struct uvc_streaming_control *probe)
308 {
309         return uvc_set_video_ctrl(video, probe, 0);
310 }
311
312 /* ------------------------------------------------------------------------
313  * Video codecs
314  */
315
316 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
317 #define UVC_STREAM_EOH  (1 << 7)
318 #define UVC_STREAM_ERR  (1 << 6)
319 #define UVC_STREAM_STI  (1 << 5)
320 #define UVC_STREAM_RES  (1 << 4)
321 #define UVC_STREAM_SCR  (1 << 3)
322 #define UVC_STREAM_PTS  (1 << 2)
323 #define UVC_STREAM_EOF  (1 << 1)
324 #define UVC_STREAM_FID  (1 << 0)
325
326 /* Video payload decoding is handled by uvc_video_decode_start(),
327  * uvc_video_decode_data() and uvc_video_decode_end().
328  *
329  * uvc_video_decode_start is called with URB data at the start of a bulk or
330  * isochronous payload. It processes header data and returns the header size
331  * in bytes if successful. If an error occurs, it returns a negative error
332  * code. The following error codes have special meanings.
333  *
334  * - EAGAIN informs the caller that the current video buffer should be marked
335  *   as done, and that the function should be called again with the same data
336  *   and a new video buffer. This is used when end of frame conditions can be
337  *   reliably detected at the beginning of the next frame only.
338  *
339  * If an error other than -EAGAIN is returned, the caller will drop the current
340  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
341  * made until the next payload. -ENODATA can be used to drop the current
342  * payload if no other error code is appropriate.
343  *
344  * uvc_video_decode_data is called for every URB with URB data. It copies the
345  * data to the video buffer.
346  *
347  * uvc_video_decode_end is called with header data at the end of a bulk or
348  * isochronous payload. It performs any additional header data processing and
349  * returns 0 or a negative error code if an error occured. As header data have
350  * already been processed by uvc_video_decode_start, this functions isn't
351  * required to perform sanity checks a second time.
352  *
353  * For isochronous transfers where a payload is always transfered in a single
354  * URB, the three functions will be called in a row.
355  *
356  * To let the decoder process header data and update its internal state even
357  * when no video buffer is available, uvc_video_decode_start must be prepared
358  * to be called with a NULL buf parameter. uvc_video_decode_data and
359  * uvc_video_decode_end will never be called with a NULL buffer.
360  */
361 static int uvc_video_decode_start(struct uvc_video_device *video,
362                 struct uvc_buffer *buf, const __u8 *data, int len)
363 {
364         __u8 fid;
365
366         /* Sanity checks:
367          * - packet must be at least 2 bytes long
368          * - bHeaderLength value must be at least 2 bytes (see above)
369          * - bHeaderLength value can't be larger than the packet size.
370          */
371         if (len < 2 || data[0] < 2 || data[0] > len)
372                 return -EINVAL;
373
374         /* Skip payloads marked with the error bit ("error frames"). */
375         if (data[1] & UVC_STREAM_ERR) {
376                 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
377                           "set).\n");
378                 return -ENODATA;
379         }
380
381         fid = data[1] & UVC_STREAM_FID;
382
383         /* Store the payload FID bit and return immediately when the buffer is
384          * NULL.
385          */
386         if (buf == NULL) {
387                 video->last_fid = fid;
388                 return -ENODATA;
389         }
390
391         /* Synchronize to the input stream by waiting for the FID bit to be
392          * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
393          * video->last_fid is initialized to -1, so the first isochronous
394          * frame will always be in sync.
395          *
396          * If the device doesn't toggle the FID bit, invert video->last_fid
397          * when the EOF bit is set to force synchronisation on the next packet.
398          */
399         if (buf->state != UVC_BUF_STATE_ACTIVE) {
400                 if (fid == video->last_fid) {
401                         uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
402                                 "sync).\n");
403                         if ((video->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
404                             (data[1] & UVC_STREAM_EOF))
405                                 video->last_fid ^= UVC_STREAM_FID;
406                         return -ENODATA;
407                 }
408
409                 /* TODO: Handle PTS and SCR. */
410                 buf->state = UVC_BUF_STATE_ACTIVE;
411         }
412
413         /* Mark the buffer as done if we're at the beginning of a new frame.
414          * End of frame detection is better implemented by checking the EOF
415          * bit (FID bit toggling is delayed by one frame compared to the EOF
416          * bit), but some devices don't set the bit at end of frame (and the
417          * last payload can be lost anyway). We thus must check if the FID has
418          * been toggled.
419          *
420          * video->last_fid is initialized to -1, so the first isochronous
421          * frame will never trigger an end of frame detection.
422          *
423          * Empty buffers (bytesused == 0) don't trigger end of frame detection
424          * as it doesn't make sense to return an empty buffer. This also
425          * avoids detecting end of frame conditions at FID toggling if the
426          * previous payload had the EOF bit set.
427          */
428         if (fid != video->last_fid && buf->buf.bytesused != 0) {
429                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
430                                 "toggled).\n");
431                 buf->state = UVC_BUF_STATE_DONE;
432                 return -EAGAIN;
433         }
434
435         video->last_fid = fid;
436
437         return data[0];
438 }
439
440 static void uvc_video_decode_data(struct uvc_video_device *video,
441                 struct uvc_buffer *buf, const __u8 *data, int len)
442 {
443         struct uvc_video_queue *queue = &video->queue;
444         unsigned int maxlen, nbytes;
445         void *mem;
446
447         if (len <= 0)
448                 return;
449
450         /* Copy the video data to the buffer. */
451         maxlen = buf->buf.length - buf->buf.bytesused;
452         mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
453         nbytes = min((unsigned int)len, maxlen);
454         memcpy(mem, data, nbytes);
455         buf->buf.bytesused += nbytes;
456
457         /* Complete the current frame if the buffer size was exceeded. */
458         if (len > maxlen) {
459                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
460                 buf->state = UVC_BUF_STATE_DONE;
461         }
462 }
463
464 static void uvc_video_decode_end(struct uvc_video_device *video,
465                 struct uvc_buffer *buf, const __u8 *data, int len)
466 {
467         /* Mark the buffer as done if the EOF marker is set. */
468         if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
469                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
470                 if (data[0] == len)
471                         uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
472                 buf->state = UVC_BUF_STATE_DONE;
473                 if (video->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
474                         video->last_fid ^= UVC_STREAM_FID;
475         }
476 }
477
478 /* Video payload encoding is handled by uvc_video_encode_header() and
479  * uvc_video_encode_data(). Only bulk transfers are currently supported.
480  *
481  * uvc_video_encode_header is called at the start of a payload. It adds header
482  * data to the transfer buffer and returns the header size. As the only known
483  * UVC output device transfers a whole frame in a single payload, the EOF bit
484  * is always set in the header.
485  *
486  * uvc_video_encode_data is called for every URB and copies the data from the
487  * video buffer to the transfer buffer.
488  */
489 static int uvc_video_encode_header(struct uvc_video_device *video,
490                 struct uvc_buffer *buf, __u8 *data, int len)
491 {
492         data[0] = 2;    /* Header length */
493         data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
494                 | (video->last_fid & UVC_STREAM_FID);
495         return 2;
496 }
497
498 static int uvc_video_encode_data(struct uvc_video_device *video,
499                 struct uvc_buffer *buf, __u8 *data, int len)
500 {
501         struct uvc_video_queue *queue = &video->queue;
502         unsigned int nbytes;
503         void *mem;
504
505         /* Copy video data to the URB buffer. */
506         mem = queue->mem + buf->buf.m.offset + queue->buf_used;
507         nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
508         nbytes = min(video->bulk.max_payload_size - video->bulk.payload_size,
509                         nbytes);
510         memcpy(data, mem, nbytes);
511
512         queue->buf_used += nbytes;
513
514         return nbytes;
515 }
516
517 /* ------------------------------------------------------------------------
518  * URB handling
519  */
520
521 /*
522  * Completion handler for video URBs.
523  */
524 static void uvc_video_decode_isoc(struct urb *urb,
525         struct uvc_video_device *video, struct uvc_buffer *buf)
526 {
527         u8 *mem;
528         int ret, i;
529
530         for (i = 0; i < urb->number_of_packets; ++i) {
531                 if (urb->iso_frame_desc[i].status < 0) {
532                         uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
533                                 "lost (%d).\n", urb->iso_frame_desc[i].status);
534                         continue;
535                 }
536
537                 /* Decode the payload header. */
538                 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
539                 do {
540                         ret = uvc_video_decode_start(video, buf, mem,
541                                 urb->iso_frame_desc[i].actual_length);
542                         if (ret == -EAGAIN)
543                                 buf = uvc_queue_next_buffer(&video->queue, buf);
544                 } while (ret == -EAGAIN);
545
546                 if (ret < 0)
547                         continue;
548
549                 /* Decode the payload data. */
550                 uvc_video_decode_data(video, buf, mem + ret,
551                         urb->iso_frame_desc[i].actual_length - ret);
552
553                 /* Process the header again. */
554                 uvc_video_decode_end(video, buf, mem,
555                         urb->iso_frame_desc[i].actual_length);
556
557                 if (buf->state == UVC_BUF_STATE_DONE ||
558                     buf->state == UVC_BUF_STATE_ERROR)
559                         buf = uvc_queue_next_buffer(&video->queue, buf);
560         }
561 }
562
563 static void uvc_video_decode_bulk(struct urb *urb,
564         struct uvc_video_device *video, struct uvc_buffer *buf)
565 {
566         u8 *mem;
567         int len, ret;
568
569         if (urb->actual_length == 0)
570                 return;
571
572         mem = urb->transfer_buffer;
573         len = urb->actual_length;
574         video->bulk.payload_size += len;
575
576         /* If the URB is the first of its payload, decode and save the
577          * header.
578          */
579         if (video->bulk.header_size == 0 && !video->bulk.skip_payload) {
580                 do {
581                         ret = uvc_video_decode_start(video, buf, mem, len);
582                         if (ret == -EAGAIN)
583                                 buf = uvc_queue_next_buffer(&video->queue, buf);
584                 } while (ret == -EAGAIN);
585
586                 /* If an error occured skip the rest of the payload. */
587                 if (ret < 0 || buf == NULL) {
588                         video->bulk.skip_payload = 1;
589                 } else {
590                         memcpy(video->bulk.header, mem, ret);
591                         video->bulk.header_size = ret;
592
593                         mem += ret;
594                         len -= ret;
595                 }
596         }
597
598         /* The buffer queue might have been cancelled while a bulk transfer
599          * was in progress, so we can reach here with buf equal to NULL. Make
600          * sure buf is never dereferenced if NULL.
601          */
602
603         /* Process video data. */
604         if (!video->bulk.skip_payload && buf != NULL)
605                 uvc_video_decode_data(video, buf, mem, len);
606
607         /* Detect the payload end by a URB smaller than the maximum size (or
608          * a payload size equal to the maximum) and process the header again.
609          */
610         if (urb->actual_length < urb->transfer_buffer_length ||
611             video->bulk.payload_size >= video->bulk.max_payload_size) {
612                 if (!video->bulk.skip_payload && buf != NULL) {
613                         uvc_video_decode_end(video, buf, video->bulk.header,
614                                 video->bulk.payload_size);
615                         if (buf->state == UVC_BUF_STATE_DONE ||
616                             buf->state == UVC_BUF_STATE_ERROR)
617                                 buf = uvc_queue_next_buffer(&video->queue, buf);
618                 }
619
620                 video->bulk.header_size = 0;
621                 video->bulk.skip_payload = 0;
622                 video->bulk.payload_size = 0;
623         }
624 }
625
626 static void uvc_video_encode_bulk(struct urb *urb,
627         struct uvc_video_device *video, struct uvc_buffer *buf)
628 {
629         u8 *mem = urb->transfer_buffer;
630         int len = video->urb_size, ret;
631
632         if (buf == NULL) {
633                 urb->transfer_buffer_length = 0;
634                 return;
635         }
636
637         /* If the URB is the first of its payload, add the header. */
638         if (video->bulk.header_size == 0) {
639                 ret = uvc_video_encode_header(video, buf, mem, len);
640                 video->bulk.header_size = ret;
641                 video->bulk.payload_size += ret;
642                 mem += ret;
643                 len -= ret;
644         }
645
646         /* Process video data. */
647         ret = uvc_video_encode_data(video, buf, mem, len);
648
649         video->bulk.payload_size += ret;
650         len -= ret;
651
652         if (buf->buf.bytesused == video->queue.buf_used ||
653             video->bulk.payload_size == video->bulk.max_payload_size) {
654                 if (buf->buf.bytesused == video->queue.buf_used) {
655                         video->queue.buf_used = 0;
656                         buf->state = UVC_BUF_STATE_DONE;
657                         uvc_queue_next_buffer(&video->queue, buf);
658                         video->last_fid ^= UVC_STREAM_FID;
659                 }
660
661                 video->bulk.header_size = 0;
662                 video->bulk.payload_size = 0;
663         }
664
665         urb->transfer_buffer_length = video->urb_size - len;
666 }
667
668 static void uvc_video_complete(struct urb *urb)
669 {
670         struct uvc_video_device *video = urb->context;
671         struct uvc_video_queue *queue = &video->queue;
672         struct uvc_buffer *buf = NULL;
673         unsigned long flags;
674         int ret;
675
676         switch (urb->status) {
677         case 0:
678                 break;
679
680         default:
681                 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
682                         "completion handler.\n", urb->status);
683
684         case -ENOENT:           /* usb_kill_urb() called. */
685                 if (video->frozen)
686                         return;
687
688         case -ECONNRESET:       /* usb_unlink_urb() called. */
689         case -ESHUTDOWN:        /* The endpoint is being disabled. */
690                 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
691                 return;
692         }
693
694         spin_lock_irqsave(&queue->irqlock, flags);
695         if (!list_empty(&queue->irqqueue))
696                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
697                                        queue);
698         spin_unlock_irqrestore(&queue->irqlock, flags);
699
700         video->decode(urb, video, buf);
701
702         if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
703                 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
704                         ret);
705         }
706 }
707
708 /*
709  * Free transfer buffers.
710  */
711 static void uvc_free_urb_buffers(struct uvc_video_device *video)
712 {
713         unsigned int i;
714
715         for (i = 0; i < UVC_URBS; ++i) {
716                 if (video->urb_buffer[i]) {
717                         usb_buffer_free(video->dev->udev, video->urb_size,
718                                 video->urb_buffer[i], video->urb_dma[i]);
719                         video->urb_buffer[i] = NULL;
720                 }
721         }
722
723         video->urb_size = 0;
724 }
725
726 /*
727  * Allocate transfer buffers. This function can be called with buffers
728  * already allocated when resuming from suspend, in which case it will
729  * return without touching the buffers.
730  *
731  * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
732  * system is too low on memory try successively smaller numbers of packets
733  * until allocation succeeds.
734  *
735  * Return the number of allocated packets on success or 0 when out of memory.
736  */
737 static int uvc_alloc_urb_buffers(struct uvc_video_device *video,
738         unsigned int size, unsigned int psize, gfp_t gfp_flags)
739 {
740         unsigned int npackets;
741         unsigned int i;
742
743         /* Buffers are already allocated, bail out. */
744         if (video->urb_size)
745                 return video->urb_size / psize;
746
747         /* Compute the number of packets. Bulk endpoints might transfer UVC
748          * payloads accross multiple URBs.
749          */
750         npackets = DIV_ROUND_UP(size, psize);
751         if (npackets > UVC_MAX_PACKETS)
752                 npackets = UVC_MAX_PACKETS;
753
754         /* Retry allocations until one succeed. */
755         for (; npackets > 1; npackets /= 2) {
756                 for (i = 0; i < UVC_URBS; ++i) {
757                         video->urb_buffer[i] = usb_buffer_alloc(
758                                 video->dev->udev, psize * npackets,
759                                 gfp_flags | __GFP_NOWARN, &video->urb_dma[i]);
760                         if (!video->urb_buffer[i]) {
761                                 uvc_free_urb_buffers(video);
762                                 break;
763                         }
764                 }
765
766                 if (i == UVC_URBS) {
767                         video->urb_size = psize * npackets;
768                         return npackets;
769                 }
770         }
771
772         return 0;
773 }
774
775 /*
776  * Uninitialize isochronous/bulk URBs and free transfer buffers.
777  */
778 static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
779 {
780         struct urb *urb;
781         unsigned int i;
782
783         for (i = 0; i < UVC_URBS; ++i) {
784                 if ((urb = video->urb[i]) == NULL)
785                         continue;
786
787                 usb_kill_urb(urb);
788                 usb_free_urb(urb);
789                 video->urb[i] = NULL;
790         }
791
792         if (free_buffers)
793                 uvc_free_urb_buffers(video);
794 }
795
796 /*
797  * Initialize isochronous URBs and allocate transfer buffers. The packet size
798  * is given by the endpoint.
799  */
800 static int uvc_init_video_isoc(struct uvc_video_device *video,
801         struct usb_host_endpoint *ep, gfp_t gfp_flags)
802 {
803         struct urb *urb;
804         unsigned int npackets, i, j;
805         u16 psize;
806         u32 size;
807
808         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
809         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
810         size = video->streaming->ctrl.dwMaxVideoFrameSize;
811
812         npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
813         if (npackets == 0)
814                 return -ENOMEM;
815
816         size = npackets * psize;
817
818         for (i = 0; i < UVC_URBS; ++i) {
819                 urb = usb_alloc_urb(npackets, gfp_flags);
820                 if (urb == NULL) {
821                         uvc_uninit_video(video, 1);
822                         return -ENOMEM;
823                 }
824
825                 urb->dev = video->dev->udev;
826                 urb->context = video;
827                 urb->pipe = usb_rcvisocpipe(video->dev->udev,
828                                 ep->desc.bEndpointAddress);
829                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
830                 urb->interval = ep->desc.bInterval;
831                 urb->transfer_buffer = video->urb_buffer[i];
832                 urb->transfer_dma = video->urb_dma[i];
833                 urb->complete = uvc_video_complete;
834                 urb->number_of_packets = npackets;
835                 urb->transfer_buffer_length = size;
836
837                 for (j = 0; j < npackets; ++j) {
838                         urb->iso_frame_desc[j].offset = j * psize;
839                         urb->iso_frame_desc[j].length = psize;
840                 }
841
842                 video->urb[i] = urb;
843         }
844
845         return 0;
846 }
847
848 /*
849  * Initialize bulk URBs and allocate transfer buffers. The packet size is
850  * given by the endpoint.
851  */
852 static int uvc_init_video_bulk(struct uvc_video_device *video,
853         struct usb_host_endpoint *ep, gfp_t gfp_flags)
854 {
855         struct urb *urb;
856         unsigned int npackets, pipe, i;
857         u16 psize;
858         u32 size;
859
860         psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
861         size = video->streaming->ctrl.dwMaxPayloadTransferSize;
862         video->bulk.max_payload_size = size;
863
864         npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
865         if (npackets == 0)
866                 return -ENOMEM;
867
868         size = npackets * psize;
869
870         if (usb_endpoint_dir_in(&ep->desc))
871                 pipe = usb_rcvbulkpipe(video->dev->udev,
872                                        ep->desc.bEndpointAddress);
873         else
874                 pipe = usb_sndbulkpipe(video->dev->udev,
875                                        ep->desc.bEndpointAddress);
876
877         if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
878                 size = 0;
879
880         for (i = 0; i < UVC_URBS; ++i) {
881                 urb = usb_alloc_urb(0, gfp_flags);
882                 if (urb == NULL) {
883                         uvc_uninit_video(video, 1);
884                         return -ENOMEM;
885                 }
886
887                 usb_fill_bulk_urb(urb, video->dev->udev, pipe,
888                         video->urb_buffer[i], size, uvc_video_complete,
889                         video);
890                 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
891                 urb->transfer_dma = video->urb_dma[i];
892
893                 video->urb[i] = urb;
894         }
895
896         return 0;
897 }
898
899 /*
900  * Initialize isochronous/bulk URBs and allocate transfer buffers.
901  */
902 static int uvc_init_video(struct uvc_video_device *video, gfp_t gfp_flags)
903 {
904         struct usb_interface *intf = video->streaming->intf;
905         struct usb_host_interface *alts;
906         struct usb_host_endpoint *ep = NULL;
907         int intfnum = video->streaming->intfnum;
908         unsigned int bandwidth, psize, i;
909         int ret;
910
911         video->last_fid = -1;
912         video->bulk.header_size = 0;
913         video->bulk.skip_payload = 0;
914         video->bulk.payload_size = 0;
915
916         if (intf->num_altsetting > 1) {
917                 /* Isochronous endpoint, select the alternate setting. */
918                 bandwidth = video->streaming->ctrl.dwMaxPayloadTransferSize;
919
920                 if (bandwidth == 0) {
921                         uvc_printk(KERN_WARNING, "device %s requested null "
922                                 "bandwidth, defaulting to lowest.\n",
923                                 video->vdev->name);
924                         bandwidth = 1;
925                 }
926
927                 for (i = 0; i < intf->num_altsetting; ++i) {
928                         alts = &intf->altsetting[i];
929                         ep = uvc_find_endpoint(alts,
930                                 video->streaming->header.bEndpointAddress);
931                         if (ep == NULL)
932                                 continue;
933
934                         /* Check if the bandwidth is high enough. */
935                         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
936                         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
937                         if (psize >= bandwidth)
938                                 break;
939                 }
940
941                 if (i >= intf->num_altsetting)
942                         return -EIO;
943
944                 if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
945                         return ret;
946
947                 ret = uvc_init_video_isoc(video, ep, gfp_flags);
948         } else {
949                 /* Bulk endpoint, proceed to URB initialization. */
950                 ep = uvc_find_endpoint(&intf->altsetting[0],
951                                 video->streaming->header.bEndpointAddress);
952                 if (ep == NULL)
953                         return -EIO;
954
955                 ret = uvc_init_video_bulk(video, ep, gfp_flags);
956         }
957
958         if (ret < 0)
959                 return ret;
960
961         /* Submit the URBs. */
962         for (i = 0; i < UVC_URBS; ++i) {
963                 if ((ret = usb_submit_urb(video->urb[i], gfp_flags)) < 0) {
964                         uvc_printk(KERN_ERR, "Failed to submit URB %u "
965                                         "(%d).\n", i, ret);
966                         uvc_uninit_video(video, 1);
967                         return ret;
968                 }
969         }
970
971         return 0;
972 }
973
974 /* --------------------------------------------------------------------------
975  * Suspend/resume
976  */
977
978 /*
979  * Stop streaming without disabling the video queue.
980  *
981  * To let userspace applications resume without trouble, we must not touch the
982  * video buffers in any way. We mark the device as frozen to make sure the URB
983  * completion handler won't try to cancel the queue when we kill the URBs.
984  */
985 int uvc_video_suspend(struct uvc_video_device *video)
986 {
987         if (!uvc_queue_streaming(&video->queue))
988                 return 0;
989
990         video->frozen = 1;
991         uvc_uninit_video(video, 0);
992         usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
993         return 0;
994 }
995
996 /*
997  * Reconfigure the video interface and restart streaming if it was enabled
998  * before suspend.
999  *
1000  * If an error occurs, disable the video queue. This will wake all pending
1001  * buffers, making sure userspace applications are notified of the problem
1002  * instead of waiting forever.
1003  */
1004 int uvc_video_resume(struct uvc_video_device *video)
1005 {
1006         int ret;
1007
1008         video->frozen = 0;
1009
1010         if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0) {
1011                 uvc_queue_enable(&video->queue, 0);
1012                 return ret;
1013         }
1014
1015         if (!uvc_queue_streaming(&video->queue))
1016                 return 0;
1017
1018         if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
1019                 uvc_queue_enable(&video->queue, 0);
1020
1021         return ret;
1022 }
1023
1024 /* ------------------------------------------------------------------------
1025  * Video device
1026  */
1027
1028 /*
1029  * Initialize the UVC video device by switching to alternate setting 0 and
1030  * retrieve the default format.
1031  *
1032  * Some cameras (namely the Fuji Finepix) set the format and frame
1033  * indexes to zero. The UVC standard doesn't clearly make this a spec
1034  * violation, so try to silently fix the values if possible.
1035  *
1036  * This function is called before registering the device with V4L.
1037  */
1038 int uvc_video_init(struct uvc_video_device *video)
1039 {
1040         struct uvc_streaming_control *probe = &video->streaming->ctrl;
1041         struct uvc_format *format = NULL;
1042         struct uvc_frame *frame = NULL;
1043         unsigned int i;
1044         int ret;
1045
1046         if (video->streaming->nformats == 0) {
1047                 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1048                 return -EINVAL;
1049         }
1050
1051         /* Alternate setting 0 should be the default, yet the XBox Live Vision
1052          * Cam (and possibly other devices) crash or otherwise misbehave if
1053          * they don't receive a SET_INTERFACE request before any other video
1054          * control request.
1055          */
1056         usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1057
1058         /* Set the streaming probe control with default streaming parameters
1059          * retrieved from the device. Webcams that don't suport GET_DEF
1060          * requests on the probe control will just keep their current streaming
1061          * parameters.
1062          */
1063         if (uvc_get_video_ctrl(video, probe, 1, GET_DEF) == 0)
1064                 uvc_set_video_ctrl(video, probe, 1);
1065
1066         /* Initialize the streaming parameters with the probe control current
1067          * value. This makes sure SET_CUR requests on the streaming commit
1068          * control will always use values retrieved from a successful GET_CUR
1069          * request on the probe control, as required by the UVC specification.
1070          */
1071         if ((ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
1072                 return ret;
1073
1074         /* Check if the default format descriptor exists. Use the first
1075          * available format otherwise.
1076          */
1077         for (i = video->streaming->nformats; i > 0; --i) {
1078                 format = &video->streaming->format[i-1];
1079                 if (format->index == probe->bFormatIndex)
1080                         break;
1081         }
1082
1083         if (format->nframes == 0) {
1084                 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1085                         "default format.\n");
1086                 return -EINVAL;
1087         }
1088
1089         /* Zero bFrameIndex might be correct. Stream-based formats (including
1090          * MPEG-2 TS and DV) do not support frames but have a dummy frame
1091          * descriptor with bFrameIndex set to zero. If the default frame
1092          * descriptor is not found, use the first avalable frame.
1093          */
1094         for (i = format->nframes; i > 0; --i) {
1095                 frame = &format->frame[i-1];
1096                 if (frame->bFrameIndex == probe->bFrameIndex)
1097                         break;
1098         }
1099
1100         probe->bFormatIndex = format->index;
1101         probe->bFrameIndex = frame->bFrameIndex;
1102
1103         video->streaming->cur_format = format;
1104         video->streaming->cur_frame = frame;
1105         atomic_set(&video->active, 0);
1106
1107         /* Select the video decoding function */
1108         if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1109                 if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1110                         video->decode = uvc_video_decode_isight;
1111                 else if (video->streaming->intf->num_altsetting > 1)
1112                         video->decode = uvc_video_decode_isoc;
1113                 else
1114                         video->decode = uvc_video_decode_bulk;
1115         } else {
1116                 if (video->streaming->intf->num_altsetting == 1)
1117                         video->decode = uvc_video_encode_bulk;
1118                 else {
1119                         uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1120                                 "supported for video output devices.\n");
1121                         return -EINVAL;
1122                 }
1123         }
1124
1125         return 0;
1126 }
1127
1128 /*
1129  * Enable or disable the video stream.
1130  */
1131 int uvc_video_enable(struct uvc_video_device *video, int enable)
1132 {
1133         int ret;
1134
1135         if (!enable) {
1136                 uvc_uninit_video(video, 1);
1137                 usb_set_interface(video->dev->udev,
1138                         video->streaming->intfnum, 0);
1139                 uvc_queue_enable(&video->queue, 0);
1140                 return 0;
1141         }
1142
1143         if ((video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
1144             uvc_no_drop_param)
1145                 video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1146         else
1147                 video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1148
1149         if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
1150                 return ret;
1151
1152         /* Commit the streaming parameters. */
1153         if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0)
1154                 return ret;
1155
1156         return uvc_init_video(video, GFP_KERNEL);
1157 }
1158