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