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