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