Merge remote-tracking branch 'remotes/tegra/android-tegra-2.6.36-honeycomb-mr1' into...
[firefly-linux-kernel-4.4.55.git] / drivers / media / video / uvc / uvc_queue.c
1 /*
2  *      uvc_queue.c  --  USB Video Class driver - Buffers management
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/mm.h>
16 #include <linux/list.h>
17 #include <linux/module.h>
18 #include <linux/usb.h>
19 #include <linux/videodev2.h>
20 #include <linux/vmalloc.h>
21 #include <linux/wait.h>
22 #include <asm/atomic.h>
23
24 #include "uvcvideo.h"
25
26 /* ------------------------------------------------------------------------
27  * Video buffers queue management.
28  *
29  * Video queues is initialized by uvc_queue_init(). The function performs
30  * basic initialization of the uvc_video_queue struct and never fails.
31  *
32  * Video buffer allocation and freeing are performed by uvc_alloc_buffers and
33  * uvc_free_buffers respectively. The former acquires the video queue lock,
34  * while the later must be called with the lock held (so that allocation can
35  * free previously allocated buffers). Trying to free buffers that are mapped
36  * to user space will return -EBUSY.
37  *
38  * Video buffers are managed using two queues. However, unlike most USB video
39  * drivers that use an in queue and an out queue, we use a main queue to hold
40  * all queued buffers (both 'empty' and 'done' buffers), and an irq queue to
41  * hold empty buffers. This design (copied from video-buf) minimizes locking
42  * in interrupt, as only one queue is shared between interrupt and user
43  * contexts.
44  *
45  * Use cases
46  * ---------
47  *
48  * Unless stated otherwise, all operations that modify the irq buffers queue
49  * are protected by the irq spinlock.
50  *
51  * 1. The user queues the buffers, starts streaming and dequeues a buffer.
52  *
53  *    The buffers are added to the main and irq queues. Both operations are
54  *    protected by the queue lock, and the later is protected by the irq
55  *    spinlock as well.
56  *
57  *    The completion handler fetches a buffer from the irq queue and fills it
58  *    with video data. If no buffer is available (irq queue empty), the handler
59  *    returns immediately.
60  *
61  *    When the buffer is full, the completion handler removes it from the irq
62  *    queue, marks it as done (UVC_BUF_STATE_DONE) and wakes its wait queue.
63  *    At that point, any process waiting on the buffer will be woken up. If a
64  *    process tries to dequeue a buffer after it has been marked done, the
65  *    dequeing will succeed immediately.
66  *
67  * 2. Buffers are queued, user is waiting on a buffer and the device gets
68  *    disconnected.
69  *
70  *    When the device is disconnected, the kernel calls the completion handler
71  *    with an appropriate status code. The handler marks all buffers in the
72  *    irq queue as being erroneous (UVC_BUF_STATE_ERROR) and wakes them up so
73  *    that any process waiting on a buffer gets woken up.
74  *
75  *    Waking up up the first buffer on the irq list is not enough, as the
76  *    process waiting on the buffer might restart the dequeue operation
77  *    immediately.
78  *
79  */
80
81 void uvc_queue_init(struct uvc_video_queue *queue, enum v4l2_buf_type type,
82                     int drop_corrupted)
83 {
84         mutex_init(&queue->mutex);
85         spin_lock_init(&queue->irqlock);
86         INIT_LIST_HEAD(&queue->mainqueue);
87         INIT_LIST_HEAD(&queue->irqqueue);
88         init_waitqueue_head(&queue->wait);  /* ddl@rock-chips.com : This design copied from video-buf */
89         queue->flags = drop_corrupted ? UVC_QUEUE_DROP_CORRUPTED : 0;
90         queue->type = type;
91 }
92
93 /*
94  * Allocate the video buffers.
95  *
96  * Pages are reserved to make sure they will not be swapped, as they will be
97  * filled in the URB completion handler.
98  *
99  * Buffers will be individually mapped, so they must all be page aligned.
100  */
101 int uvc_alloc_buffers(struct uvc_video_queue *queue, unsigned int nbuffers,
102                 unsigned int buflength)
103 {
104         unsigned int bufsize = PAGE_ALIGN(buflength);
105         unsigned int i;
106         void *mem = NULL;
107         int ret;
108
109         if (nbuffers > UVC_MAX_VIDEO_BUFFERS)
110                 nbuffers = UVC_MAX_VIDEO_BUFFERS;
111
112         mutex_lock(&queue->mutex);
113
114         if ((ret = uvc_free_buffers(queue)) < 0)
115                 goto done;
116
117         /* Bail out if no buffers should be allocated. */
118         if (nbuffers == 0)
119                 goto done;
120
121         /* Decrement the number of buffers until allocation succeeds. */
122         for (; nbuffers > 0; --nbuffers) {
123                 mem = vmalloc_32(nbuffers * bufsize);
124                 if (mem != NULL)
125                         break;
126         }
127
128         if (mem == NULL) {
129                 ret = -ENOMEM;
130                 goto done;
131         }
132
133         for (i = 0; i < nbuffers; ++i) {
134                 memset(&queue->buffer[i], 0, sizeof queue->buffer[i]);
135                 queue->buffer[i].buf.index = i;
136                 queue->buffer[i].buf.m.offset = i * bufsize;
137                 queue->buffer[i].buf.length = buflength;
138                 queue->buffer[i].buf.type = queue->type;
139                 queue->buffer[i].buf.sequence = 0;
140                 queue->buffer[i].buf.field = V4L2_FIELD_NONE;
141                 queue->buffer[i].buf.memory = V4L2_MEMORY_MMAP;
142                 queue->buffer[i].buf.flags = 0;
143                 init_waitqueue_head(&queue->buffer[i].wait);
144         }
145
146         queue->mem = mem;
147         queue->count = nbuffers;
148         queue->buf_size = bufsize;
149         ret = nbuffers;
150
151 done:
152         mutex_unlock(&queue->mutex);
153         return ret;
154 }
155
156 /*
157  * Free the video buffers.
158  *
159  * This function must be called with the queue lock held.
160  */
161 int uvc_free_buffers(struct uvc_video_queue *queue)
162 {
163         unsigned int i;
164
165         for (i = 0; i < queue->count; ++i) {
166                 if (queue->buffer[i].vma_use_count != 0)
167                         return -EBUSY;
168         }
169
170         if (queue->count) {
171                 vfree(queue->mem);
172                 queue->count = 0;
173         }
174
175         return 0;
176 }
177
178 /*
179  * Check if buffers have been allocated.
180  */
181 int uvc_queue_allocated(struct uvc_video_queue *queue)
182 {
183         int allocated;
184
185         mutex_lock(&queue->mutex);
186         allocated = queue->count != 0;
187         mutex_unlock(&queue->mutex);
188
189         return allocated;
190 }
191
192 static void __uvc_query_buffer(struct uvc_buffer *buf,
193                 struct v4l2_buffer *v4l2_buf)
194 {
195         memcpy(v4l2_buf, &buf->buf, sizeof *v4l2_buf);
196
197         if (buf->vma_use_count)
198                 v4l2_buf->flags |= V4L2_BUF_FLAG_MAPPED;
199
200         switch (buf->state) {
201         case UVC_BUF_STATE_ERROR:
202         case UVC_BUF_STATE_DONE:
203                 v4l2_buf->flags |= V4L2_BUF_FLAG_DONE;
204                 break;
205         case UVC_BUF_STATE_QUEUED:
206         case UVC_BUF_STATE_ACTIVE:
207         case UVC_BUF_STATE_READY:
208                 v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
209                 break;
210         case UVC_BUF_STATE_IDLE:
211         default:
212                 break;
213         }
214 }
215
216 int uvc_query_buffer(struct uvc_video_queue *queue,
217                 struct v4l2_buffer *v4l2_buf)
218 {
219         int ret = 0;
220
221         mutex_lock(&queue->mutex);
222         if (v4l2_buf->index >= queue->count) {
223                 ret = -EINVAL;
224                 goto done;
225         }
226
227         __uvc_query_buffer(&queue->buffer[v4l2_buf->index], v4l2_buf);
228
229 done:
230         mutex_unlock(&queue->mutex);
231         return ret;
232 }
233
234 /*
235  * Queue a video buffer. Attempting to queue a buffer that has already been
236  * queued will return -EINVAL.
237  */
238 int uvc_queue_buffer(struct uvc_video_queue *queue,
239         struct v4l2_buffer *v4l2_buf)
240 {
241         struct uvc_buffer *buf;
242         unsigned long flags;
243         int ret = 0;
244
245         uvc_trace(UVC_TRACE_CAPTURE, "Queuing buffer %u.\n", v4l2_buf->index);
246
247         if (v4l2_buf->type != queue->type ||
248             v4l2_buf->memory != V4L2_MEMORY_MMAP) {
249                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer type (%u) "
250                         "and/or memory (%u).\n", v4l2_buf->type,
251                         v4l2_buf->memory);
252                 return -EINVAL;
253         }
254
255         mutex_lock(&queue->mutex);
256         if (v4l2_buf->index >= queue->count) {
257                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Out of range index.\n");
258                 ret = -EINVAL;
259                 goto done;
260         }
261
262         buf = &queue->buffer[v4l2_buf->index];
263         if (buf->state != UVC_BUF_STATE_IDLE) {
264                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer state "
265                         "(%u).\n", buf->state);
266                 ret = -EINVAL;
267                 goto done;
268         }
269
270         if (v4l2_buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT &&
271             v4l2_buf->bytesused > buf->buf.length) {
272                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Bytes used out of bounds.\n");
273                 ret = -EINVAL;
274                 goto done;
275         }
276
277         spin_lock_irqsave(&queue->irqlock, flags);
278         if (queue->flags & UVC_QUEUE_DISCONNECTED) {
279                 spin_unlock_irqrestore(&queue->irqlock, flags);
280                 ret = -ENODEV;
281                 goto done;
282         }
283         buf->state = UVC_BUF_STATE_QUEUED;
284         if (v4l2_buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
285                 buf->buf.bytesused = 0;
286         else
287                 buf->buf.bytesused = v4l2_buf->bytesused;
288
289         list_add_tail(&buf->stream, &queue->mainqueue);
290         list_add_tail(&buf->queue, &queue->irqqueue);
291         spin_unlock_irqrestore(&queue->irqlock, flags);
292
293     wake_up_interruptible_sync(&queue->wait);     /* ddl@rock-chips.com : This design copied from video-buf */
294
295 done:
296         mutex_unlock(&queue->mutex);
297         return ret;
298 }
299
300 static int uvc_queue_waiton(struct uvc_buffer *buf, int nonblocking)
301 {
302         if (nonblocking) {
303                 return (buf->state != UVC_BUF_STATE_QUEUED &&
304                         buf->state != UVC_BUF_STATE_ACTIVE &&
305                         buf->state != UVC_BUF_STATE_READY)
306                         ? 0 : -EAGAIN;
307         }
308 #if 0
309         return wait_event_interruptible(buf->wait,
310                 buf->state != UVC_BUF_STATE_QUEUED &&
311                 buf->state != UVC_BUF_STATE_ACTIVE &&
312                 buf->state != UVC_BUF_STATE_READY);
313 #else
314         /* ddl@rock-chips.com: wait_event_interruptible -> wait_event_interruptible_timeout */
315         return wait_event_interruptible_timeout(buf->wait,
316                 buf->state != UVC_BUF_STATE_QUEUED &&
317                 buf->state != UVC_BUF_STATE_ACTIVE &&
318                 buf->state != UVC_BUF_STATE_READYi,
319                 msecs_to_jiffies(800);
320 }
321
322 /*
323  * Dequeue a video buffer. If nonblocking is false, block until a buffer is
324  * available.
325  */
326 int uvc_dequeue_buffer(struct uvc_video_queue *queue,
327                 struct v4l2_buffer *v4l2_buf, int nonblocking)
328 {
329         struct uvc_buffer *buf;
330         int ret = 0;
331
332         if (v4l2_buf->type != queue->type ||
333             v4l2_buf->memory != V4L2_MEMORY_MMAP) {
334                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer type (%u) "
335                         "and/or memory (%u).\n", v4l2_buf->type,
336                         v4l2_buf->memory);
337                 return -EINVAL;
338         }
339
340         mutex_lock(&queue->mutex);
341     /* ddl@rock-chips.com : This design copied from video-buf */
342 checks:    
343         if (list_empty(&queue->mainqueue)) {
344         if (nonblocking) {
345                         uvc_trace(UVC_TRACE_CAPTURE, "[E] Empty buffer queue.\n");
346                 ret = -EINVAL;
347                 goto done;
348                 } else {
349                     //uvc_trace(UVC_TRACE_CAPTURE, "dequeue_buffer: waiting on buffer\n");
350             printk("dequeue_buffer: waiting on buffer\n");
351                         /* Drop lock to avoid deadlock with qbuf */
352                         mutex_unlock(&queue->mutex);
353
354                         /* Checking list_empty and streaming is safe without
355                          * locks because we goto checks to validate while
356                          * holding locks before proceeding */
357                         ret = wait_event_interruptible(queue->wait,
358                                 ((!list_empty(&queue->mainqueue)) || (!(queue->flags & UVC_QUEUE_STREAMING))));
359                         mutex_lock(&queue->mutex);
360
361                         if (ret)
362                                 goto done;
363
364                         goto checks;
365                 }       
366         }
367
368         buf = list_first_entry(&queue->mainqueue, struct uvc_buffer, stream);
369         if ((ret = uvc_queue_waiton(buf, nonblocking)) <= 0) {
370         /* ddl@rock-chips.com: It is timeout */
371         if (ret == 0) {
372             ret = -EINVAL;
373             printk(KERN_ERR "uvcvideo: uvc_dequeue_buffer is timeout!!");
374         } else {
375             printk(KERN_ERR "uvcvideo: uvc_dequeue_buffer is failed!!(ret:%d)",ret);
376         }
377                 goto done;
378         }
379
380         uvc_trace(UVC_TRACE_CAPTURE, "Dequeuing buffer %u (%u, %u bytes).\n",
381                 buf->buf.index, buf->state, buf->buf.bytesused);
382
383         switch (buf->state) {
384         case UVC_BUF_STATE_ERROR:
385                 uvc_trace(UVC_TRACE_CAPTURE, "[W] Corrupted data "
386                         "(transmission error).\n");
387                 ret = -EIO;
388         case UVC_BUF_STATE_DONE:
389                 buf->state = UVC_BUF_STATE_IDLE;
390                 break;
391
392         case UVC_BUF_STATE_IDLE:
393         case UVC_BUF_STATE_QUEUED:
394         case UVC_BUF_STATE_ACTIVE:
395         case UVC_BUF_STATE_READY:
396         default:
397                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer state %u "
398                         "(driver bug?).\n", buf->state);
399                 ret = -EINVAL;
400                 goto done;
401         }
402
403         list_del(&buf->stream);
404         __uvc_query_buffer(buf, v4l2_buf);
405
406 done:
407         mutex_unlock(&queue->mutex);
408         return ret;
409 }
410
411 /*
412  * Poll the video queue.
413  *
414  * This function implements video queue polling and is intended to be used by
415  * the device poll handler.
416  */
417 unsigned int uvc_queue_poll(struct uvc_video_queue *queue, struct file *file,
418                 poll_table *wait)
419 {
420         struct uvc_buffer *buf;
421         unsigned int mask = 0;
422
423         mutex_lock(&queue->mutex);
424         if (list_empty(&queue->mainqueue)) {
425                 mask |= POLLERR;
426                 goto done;
427         }
428         buf = list_first_entry(&queue->mainqueue, struct uvc_buffer, stream);
429
430         poll_wait(file, &buf->wait, wait);
431         if (buf->state == UVC_BUF_STATE_DONE ||
432             buf->state == UVC_BUF_STATE_ERROR) {
433                 if (queue->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
434                         mask |= POLLIN | POLLRDNORM;
435                 else
436                         mask |= POLLOUT | POLLWRNORM;
437         }
438
439 done:
440         mutex_unlock(&queue->mutex);
441         return mask;
442 }
443
444 /*
445  * Enable or disable the video buffers queue.
446  *
447  * The queue must be enabled before starting video acquisition and must be
448  * disabled after stopping it. This ensures that the video buffers queue
449  * state can be properly initialized before buffers are accessed from the
450  * interrupt handler.
451  *
452  * Enabling the video queue initializes parameters (such as sequence number,
453  * sync pattern, ...). If the queue is already enabled, return -EBUSY.
454  *
455  * Disabling the video queue cancels the queue and removes all buffers from
456  * the main queue.
457  *
458  * This function can't be called from interrupt context. Use
459  * uvc_queue_cancel() instead.
460  */
461 int uvc_queue_enable(struct uvc_video_queue *queue, int enable)
462 {
463         unsigned int i;
464         int ret = 0;
465
466         mutex_lock(&queue->mutex);
467         if (enable) {
468                 if (uvc_queue_streaming(queue)) {
469                         ret = -EBUSY;
470                         goto done;
471                 }
472                 queue->sequence = 0;
473                 queue->flags |= UVC_QUEUE_STREAMING;
474                 queue->buf_used = 0;
475         } else {
476                 uvc_queue_cancel(queue, 0);
477                 INIT_LIST_HEAD(&queue->mainqueue);
478
479                 for (i = 0; i < queue->count; ++i) {
480                         queue->buffer[i].error = 0;
481                         queue->buffer[i].state = UVC_BUF_STATE_IDLE;
482                 }
483
484                 queue->flags &= ~UVC_QUEUE_STREAMING;
485         }
486
487 done:
488         mutex_unlock(&queue->mutex);
489         return ret;
490 }
491
492 /*
493  * Cancel the video buffers queue.
494  *
495  * Cancelling the queue marks all buffers on the irq queue as erroneous,
496  * wakes them up and removes them from the queue.
497  *
498  * If the disconnect parameter is set, further calls to uvc_queue_buffer will
499  * fail with -ENODEV.
500  *
501  * This function acquires the irq spinlock and can be called from interrupt
502  * context.
503  */
504 void uvc_queue_cancel(struct uvc_video_queue *queue, int disconnect)
505 {
506         struct uvc_buffer *buf;
507         unsigned long flags;
508
509     wake_up_interruptible_sync(&queue->wait);           /* ddl@rock-chips.com : This design copied from video-buf */
510
511         spin_lock_irqsave(&queue->irqlock, flags);
512         while (!list_empty(&queue->irqqueue)) {
513                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
514                                        queue);
515                 list_del(&buf->queue);
516                 buf->state = UVC_BUF_STATE_ERROR;
517                 wake_up(&buf->wait);
518         }
519         /* This must be protected by the irqlock spinlock to avoid race
520          * conditions between uvc_queue_buffer and the disconnection event that
521          * could result in an interruptible wait in uvc_dequeue_buffer. Do not
522          * blindly replace this logic by checking for the UVC_DEV_DISCONNECTED
523          * state outside the queue code.
524          */
525         if (disconnect)
526                 queue->flags |= UVC_QUEUE_DISCONNECTED;
527         spin_unlock_irqrestore(&queue->irqlock, flags);
528 }
529
530 struct uvc_buffer *uvc_queue_next_buffer(struct uvc_video_queue *queue,
531                 struct uvc_buffer *buf)
532 {
533         struct uvc_buffer *nextbuf;
534         unsigned long flags;
535
536         if ((queue->flags & UVC_QUEUE_DROP_CORRUPTED) && buf->error) {
537                 buf->error = 0;
538                 buf->state = UVC_BUF_STATE_QUEUED;
539                 buf->buf.bytesused = 0;
540                 return buf;
541         }
542
543         spin_lock_irqsave(&queue->irqlock, flags);
544         list_del(&buf->queue);
545         buf->error = 0;
546         buf->state = UVC_BUF_STATE_DONE;
547         if (!list_empty(&queue->irqqueue))
548                 nextbuf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
549                                            queue);
550         else
551                 nextbuf = NULL;
552         spin_unlock_irqrestore(&queue->irqlock, flags);
553
554         buf->buf.sequence = queue->sequence++;
555
556         wake_up(&buf->wait);
557         return nextbuf;
558 }
559