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