Merge branch 'kconfig-text' into release
[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         /* Perform probing. The device should adjust the requested values
297          * according to its capabilities. However, some devices, namely the
298          * first generation UVC Logitech webcams, don't implement the Video
299          * Probe control properly, and just return the needed bandwidth. For
300          * that reason, if the needed bandwidth exceeds the maximum available
301          * bandwidth, try to lower the quality.
302          */
303         ret = uvc_set_video_ctrl(stream, probe, 1);
304         if (ret < 0)
305                 goto done;
306
307         /* Get the minimum and maximum values for compression settings. */
308         if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
309                 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
310                 if (ret < 0)
311                         goto done;
312                 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
313                 if (ret < 0)
314                         goto done;
315
316                 probe->wCompQuality = probe_max.wCompQuality;
317         }
318
319         for (i = 0; i < 2; ++i) {
320                 ret = uvc_set_video_ctrl(stream, probe, 1);
321                 if (ret < 0)
322                         goto done;
323                 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
324                 if (ret < 0)
325                         goto done;
326
327                 if (stream->intf->num_altsetting == 1)
328                         break;
329
330                 bandwidth = probe->dwMaxPayloadTransferSize;
331                 if (bandwidth <= stream->maxpsize)
332                         break;
333
334                 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
335                         ret = -ENOSPC;
336                         goto done;
337                 }
338
339                 /* TODO: negotiate compression parameters */
340                 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
341                 probe->wPFrameRate = probe_min.wPFrameRate;
342                 probe->wCompQuality = probe_max.wCompQuality;
343                 probe->wCompWindowSize = probe_min.wCompWindowSize;
344         }
345
346 done:
347         return ret;
348 }
349
350 int uvc_commit_video(struct uvc_streaming *stream,
351         struct uvc_streaming_control *probe)
352 {
353         return uvc_set_video_ctrl(stream, probe, 0);
354 }
355
356 /* ------------------------------------------------------------------------
357  * Video codecs
358  */
359
360 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
361 #define UVC_STREAM_EOH  (1 << 7)
362 #define UVC_STREAM_ERR  (1 << 6)
363 #define UVC_STREAM_STI  (1 << 5)
364 #define UVC_STREAM_RES  (1 << 4)
365 #define UVC_STREAM_SCR  (1 << 3)
366 #define UVC_STREAM_PTS  (1 << 2)
367 #define UVC_STREAM_EOF  (1 << 1)
368 #define UVC_STREAM_FID  (1 << 0)
369
370 /* Video payload decoding is handled by uvc_video_decode_start(),
371  * uvc_video_decode_data() and uvc_video_decode_end().
372  *
373  * uvc_video_decode_start is called with URB data at the start of a bulk or
374  * isochronous payload. It processes header data and returns the header size
375  * in bytes if successful. If an error occurs, it returns a negative error
376  * code. The following error codes have special meanings.
377  *
378  * - EAGAIN informs the caller that the current video buffer should be marked
379  *   as done, and that the function should be called again with the same data
380  *   and a new video buffer. This is used when end of frame conditions can be
381  *   reliably detected at the beginning of the next frame only.
382  *
383  * If an error other than -EAGAIN is returned, the caller will drop the current
384  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
385  * made until the next payload. -ENODATA can be used to drop the current
386  * payload if no other error code is appropriate.
387  *
388  * uvc_video_decode_data is called for every URB with URB data. It copies the
389  * data to the video buffer.
390  *
391  * uvc_video_decode_end is called with header data at the end of a bulk or
392  * isochronous payload. It performs any additional header data processing and
393  * returns 0 or a negative error code if an error occured. As header data have
394  * already been processed by uvc_video_decode_start, this functions isn't
395  * required to perform sanity checks a second time.
396  *
397  * For isochronous transfers where a payload is always transfered in a single
398  * URB, the three functions will be called in a row.
399  *
400  * To let the decoder process header data and update its internal state even
401  * when no video buffer is available, uvc_video_decode_start must be prepared
402  * to be called with a NULL buf parameter. uvc_video_decode_data and
403  * uvc_video_decode_end will never be called with a NULL buffer.
404  */
405 static int uvc_video_decode_start(struct uvc_streaming *stream,
406                 struct uvc_buffer *buf, const __u8 *data, int len)
407 {
408         __u8 fid;
409
410         /* Sanity checks:
411          * - packet must be at least 2 bytes long
412          * - bHeaderLength value must be at least 2 bytes (see above)
413          * - bHeaderLength value can't be larger than the packet size.
414          */
415         if (len < 2 || data[0] < 2 || data[0] > len)
416                 return -EINVAL;
417
418         /* Skip payloads marked with the error bit ("error frames"). */
419         if (data[1] & UVC_STREAM_ERR) {
420                 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
421                           "set).\n");
422                 return -ENODATA;
423         }
424
425         fid = data[1] & UVC_STREAM_FID;
426
427         /* Increase the sequence number regardless of any buffer states, so
428          * that discontinuous sequence numbers always indicate lost frames.
429          */
430         if (stream->last_fid != fid)
431                 stream->sequence++;
432
433         /* Store the payload FID bit and return immediately when the buffer is
434          * NULL.
435          */
436         if (buf == NULL) {
437                 stream->last_fid = fid;
438                 return -ENODATA;
439         }
440
441         /* Synchronize to the input stream by waiting for the FID bit to be
442          * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
443          * stream->last_fid is initialized to -1, so the first isochronous
444          * frame will always be in sync.
445          *
446          * If the device doesn't toggle the FID bit, invert stream->last_fid
447          * when the EOF bit is set to force synchronisation on the next packet.
448          */
449         if (buf->state != UVC_BUF_STATE_ACTIVE) {
450                 struct timespec ts;
451
452                 if (fid == stream->last_fid) {
453                         uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
454                                 "sync).\n");
455                         if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
456                             (data[1] & UVC_STREAM_EOF))
457                                 stream->last_fid ^= UVC_STREAM_FID;
458                         return -ENODATA;
459                 }
460
461                 if (uvc_clock_param == CLOCK_MONOTONIC)
462                         ktime_get_ts(&ts);
463                 else
464                         ktime_get_real_ts(&ts);
465
466                 buf->buf.sequence = stream->sequence;
467                 buf->buf.timestamp.tv_sec = ts.tv_sec;
468                 buf->buf.timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
469
470                 /* TODO: Handle PTS and SCR. */
471                 buf->state = UVC_BUF_STATE_ACTIVE;
472         }
473
474         /* Mark the buffer as done if we're at the beginning of a new frame.
475          * End of frame detection is better implemented by checking the EOF
476          * bit (FID bit toggling is delayed by one frame compared to the EOF
477          * bit), but some devices don't set the bit at end of frame (and the
478          * last payload can be lost anyway). We thus must check if the FID has
479          * been toggled.
480          *
481          * stream->last_fid is initialized to -1, so the first isochronous
482          * frame will never trigger an end of frame detection.
483          *
484          * Empty buffers (bytesused == 0) don't trigger end of frame detection
485          * as it doesn't make sense to return an empty buffer. This also
486          * avoids detecting end of frame conditions at FID toggling if the
487          * previous payload had the EOF bit set.
488          */
489         if (fid != stream->last_fid && buf->buf.bytesused != 0) {
490                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
491                                 "toggled).\n");
492                 buf->state = UVC_BUF_STATE_READY;
493                 return -EAGAIN;
494         }
495
496         stream->last_fid = fid;
497
498         return data[0];
499 }
500
501 static void uvc_video_decode_data(struct uvc_streaming *stream,
502                 struct uvc_buffer *buf, const __u8 *data, int len)
503 {
504         struct uvc_video_queue *queue = &stream->queue;
505         unsigned int maxlen, nbytes;
506         void *mem;
507
508         if (len <= 0)
509                 return;
510
511         /* Copy the video data to the buffer. */
512         maxlen = buf->buf.length - buf->buf.bytesused;
513         mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
514         nbytes = min((unsigned int)len, maxlen);
515         memcpy(mem, data, nbytes);
516         buf->buf.bytesused += nbytes;
517
518         /* Complete the current frame if the buffer size was exceeded. */
519         if (len > maxlen) {
520                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
521                 buf->state = UVC_BUF_STATE_READY;
522         }
523 }
524
525 static void uvc_video_decode_end(struct uvc_streaming *stream,
526                 struct uvc_buffer *buf, const __u8 *data, int len)
527 {
528         /* Mark the buffer as done if the EOF marker is set. */
529         if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
530                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
531                 if (data[0] == len)
532                         uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
533                 buf->state = UVC_BUF_STATE_READY;
534                 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
535                         stream->last_fid ^= UVC_STREAM_FID;
536         }
537 }
538
539 /* Video payload encoding is handled by uvc_video_encode_header() and
540  * uvc_video_encode_data(). Only bulk transfers are currently supported.
541  *
542  * uvc_video_encode_header is called at the start of a payload. It adds header
543  * data to the transfer buffer and returns the header size. As the only known
544  * UVC output device transfers a whole frame in a single payload, the EOF bit
545  * is always set in the header.
546  *
547  * uvc_video_encode_data is called for every URB and copies the data from the
548  * video buffer to the transfer buffer.
549  */
550 static int uvc_video_encode_header(struct uvc_streaming *stream,
551                 struct uvc_buffer *buf, __u8 *data, int len)
552 {
553         data[0] = 2;    /* Header length */
554         data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
555                 | (stream->last_fid & UVC_STREAM_FID);
556         return 2;
557 }
558
559 static int uvc_video_encode_data(struct uvc_streaming *stream,
560                 struct uvc_buffer *buf, __u8 *data, int len)
561 {
562         struct uvc_video_queue *queue = &stream->queue;
563         unsigned int nbytes;
564         void *mem;
565
566         /* Copy video data to the URB buffer. */
567         mem = queue->mem + buf->buf.m.offset + queue->buf_used;
568         nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
569         nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
570                         nbytes);
571         memcpy(data, mem, nbytes);
572
573         queue->buf_used += nbytes;
574
575         return nbytes;
576 }
577
578 /* ------------------------------------------------------------------------
579  * URB handling
580  */
581
582 /*
583  * Completion handler for video URBs.
584  */
585 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
586         struct uvc_buffer *buf)
587 {
588         u8 *mem;
589         int ret, i;
590
591         for (i = 0; i < urb->number_of_packets; ++i) {
592                 if (urb->iso_frame_desc[i].status < 0) {
593                         uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
594                                 "lost (%d).\n", urb->iso_frame_desc[i].status);
595                         /* Mark the buffer as faulty. */
596                         if (buf != NULL)
597                                 buf->error = 1;
598                         continue;
599                 }
600
601                 /* Decode the payload header. */
602                 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
603                 do {
604                         ret = uvc_video_decode_start(stream, buf, mem,
605                                 urb->iso_frame_desc[i].actual_length);
606                         if (ret == -EAGAIN)
607                                 buf = uvc_queue_next_buffer(&stream->queue,
608                                                             buf);
609                 } while (ret == -EAGAIN);
610
611                 if (ret < 0)
612                         continue;
613
614                 /* Decode the payload data. */
615                 uvc_video_decode_data(stream, buf, mem + ret,
616                         urb->iso_frame_desc[i].actual_length - ret);
617
618                 /* Process the header again. */
619                 uvc_video_decode_end(stream, buf, mem,
620                         urb->iso_frame_desc[i].actual_length);
621
622                 if (buf->state == UVC_BUF_STATE_READY) {
623                         if (buf->buf.length != buf->buf.bytesused &&
624                             !(stream->cur_format->flags &
625                               UVC_FMT_FLAG_COMPRESSED))
626                                 buf->error = 1;
627
628                         buf = uvc_queue_next_buffer(&stream->queue, buf);
629                 }
630         }
631 }
632
633 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
634         struct uvc_buffer *buf)
635 {
636         u8 *mem;
637         int len, ret;
638
639         if (urb->actual_length == 0)
640                 return;
641
642         mem = urb->transfer_buffer;
643         len = urb->actual_length;
644         stream->bulk.payload_size += len;
645
646         /* If the URB is the first of its payload, decode and save the
647          * header.
648          */
649         if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
650                 do {
651                         ret = uvc_video_decode_start(stream, buf, mem, len);
652                         if (ret == -EAGAIN)
653                                 buf = uvc_queue_next_buffer(&stream->queue,
654                                                             buf);
655                 } while (ret == -EAGAIN);
656
657                 /* If an error occured skip the rest of the payload. */
658                 if (ret < 0 || buf == NULL) {
659                         stream->bulk.skip_payload = 1;
660                 } else {
661                         memcpy(stream->bulk.header, mem, ret);
662                         stream->bulk.header_size = ret;
663
664                         mem += ret;
665                         len -= ret;
666                 }
667         }
668
669         /* The buffer queue might have been cancelled while a bulk transfer
670          * was in progress, so we can reach here with buf equal to NULL. Make
671          * sure buf is never dereferenced if NULL.
672          */
673
674         /* Process video data. */
675         if (!stream->bulk.skip_payload && buf != NULL)
676                 uvc_video_decode_data(stream, buf, mem, len);
677
678         /* Detect the payload end by a URB smaller than the maximum size (or
679          * a payload size equal to the maximum) and process the header again.
680          */
681         if (urb->actual_length < urb->transfer_buffer_length ||
682             stream->bulk.payload_size >= stream->bulk.max_payload_size) {
683                 if (!stream->bulk.skip_payload && buf != NULL) {
684                         uvc_video_decode_end(stream, buf, stream->bulk.header,
685                                 stream->bulk.payload_size);
686                         if (buf->state == UVC_BUF_STATE_READY)
687                                 buf = uvc_queue_next_buffer(&stream->queue,
688                                                             buf);
689                 }
690
691                 stream->bulk.header_size = 0;
692                 stream->bulk.skip_payload = 0;
693                 stream->bulk.payload_size = 0;
694         }
695 }
696
697 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
698         struct uvc_buffer *buf)
699 {
700         u8 *mem = urb->transfer_buffer;
701         int len = stream->urb_size, ret;
702
703         if (buf == NULL) {
704                 urb->transfer_buffer_length = 0;
705                 return;
706         }
707
708         /* If the URB is the first of its payload, add the header. */
709         if (stream->bulk.header_size == 0) {
710                 ret = uvc_video_encode_header(stream, buf, mem, len);
711                 stream->bulk.header_size = ret;
712                 stream->bulk.payload_size += ret;
713                 mem += ret;
714                 len -= ret;
715         }
716
717         /* Process video data. */
718         ret = uvc_video_encode_data(stream, buf, mem, len);
719
720         stream->bulk.payload_size += ret;
721         len -= ret;
722
723         if (buf->buf.bytesused == stream->queue.buf_used ||
724             stream->bulk.payload_size == stream->bulk.max_payload_size) {
725                 if (buf->buf.bytesused == stream->queue.buf_used) {
726                         stream->queue.buf_used = 0;
727                         buf->state = UVC_BUF_STATE_READY;
728                         buf->buf.sequence = ++stream->sequence;
729                         uvc_queue_next_buffer(&stream->queue, buf);
730                         stream->last_fid ^= UVC_STREAM_FID;
731                 }
732
733                 stream->bulk.header_size = 0;
734                 stream->bulk.payload_size = 0;
735         }
736
737         urb->transfer_buffer_length = stream->urb_size - len;
738 }
739
740 static void uvc_video_complete(struct urb *urb)
741 {
742         struct uvc_streaming *stream = urb->context;
743         struct uvc_video_queue *queue = &stream->queue;
744         struct uvc_buffer *buf = NULL;
745         unsigned long flags;
746         int ret;
747
748         switch (urb->status) {
749         case 0:
750                 break;
751
752         default:
753                 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
754                         "completion handler.\n", urb->status);
755
756         case -ENOENT:           /* usb_kill_urb() called. */
757                 if (stream->frozen)
758                         return;
759
760         case -ECONNRESET:       /* usb_unlink_urb() called. */
761         case -ESHUTDOWN:        /* The endpoint is being disabled. */
762                 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
763                 return;
764         }
765
766         spin_lock_irqsave(&queue->irqlock, flags);
767         if (!list_empty(&queue->irqqueue))
768                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
769                                        queue);
770         spin_unlock_irqrestore(&queue->irqlock, flags);
771
772         stream->decode(urb, stream, buf);
773
774         if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
775                 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
776                         ret);
777         }
778 }
779
780 /*
781  * Free transfer buffers.
782  */
783 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
784 {
785         unsigned int i;
786
787         for (i = 0; i < UVC_URBS; ++i) {
788                 if (stream->urb_buffer[i]) {
789                         usb_free_coherent(stream->dev->udev, stream->urb_size,
790                                 stream->urb_buffer[i], stream->urb_dma[i]);
791                         stream->urb_buffer[i] = NULL;
792                 }
793         }
794
795         stream->urb_size = 0;
796 }
797
798 /*
799  * Allocate transfer buffers. This function can be called with buffers
800  * already allocated when resuming from suspend, in which case it will
801  * return without touching the buffers.
802  *
803  * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
804  * system is too low on memory try successively smaller numbers of packets
805  * until allocation succeeds.
806  *
807  * Return the number of allocated packets on success or 0 when out of memory.
808  */
809 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
810         unsigned int size, unsigned int psize, gfp_t gfp_flags)
811 {
812         unsigned int npackets;
813         unsigned int i;
814
815         /* Buffers are already allocated, bail out. */
816         if (stream->urb_size)
817                 return stream->urb_size / psize;
818
819         /* Compute the number of packets. Bulk endpoints might transfer UVC
820          * payloads accross multiple URBs.
821          */
822         npackets = DIV_ROUND_UP(size, psize);
823         if (npackets > UVC_MAX_PACKETS)
824                 npackets = UVC_MAX_PACKETS;
825
826         /* Retry allocations until one succeed. */
827         for (; npackets > 1; npackets /= 2) {
828                 for (i = 0; i < UVC_URBS; ++i) {
829                         stream->urb_size = psize * npackets;
830                         stream->urb_buffer[i] = usb_alloc_coherent(
831                                 stream->dev->udev, stream->urb_size,
832                                 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
833                         if (!stream->urb_buffer[i]) {
834                                 uvc_free_urb_buffers(stream);
835                                 break;
836                         }
837                 }
838
839                 if (i == UVC_URBS) {
840                         uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
841                                 "of %ux%u bytes each.\n", UVC_URBS, npackets,
842                                 psize);
843                         return npackets;
844                 }
845         }
846
847         uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
848                 "per packet).\n", psize);
849         return 0;
850 }
851
852 /*
853  * Uninitialize isochronous/bulk URBs and free transfer buffers.
854  */
855 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
856 {
857         struct urb *urb;
858         unsigned int i;
859
860         for (i = 0; i < UVC_URBS; ++i) {
861                 urb = stream->urb[i];
862                 if (urb == NULL)
863                         continue;
864
865                 usb_kill_urb(urb);
866                 usb_free_urb(urb);
867                 stream->urb[i] = NULL;
868         }
869
870         if (free_buffers)
871                 uvc_free_urb_buffers(stream);
872 }
873
874 /*
875  * Initialize isochronous URBs and allocate transfer buffers. The packet size
876  * is given by the endpoint.
877  */
878 static int uvc_init_video_isoc(struct uvc_streaming *stream,
879         struct usb_host_endpoint *ep, gfp_t gfp_flags)
880 {
881         struct urb *urb;
882         unsigned int npackets, i, j;
883         u16 psize;
884         u32 size;
885
886         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
887         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
888         size = stream->ctrl.dwMaxVideoFrameSize;
889
890         npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
891         if (npackets == 0)
892                 return -ENOMEM;
893
894         size = npackets * psize;
895
896         for (i = 0; i < UVC_URBS; ++i) {
897                 urb = usb_alloc_urb(npackets, gfp_flags);
898                 if (urb == NULL) {
899                         uvc_uninit_video(stream, 1);
900                         return -ENOMEM;
901                 }
902
903                 urb->dev = stream->dev->udev;
904                 urb->context = stream;
905                 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
906                                 ep->desc.bEndpointAddress);
907                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
908                 urb->interval = ep->desc.bInterval;
909                 urb->transfer_buffer = stream->urb_buffer[i];
910                 urb->transfer_dma = stream->urb_dma[i];
911                 urb->complete = uvc_video_complete;
912                 urb->number_of_packets = npackets;
913                 urb->transfer_buffer_length = size;
914
915                 for (j = 0; j < npackets; ++j) {
916                         urb->iso_frame_desc[j].offset = j * psize;
917                         urb->iso_frame_desc[j].length = psize;
918                 }
919
920                 stream->urb[i] = urb;
921         }
922
923         return 0;
924 }
925
926 /*
927  * Initialize bulk URBs and allocate transfer buffers. The packet size is
928  * given by the endpoint.
929  */
930 static int uvc_init_video_bulk(struct uvc_streaming *stream,
931         struct usb_host_endpoint *ep, gfp_t gfp_flags)
932 {
933         struct urb *urb;
934         unsigned int npackets, pipe, i;
935         u16 psize;
936         u32 size;
937
938         psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
939         size = stream->ctrl.dwMaxPayloadTransferSize;
940         stream->bulk.max_payload_size = size;
941
942         npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
943         if (npackets == 0)
944                 return -ENOMEM;
945
946         size = npackets * psize;
947
948         if (usb_endpoint_dir_in(&ep->desc))
949                 pipe = usb_rcvbulkpipe(stream->dev->udev,
950                                        ep->desc.bEndpointAddress);
951         else
952                 pipe = usb_sndbulkpipe(stream->dev->udev,
953                                        ep->desc.bEndpointAddress);
954
955         if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
956                 size = 0;
957
958         for (i = 0; i < UVC_URBS; ++i) {
959                 urb = usb_alloc_urb(0, gfp_flags);
960                 if (urb == NULL) {
961                         uvc_uninit_video(stream, 1);
962                         return -ENOMEM;
963                 }
964
965                 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
966                         stream->urb_buffer[i], size, uvc_video_complete,
967                         stream);
968                 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
969                 urb->transfer_dma = stream->urb_dma[i];
970
971                 stream->urb[i] = urb;
972         }
973
974         return 0;
975 }
976
977 /*
978  * Initialize isochronous/bulk URBs and allocate transfer buffers.
979  */
980 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
981 {
982         struct usb_interface *intf = stream->intf;
983         struct usb_host_endpoint *ep;
984         unsigned int i;
985         int ret;
986
987         stream->sequence = -1;
988         stream->last_fid = -1;
989         stream->bulk.header_size = 0;
990         stream->bulk.skip_payload = 0;
991         stream->bulk.payload_size = 0;
992
993         if (intf->num_altsetting > 1) {
994                 struct usb_host_endpoint *best_ep = NULL;
995                 unsigned int best_psize = 3 * 1024;
996                 unsigned int bandwidth;
997                 unsigned int uninitialized_var(altsetting);
998                 int intfnum = stream->intfnum;
999
1000                 /* Isochronous endpoint, select the alternate setting. */
1001                 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1002
1003                 if (bandwidth == 0) {
1004                         uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1005                                 "bandwidth, defaulting to lowest.\n");
1006                         bandwidth = 1;
1007                 } else {
1008                         uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1009                                 "B/frame bandwidth.\n", bandwidth);
1010                 }
1011
1012                 for (i = 0; i < intf->num_altsetting; ++i) {
1013                         struct usb_host_interface *alts;
1014                         unsigned int psize;
1015
1016                         alts = &intf->altsetting[i];
1017                         ep = uvc_find_endpoint(alts,
1018                                 stream->header.bEndpointAddress);
1019                         if (ep == NULL)
1020                                 continue;
1021
1022                         /* Check if the bandwidth is high enough. */
1023                         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
1024                         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1025                         if (psize >= bandwidth && psize <= best_psize) {
1026                                 altsetting = i;
1027                                 best_psize = psize;
1028                                 best_ep = ep;
1029                         }
1030                 }
1031
1032                 if (best_ep == NULL) {
1033                         uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1034                                 "for requested bandwidth.\n");
1035                         return -EIO;
1036                 }
1037
1038                 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1039                         "(%u B/frame bandwidth).\n", altsetting, best_psize);
1040
1041                 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1042                 if (ret < 0)
1043                         return ret;
1044
1045                 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1046         } else {
1047                 /* Bulk endpoint, proceed to URB initialization. */
1048                 ep = uvc_find_endpoint(&intf->altsetting[0],
1049                                 stream->header.bEndpointAddress);
1050                 if (ep == NULL)
1051                         return -EIO;
1052
1053                 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1054         }
1055
1056         if (ret < 0)
1057                 return ret;
1058
1059         /* Submit the URBs. */
1060         for (i = 0; i < UVC_URBS; ++i) {
1061                 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1062                 if (ret < 0) {
1063                         uvc_printk(KERN_ERR, "Failed to submit URB %u "
1064                                         "(%d).\n", i, ret);
1065                         uvc_uninit_video(stream, 1);
1066                         return ret;
1067                 }
1068         }
1069
1070         return 0;
1071 }
1072
1073 /* --------------------------------------------------------------------------
1074  * Suspend/resume
1075  */
1076
1077 /*
1078  * Stop streaming without disabling the video queue.
1079  *
1080  * To let userspace applications resume without trouble, we must not touch the
1081  * video buffers in any way. We mark the device as frozen to make sure the URB
1082  * completion handler won't try to cancel the queue when we kill the URBs.
1083  */
1084 int uvc_video_suspend(struct uvc_streaming *stream)
1085 {
1086         if (!uvc_queue_streaming(&stream->queue))
1087                 return 0;
1088
1089         stream->frozen = 1;
1090         uvc_uninit_video(stream, 0);
1091         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1092         return 0;
1093 }
1094
1095 /*
1096  * Reconfigure the video interface and restart streaming if it was enabled
1097  * before suspend.
1098  *
1099  * If an error occurs, disable the video queue. This will wake all pending
1100  * buffers, making sure userspace applications are notified of the problem
1101  * instead of waiting forever.
1102  */
1103 int uvc_video_resume(struct uvc_streaming *stream)
1104 {
1105         int ret;
1106
1107         stream->frozen = 0;
1108
1109         ret = uvc_commit_video(stream, &stream->ctrl);
1110         if (ret < 0) {
1111                 uvc_queue_enable(&stream->queue, 0);
1112                 return ret;
1113         }
1114
1115         if (!uvc_queue_streaming(&stream->queue))
1116                 return 0;
1117
1118         ret = uvc_init_video(stream, GFP_NOIO);
1119         if (ret < 0)
1120                 uvc_queue_enable(&stream->queue, 0);
1121
1122         return ret;
1123 }
1124
1125 /* ------------------------------------------------------------------------
1126  * Video device
1127  */
1128
1129 /*
1130  * Initialize the UVC video device by switching to alternate setting 0 and
1131  * retrieve the default format.
1132  *
1133  * Some cameras (namely the Fuji Finepix) set the format and frame
1134  * indexes to zero. The UVC standard doesn't clearly make this a spec
1135  * violation, so try to silently fix the values if possible.
1136  *
1137  * This function is called before registering the device with V4L.
1138  */
1139 int uvc_video_init(struct uvc_streaming *stream)
1140 {
1141         struct uvc_streaming_control *probe = &stream->ctrl;
1142         struct uvc_format *format = NULL;
1143         struct uvc_frame *frame = NULL;
1144         unsigned int i;
1145         int ret;
1146
1147         if (stream->nformats == 0) {
1148                 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1149                 return -EINVAL;
1150         }
1151
1152         atomic_set(&stream->active, 0);
1153
1154         /* Initialize the video buffers queue. */
1155         uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1156
1157         /* Alternate setting 0 should be the default, yet the XBox Live Vision
1158          * Cam (and possibly other devices) crash or otherwise misbehave if
1159          * they don't receive a SET_INTERFACE request before any other video
1160          * control request.
1161          */
1162         usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1163
1164         /* Set the streaming probe control with default streaming parameters
1165          * retrieved from the device. Webcams that don't suport GET_DEF
1166          * requests on the probe control will just keep their current streaming
1167          * parameters.
1168          */
1169         if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1170                 uvc_set_video_ctrl(stream, probe, 1);
1171
1172         /* Initialize the streaming parameters with the probe control current
1173          * value. This makes sure SET_CUR requests on the streaming commit
1174          * control will always use values retrieved from a successful GET_CUR
1175          * request on the probe control, as required by the UVC specification.
1176          */
1177         ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1178         if (ret < 0)
1179                 return ret;
1180
1181         /* Check if the default format descriptor exists. Use the first
1182          * available format otherwise.
1183          */
1184         for (i = stream->nformats; i > 0; --i) {
1185                 format = &stream->format[i-1];
1186                 if (format->index == probe->bFormatIndex)
1187                         break;
1188         }
1189
1190         if (format->nframes == 0) {
1191                 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1192                         "default format.\n");
1193                 return -EINVAL;
1194         }
1195
1196         /* Zero bFrameIndex might be correct. Stream-based formats (including
1197          * MPEG-2 TS and DV) do not support frames but have a dummy frame
1198          * descriptor with bFrameIndex set to zero. If the default frame
1199          * descriptor is not found, use the first available frame.
1200          */
1201         for (i = format->nframes; i > 0; --i) {
1202                 frame = &format->frame[i-1];
1203                 if (frame->bFrameIndex == probe->bFrameIndex)
1204                         break;
1205         }
1206
1207         probe->bFormatIndex = format->index;
1208         probe->bFrameIndex = frame->bFrameIndex;
1209
1210         stream->cur_format = format;
1211         stream->cur_frame = frame;
1212
1213         /* Select the video decoding function */
1214         if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1215                 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1216                         stream->decode = uvc_video_decode_isight;
1217                 else if (stream->intf->num_altsetting > 1)
1218                         stream->decode = uvc_video_decode_isoc;
1219                 else
1220                         stream->decode = uvc_video_decode_bulk;
1221         } else {
1222                 if (stream->intf->num_altsetting == 1)
1223                         stream->decode = uvc_video_encode_bulk;
1224                 else {
1225                         uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1226                                 "supported for video output devices.\n");
1227                         return -EINVAL;
1228                 }
1229         }
1230
1231         return 0;
1232 }
1233
1234 /*
1235  * Enable or disable the video stream.
1236  */
1237 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1238 {
1239         int ret;
1240
1241         if (!enable) {
1242                 uvc_uninit_video(stream, 1);
1243                 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1244                 uvc_queue_enable(&stream->queue, 0);
1245                 return 0;
1246         }
1247
1248         ret = uvc_queue_enable(&stream->queue, 1);
1249         if (ret < 0)
1250                 return ret;
1251
1252         /* Commit the streaming parameters. */
1253         ret = uvc_commit_video(stream, &stream->ctrl);
1254         if (ret < 0)
1255                 return ret;
1256
1257         return uvc_init_video(stream, GFP_KERNEL);
1258 }
1259