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