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