Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/linville/wirel...
[pandora-kernel.git] / drivers / media / video / uvc / uvc_queue.c
1 /*
2  *      uvc_queue.c  --  USB Video Class driver - Buffers management
3  *
4  *      Copyright (C) 2005-2010
5  *          Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6  *
7  *      This program is free software; you can redistribute it and/or modify
8  *      it under the terms of the GNU General Public License as published by
9  *      the Free Software Foundation; either version 2 of the License, or
10  *      (at your option) any later version.
11  *
12  */
13
14 #include <linux/kernel.h>
15 #include <linux/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         queue->flags = drop_corrupted ? UVC_QUEUE_DROP_CORRUPTED : 0;
89         queue->type = type;
90 }
91
92 /*
93  * Free the video buffers.
94  *
95  * This function must be called with the queue lock held.
96  */
97 static int __uvc_free_buffers(struct uvc_video_queue *queue)
98 {
99         unsigned int i;
100
101         for (i = 0; i < queue->count; ++i) {
102                 if (queue->buffer[i].vma_use_count != 0)
103                         return -EBUSY;
104         }
105
106         if (queue->count) {
107                 vfree(queue->mem);
108                 queue->count = 0;
109         }
110
111         return 0;
112 }
113
114 int uvc_free_buffers(struct uvc_video_queue *queue)
115 {
116         int ret;
117
118         mutex_lock(&queue->mutex);
119         ret = __uvc_free_buffers(queue);
120         mutex_unlock(&queue->mutex);
121
122         return ret;
123 }
124
125 /*
126  * Allocate the video buffers.
127  *
128  * Pages are reserved to make sure they will not be swapped, as they will be
129  * filled in the URB completion handler.
130  *
131  * Buffers will be individually mapped, so they must all be page aligned.
132  */
133 int uvc_alloc_buffers(struct uvc_video_queue *queue, unsigned int nbuffers,
134                 unsigned int buflength)
135 {
136         unsigned int bufsize = PAGE_ALIGN(buflength);
137         unsigned int i;
138         void *mem = NULL;
139         int ret;
140
141         if (nbuffers > UVC_MAX_VIDEO_BUFFERS)
142                 nbuffers = UVC_MAX_VIDEO_BUFFERS;
143
144         mutex_lock(&queue->mutex);
145
146         if ((ret = __uvc_free_buffers(queue)) < 0)
147                 goto done;
148
149         /* Bail out if no buffers should be allocated. */
150         if (nbuffers == 0)
151                 goto done;
152
153         /* Decrement the number of buffers until allocation succeeds. */
154         for (; nbuffers > 0; --nbuffers) {
155                 mem = vmalloc_32(nbuffers * bufsize);
156                 if (mem != NULL)
157                         break;
158         }
159
160         if (mem == NULL) {
161                 ret = -ENOMEM;
162                 goto done;
163         }
164
165         for (i = 0; i < nbuffers; ++i) {
166                 memset(&queue->buffer[i], 0, sizeof queue->buffer[i]);
167                 queue->buffer[i].buf.index = i;
168                 queue->buffer[i].buf.m.offset = i * bufsize;
169                 queue->buffer[i].buf.length = buflength;
170                 queue->buffer[i].buf.type = queue->type;
171                 queue->buffer[i].buf.field = V4L2_FIELD_NONE;
172                 queue->buffer[i].buf.memory = V4L2_MEMORY_MMAP;
173                 queue->buffer[i].buf.flags = 0;
174                 init_waitqueue_head(&queue->buffer[i].wait);
175         }
176
177         queue->mem = mem;
178         queue->count = nbuffers;
179         queue->buf_size = bufsize;
180         ret = nbuffers;
181
182 done:
183         mutex_unlock(&queue->mutex);
184         return ret;
185 }
186
187 /*
188  * Check if buffers have been allocated.
189  */
190 int uvc_queue_allocated(struct uvc_video_queue *queue)
191 {
192         int allocated;
193
194         mutex_lock(&queue->mutex);
195         allocated = queue->count != 0;
196         mutex_unlock(&queue->mutex);
197
198         return allocated;
199 }
200
201 static void __uvc_query_buffer(struct uvc_buffer *buf,
202                 struct v4l2_buffer *v4l2_buf)
203 {
204         memcpy(v4l2_buf, &buf->buf, sizeof *v4l2_buf);
205
206         if (buf->vma_use_count)
207                 v4l2_buf->flags |= V4L2_BUF_FLAG_MAPPED;
208
209         switch (buf->state) {
210         case UVC_BUF_STATE_ERROR:
211         case UVC_BUF_STATE_DONE:
212                 v4l2_buf->flags |= V4L2_BUF_FLAG_DONE;
213                 break;
214         case UVC_BUF_STATE_QUEUED:
215         case UVC_BUF_STATE_ACTIVE:
216         case UVC_BUF_STATE_READY:
217                 v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
218                 break;
219         case UVC_BUF_STATE_IDLE:
220         default:
221                 break;
222         }
223 }
224
225 int uvc_query_buffer(struct uvc_video_queue *queue,
226                 struct v4l2_buffer *v4l2_buf)
227 {
228         int ret = 0;
229
230         mutex_lock(&queue->mutex);
231         if (v4l2_buf->index >= queue->count) {
232                 ret = -EINVAL;
233                 goto done;
234         }
235
236         __uvc_query_buffer(&queue->buffer[v4l2_buf->index], v4l2_buf);
237
238 done:
239         mutex_unlock(&queue->mutex);
240         return ret;
241 }
242
243 /*
244  * Queue a video buffer. Attempting to queue a buffer that has already been
245  * queued will return -EINVAL.
246  */
247 int uvc_queue_buffer(struct uvc_video_queue *queue,
248         struct v4l2_buffer *v4l2_buf)
249 {
250         struct uvc_buffer *buf;
251         unsigned long flags;
252         int ret = 0;
253
254         uvc_trace(UVC_TRACE_CAPTURE, "Queuing buffer %u.\n", v4l2_buf->index);
255
256         if (v4l2_buf->type != queue->type ||
257             v4l2_buf->memory != V4L2_MEMORY_MMAP) {
258                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer type (%u) "
259                         "and/or memory (%u).\n", v4l2_buf->type,
260                         v4l2_buf->memory);
261                 return -EINVAL;
262         }
263
264         mutex_lock(&queue->mutex);
265         if (v4l2_buf->index >= queue->count) {
266                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Out of range index.\n");
267                 ret = -EINVAL;
268                 goto done;
269         }
270
271         buf = &queue->buffer[v4l2_buf->index];
272         if (buf->state != UVC_BUF_STATE_IDLE) {
273                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer state "
274                         "(%u).\n", buf->state);
275                 ret = -EINVAL;
276                 goto done;
277         }
278
279         if (v4l2_buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT &&
280             v4l2_buf->bytesused > buf->buf.length) {
281                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Bytes used out of bounds.\n");
282                 ret = -EINVAL;
283                 goto done;
284         }
285
286         spin_lock_irqsave(&queue->irqlock, flags);
287         if (queue->flags & UVC_QUEUE_DISCONNECTED) {
288                 spin_unlock_irqrestore(&queue->irqlock, flags);
289                 ret = -ENODEV;
290                 goto done;
291         }
292         buf->state = UVC_BUF_STATE_QUEUED;
293         if (v4l2_buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
294                 buf->buf.bytesused = 0;
295         else
296                 buf->buf.bytesused = v4l2_buf->bytesused;
297
298         list_add_tail(&buf->stream, &queue->mainqueue);
299         list_add_tail(&buf->queue, &queue->irqqueue);
300         spin_unlock_irqrestore(&queue->irqlock, flags);
301
302 done:
303         mutex_unlock(&queue->mutex);
304         return ret;
305 }
306
307 static int uvc_queue_waiton(struct uvc_buffer *buf, int nonblocking)
308 {
309         if (nonblocking) {
310                 return (buf->state != UVC_BUF_STATE_QUEUED &&
311                         buf->state != UVC_BUF_STATE_ACTIVE &&
312                         buf->state != UVC_BUF_STATE_READY)
313                         ? 0 : -EAGAIN;
314         }
315
316         return wait_event_interruptible(buf->wait,
317                 buf->state != UVC_BUF_STATE_QUEUED &&
318                 buf->state != UVC_BUF_STATE_ACTIVE &&
319                 buf->state != UVC_BUF_STATE_READY);
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         if (list_empty(&queue->mainqueue)) {
342                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Empty buffer queue.\n");
343                 ret = -EINVAL;
344                 goto done;
345         }
346
347         buf = list_first_entry(&queue->mainqueue, struct uvc_buffer, stream);
348         if ((ret = uvc_queue_waiton(buf, nonblocking)) < 0)
349                 goto done;
350
351         uvc_trace(UVC_TRACE_CAPTURE, "Dequeuing buffer %u (%u, %u bytes).\n",
352                 buf->buf.index, buf->state, buf->buf.bytesused);
353
354         switch (buf->state) {
355         case UVC_BUF_STATE_ERROR:
356                 uvc_trace(UVC_TRACE_CAPTURE, "[W] Corrupted data "
357                         "(transmission error).\n");
358                 ret = -EIO;
359         case UVC_BUF_STATE_DONE:
360                 buf->state = UVC_BUF_STATE_IDLE;
361                 break;
362
363         case UVC_BUF_STATE_IDLE:
364         case UVC_BUF_STATE_QUEUED:
365         case UVC_BUF_STATE_ACTIVE:
366         case UVC_BUF_STATE_READY:
367         default:
368                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer state %u "
369                         "(driver bug?).\n", buf->state);
370                 ret = -EINVAL;
371                 goto done;
372         }
373
374         list_del(&buf->stream);
375         __uvc_query_buffer(buf, v4l2_buf);
376
377 done:
378         mutex_unlock(&queue->mutex);
379         return ret;
380 }
381
382 /*
383  * VMA operations.
384  */
385 static void uvc_vm_open(struct vm_area_struct *vma)
386 {
387         struct uvc_buffer *buffer = vma->vm_private_data;
388         buffer->vma_use_count++;
389 }
390
391 static void uvc_vm_close(struct vm_area_struct *vma)
392 {
393         struct uvc_buffer *buffer = vma->vm_private_data;
394         buffer->vma_use_count--;
395 }
396
397 static const struct vm_operations_struct uvc_vm_ops = {
398         .open           = uvc_vm_open,
399         .close          = uvc_vm_close,
400 };
401
402 /*
403  * Memory-map a video buffer.
404  *
405  * This function implements video buffers memory mapping and is intended to be
406  * used by the device mmap handler.
407  */
408 int uvc_queue_mmap(struct uvc_video_queue *queue, struct vm_area_struct *vma)
409 {
410         struct uvc_buffer *uninitialized_var(buffer);
411         struct page *page;
412         unsigned long addr, start, size;
413         unsigned int i;
414         int ret = 0;
415
416         start = vma->vm_start;
417         size = vma->vm_end - vma->vm_start;
418
419         mutex_lock(&queue->mutex);
420
421         for (i = 0; i < queue->count; ++i) {
422                 buffer = &queue->buffer[i];
423                 if ((buffer->buf.m.offset >> PAGE_SHIFT) == vma->vm_pgoff)
424                         break;
425         }
426
427         if (i == queue->count || PAGE_ALIGN(size) != queue->buf_size) {
428                 ret = -EINVAL;
429                 goto done;
430         }
431
432         /*
433          * VM_IO marks the area as being an mmaped region for I/O to a
434          * device. It also prevents the region from being core dumped.
435          */
436         vma->vm_flags |= VM_IO;
437
438         addr = (unsigned long)queue->mem + buffer->buf.m.offset;
439 #ifdef CONFIG_MMU
440         while (size > 0) {
441                 page = vmalloc_to_page((void *)addr);
442                 if ((ret = vm_insert_page(vma, start, page)) < 0)
443                         goto done;
444
445                 start += PAGE_SIZE;
446                 addr += PAGE_SIZE;
447                 size -= PAGE_SIZE;
448         }
449 #endif
450
451         vma->vm_ops = &uvc_vm_ops;
452         vma->vm_private_data = buffer;
453         uvc_vm_open(vma);
454
455 done:
456         mutex_unlock(&queue->mutex);
457         return ret;
458 }
459
460 /*
461  * Poll the video queue.
462  *
463  * This function implements video queue polling and is intended to be used by
464  * the device poll handler.
465  */
466 unsigned int uvc_queue_poll(struct uvc_video_queue *queue, struct file *file,
467                 poll_table *wait)
468 {
469         struct uvc_buffer *buf;
470         unsigned int mask = 0;
471
472         mutex_lock(&queue->mutex);
473         if (list_empty(&queue->mainqueue)) {
474                 mask |= POLLERR;
475                 goto done;
476         }
477         buf = list_first_entry(&queue->mainqueue, struct uvc_buffer, stream);
478
479         poll_wait(file, &buf->wait, wait);
480         if (buf->state == UVC_BUF_STATE_DONE ||
481             buf->state == UVC_BUF_STATE_ERROR) {
482                 if (queue->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
483                         mask |= POLLIN | POLLRDNORM;
484                 else
485                         mask |= POLLOUT | POLLWRNORM;
486         }
487
488 done:
489         mutex_unlock(&queue->mutex);
490         return mask;
491 }
492
493 #ifndef CONFIG_MMU
494 /*
495  * Get unmapped area.
496  *
497  * NO-MMU arch need this function to make mmap() work correctly.
498  */
499 unsigned long uvc_queue_get_unmapped_area(struct uvc_video_queue *queue,
500                 unsigned long pgoff)
501 {
502         struct uvc_buffer *buffer;
503         unsigned int i;
504         unsigned long ret;
505
506         mutex_lock(&queue->mutex);
507         for (i = 0; i < queue->count; ++i) {
508                 buffer = &queue->buffer[i];
509                 if ((buffer->buf.m.offset >> PAGE_SHIFT) == pgoff)
510                         break;
511         }
512         if (i == queue->count) {
513                 ret = -EINVAL;
514                 goto done;
515         }
516         ret = (unsigned long)queue->mem + buffer->buf.m.offset;
517 done:
518         mutex_unlock(&queue->mutex);
519         return ret;
520 }
521 #endif
522
523 /*
524  * Enable or disable the video buffers queue.
525  *
526  * The queue must be enabled before starting video acquisition and must be
527  * disabled after stopping it. This ensures that the video buffers queue
528  * state can be properly initialized before buffers are accessed from the
529  * interrupt handler.
530  *
531  * Enabling the video queue returns -EBUSY if the queue is already enabled.
532  *
533  * Disabling the video queue cancels the queue and removes all buffers from
534  * the main queue.
535  *
536  * This function can't be called from interrupt context. Use
537  * uvc_queue_cancel() instead.
538  */
539 int uvc_queue_enable(struct uvc_video_queue *queue, int enable)
540 {
541         unsigned int i;
542         int ret = 0;
543
544         mutex_lock(&queue->mutex);
545         if (enable) {
546                 if (uvc_queue_streaming(queue)) {
547                         ret = -EBUSY;
548                         goto done;
549                 }
550                 queue->flags |= UVC_QUEUE_STREAMING;
551                 queue->buf_used = 0;
552         } else {
553                 uvc_queue_cancel(queue, 0);
554                 INIT_LIST_HEAD(&queue->mainqueue);
555
556                 for (i = 0; i < queue->count; ++i) {
557                         queue->buffer[i].error = 0;
558                         queue->buffer[i].state = UVC_BUF_STATE_IDLE;
559                 }
560
561                 queue->flags &= ~UVC_QUEUE_STREAMING;
562         }
563
564 done:
565         mutex_unlock(&queue->mutex);
566         return ret;
567 }
568
569 /*
570  * Cancel the video buffers queue.
571  *
572  * Cancelling the queue marks all buffers on the irq queue as erroneous,
573  * wakes them up and removes them from the queue.
574  *
575  * If the disconnect parameter is set, further calls to uvc_queue_buffer will
576  * fail with -ENODEV.
577  *
578  * This function acquires the irq spinlock and can be called from interrupt
579  * context.
580  */
581 void uvc_queue_cancel(struct uvc_video_queue *queue, int disconnect)
582 {
583         struct uvc_buffer *buf;
584         unsigned long flags;
585
586         spin_lock_irqsave(&queue->irqlock, flags);
587         while (!list_empty(&queue->irqqueue)) {
588                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
589                                        queue);
590                 list_del(&buf->queue);
591                 buf->state = UVC_BUF_STATE_ERROR;
592                 wake_up(&buf->wait);
593         }
594         /* This must be protected by the irqlock spinlock to avoid race
595          * conditions between uvc_queue_buffer and the disconnection event that
596          * could result in an interruptible wait in uvc_dequeue_buffer. Do not
597          * blindly replace this logic by checking for the UVC_DEV_DISCONNECTED
598          * state outside the queue code.
599          */
600         if (disconnect)
601                 queue->flags |= UVC_QUEUE_DISCONNECTED;
602         spin_unlock_irqrestore(&queue->irqlock, flags);
603 }
604
605 struct uvc_buffer *uvc_queue_next_buffer(struct uvc_video_queue *queue,
606                 struct uvc_buffer *buf)
607 {
608         struct uvc_buffer *nextbuf;
609         unsigned long flags;
610
611         if ((queue->flags & UVC_QUEUE_DROP_CORRUPTED) && buf->error) {
612                 buf->error = 0;
613                 buf->state = UVC_BUF_STATE_QUEUED;
614                 buf->buf.bytesused = 0;
615                 return buf;
616         }
617
618         spin_lock_irqsave(&queue->irqlock, flags);
619         list_del(&buf->queue);
620         buf->error = 0;
621         buf->state = UVC_BUF_STATE_DONE;
622         if (!list_empty(&queue->irqqueue))
623                 nextbuf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
624                                            queue);
625         else
626                 nextbuf = NULL;
627         spin_unlock_irqrestore(&queue->irqlock, flags);
628
629         wake_up(&buf->wait);
630         return nextbuf;
631 }
632