Merge branch 'i2c-fix' of git://aeryn.fluff.org.uk/bjdooks/linux
[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-2008
5  *          Laurent Pinchart (laurent.pinchart@skynet.be)
6  *
7  *      This program is free software; you can redistribute it and/or modify
8  *      it under the terms of the GNU General Public License as published by
9  *      the Free Software Foundation; either version 2 of the License, or
10  *      (at your option) any later version.
11  *
12  */
13
14 #include <linux/kernel.h>
15 #include <linux/version.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 which use an in queue and an out queue, we use a main queue which
40  * holds all queued buffers (both 'empty' and 'done' buffers), and an irq
41  * queue which holds empty buffers. This design (copied from video-buf)
42  * minimizes locking in interrupt, as only one queue is shared between
43  * interrupt and user contexts.
44  *
45  * Use cases
46  * ---------
47  *
48  * Unless stated otherwise, all operations which 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 latert 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 ready (UVC_BUF_STATE_DONE) and wake 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 ready, 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)
82 {
83         mutex_init(&queue->mutex);
84         spin_lock_init(&queue->irqlock);
85         INIT_LIST_HEAD(&queue->mainqueue);
86         INIT_LIST_HEAD(&queue->irqqueue);
87 }
88
89 /*
90  * Allocate the video buffers.
91  *
92  * Pages are reserved to make sure they will not be swaped, as they will be
93  * filled in URB completion handler.
94  *
95  * Buffers will be individually mapped, so they must all be page aligned.
96  */
97 int uvc_alloc_buffers(struct uvc_video_queue *queue, unsigned int nbuffers,
98                 unsigned int buflength)
99 {
100         unsigned int bufsize = PAGE_ALIGN(buflength);
101         unsigned int i;
102         void *mem = NULL;
103         int ret;
104
105         if (nbuffers > UVC_MAX_VIDEO_BUFFERS)
106                 nbuffers = UVC_MAX_VIDEO_BUFFERS;
107
108         mutex_lock(&queue->mutex);
109
110         if ((ret = uvc_free_buffers(queue)) < 0)
111                 goto done;
112
113         /* Bail out if no buffers should be allocated. */
114         if (nbuffers == 0)
115                 goto done;
116
117         /* Decrement the number of buffers until allocation succeeds. */
118         for (; nbuffers > 0; --nbuffers) {
119                 mem = vmalloc_32(nbuffers * bufsize);
120                 if (mem != NULL)
121                         break;
122         }
123
124         if (mem == NULL) {
125                 ret = -ENOMEM;
126                 goto done;
127         }
128
129         for (i = 0; i < nbuffers; ++i) {
130                 memset(&queue->buffer[i], 0, sizeof queue->buffer[i]);
131                 queue->buffer[i].buf.index = i;
132                 queue->buffer[i].buf.m.offset = i * bufsize;
133                 queue->buffer[i].buf.length = buflength;
134                 queue->buffer[i].buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
135                 queue->buffer[i].buf.sequence = 0;
136                 queue->buffer[i].buf.field = V4L2_FIELD_NONE;
137                 queue->buffer[i].buf.memory = V4L2_MEMORY_MMAP;
138                 queue->buffer[i].buf.flags = 0;
139                 init_waitqueue_head(&queue->buffer[i].wait);
140         }
141
142         queue->mem = mem;
143         queue->count = nbuffers;
144         queue->buf_size = bufsize;
145         ret = nbuffers;
146
147 done:
148         mutex_unlock(&queue->mutex);
149         return ret;
150 }
151
152 /*
153  * Free the video buffers.
154  *
155  * This function must be called with the queue lock held.
156  */
157 int uvc_free_buffers(struct uvc_video_queue *queue)
158 {
159         unsigned int i;
160
161         for (i = 0; i < queue->count; ++i) {
162                 if (queue->buffer[i].vma_use_count != 0)
163                         return -EBUSY;
164         }
165
166         if (queue->count) {
167                 vfree(queue->mem);
168                 queue->count = 0;
169         }
170
171         return 0;
172 }
173
174 static void __uvc_query_buffer(struct uvc_buffer *buf,
175                 struct v4l2_buffer *v4l2_buf)
176 {
177         memcpy(v4l2_buf, &buf->buf, sizeof *v4l2_buf);
178
179         if (buf->vma_use_count)
180                 v4l2_buf->flags |= V4L2_BUF_FLAG_MAPPED;
181
182         switch (buf->state) {
183         case UVC_BUF_STATE_ERROR:
184         case UVC_BUF_STATE_DONE:
185                 v4l2_buf->flags |= V4L2_BUF_FLAG_DONE;
186                 break;
187         case UVC_BUF_STATE_QUEUED:
188         case UVC_BUF_STATE_ACTIVE:
189                 v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
190                 break;
191         case UVC_BUF_STATE_IDLE:
192         default:
193                 break;
194         }
195 }
196
197 int uvc_query_buffer(struct uvc_video_queue *queue,
198                 struct v4l2_buffer *v4l2_buf)
199 {
200         int ret = 0;
201
202         mutex_lock(&queue->mutex);
203         if (v4l2_buf->index >= queue->count) {
204                 ret = -EINVAL;
205                 goto done;
206         }
207
208         __uvc_query_buffer(&queue->buffer[v4l2_buf->index], v4l2_buf);
209
210 done:
211        mutex_unlock(&queue->mutex);
212        return ret;
213 }
214
215 /*
216  * Queue a video buffer. Attempting to queue a buffer that has already been
217  * queued will return -EINVAL.
218  */
219 int uvc_queue_buffer(struct uvc_video_queue *queue,
220         struct v4l2_buffer *v4l2_buf)
221 {
222         struct uvc_buffer *buf;
223         unsigned long flags;
224         int ret = 0;
225
226         uvc_trace(UVC_TRACE_CAPTURE, "Queuing buffer %u.\n", v4l2_buf->index);
227
228         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
229             v4l2_buf->memory != V4L2_MEMORY_MMAP) {
230                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer type (%u) "
231                         "and/or memory (%u).\n", v4l2_buf->type,
232                         v4l2_buf->memory);
233                 return -EINVAL;
234         }
235
236         mutex_lock(&queue->mutex);
237         if (v4l2_buf->index >= queue->count)  {
238                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Out of range index.\n");
239                 ret = -EINVAL;
240                 goto done;
241         }
242
243         buf = &queue->buffer[v4l2_buf->index];
244         if (buf->state != UVC_BUF_STATE_IDLE) {
245                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer state "
246                         "(%u).\n", buf->state);
247                 ret = -EINVAL;
248                 goto done;
249         }
250
251         spin_lock_irqsave(&queue->irqlock, flags);
252         if (queue->flags & UVC_QUEUE_DISCONNECTED) {
253                 spin_unlock_irqrestore(&queue->irqlock, flags);
254                 ret = -ENODEV;
255                 goto done;
256         }
257         buf->state = UVC_BUF_STATE_QUEUED;
258         buf->buf.bytesused = 0;
259         list_add_tail(&buf->stream, &queue->mainqueue);
260         list_add_tail(&buf->queue, &queue->irqqueue);
261         spin_unlock_irqrestore(&queue->irqlock, flags);
262
263 done:
264         mutex_unlock(&queue->mutex);
265         return ret;
266 }
267
268 static int uvc_queue_waiton(struct uvc_buffer *buf, int nonblocking)
269 {
270         if (nonblocking) {
271                 return (buf->state != UVC_BUF_STATE_QUEUED &&
272                         buf->state != UVC_BUF_STATE_ACTIVE)
273                         ? 0 : -EAGAIN;
274         }
275
276         return wait_event_interruptible(buf->wait,
277                 buf->state != UVC_BUF_STATE_QUEUED &&
278                 buf->state != UVC_BUF_STATE_ACTIVE);
279 }
280
281 /*
282  * Dequeue a video buffer. If nonblocking is false, block until a buffer is
283  * available.
284  */
285 int uvc_dequeue_buffer(struct uvc_video_queue *queue,
286                 struct v4l2_buffer *v4l2_buf, int nonblocking)
287 {
288         struct uvc_buffer *buf;
289         int ret = 0;
290
291         if (v4l2_buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
292             v4l2_buf->memory != V4L2_MEMORY_MMAP) {
293                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer type (%u) "
294                         "and/or memory (%u).\n", v4l2_buf->type,
295                         v4l2_buf->memory);
296                 return -EINVAL;
297         }
298
299         mutex_lock(&queue->mutex);
300         if (list_empty(&queue->mainqueue)) {
301                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Empty buffer queue.\n");
302                 ret = -EINVAL;
303                 goto done;
304         }
305
306         buf = list_first_entry(&queue->mainqueue, struct uvc_buffer, stream);
307         if ((ret = uvc_queue_waiton(buf, nonblocking)) < 0)
308                 goto done;
309
310         uvc_trace(UVC_TRACE_CAPTURE, "Dequeuing buffer %u (%u, %u bytes).\n",
311                 buf->buf.index, buf->state, buf->buf.bytesused);
312
313         switch (buf->state) {
314         case UVC_BUF_STATE_ERROR:
315                 uvc_trace(UVC_TRACE_CAPTURE, "[W] Corrupted data "
316                         "(transmission error).\n");
317                 ret = -EIO;
318         case UVC_BUF_STATE_DONE:
319                 buf->state = UVC_BUF_STATE_IDLE;
320                 break;
321
322         case UVC_BUF_STATE_IDLE:
323         case UVC_BUF_STATE_QUEUED:
324         case UVC_BUF_STATE_ACTIVE:
325         default:
326                 uvc_trace(UVC_TRACE_CAPTURE, "[E] Invalid buffer state %u "
327                         "(driver bug?).\n", buf->state);
328                 ret = -EINVAL;
329                 goto done;
330         }
331
332         list_del(&buf->stream);
333         __uvc_query_buffer(buf, v4l2_buf);
334
335 done:
336         mutex_unlock(&queue->mutex);
337         return ret;
338 }
339
340 /*
341  * Poll the video queue.
342  *
343  * This function implements video queue polling and is intended to be used by
344  * the device poll handler.
345  */
346 unsigned int uvc_queue_poll(struct uvc_video_queue *queue, struct file *file,
347                 poll_table *wait)
348 {
349         struct uvc_buffer *buf;
350         unsigned int mask = 0;
351
352         mutex_lock(&queue->mutex);
353         if (list_empty(&queue->mainqueue)) {
354                 mask |= POLLERR;
355                 goto done;
356         }
357         buf = list_first_entry(&queue->mainqueue, struct uvc_buffer, stream);
358
359         poll_wait(file, &buf->wait, wait);
360         if (buf->state == UVC_BUF_STATE_DONE ||
361             buf->state == UVC_BUF_STATE_ERROR)
362                 mask |= POLLIN | POLLRDNORM;
363
364 done:
365         mutex_unlock(&queue->mutex);
366         return mask;
367 }
368
369 /*
370  * Enable or disable the video buffers queue.
371  *
372  * The queue must be enabled before starting video acquisition and must be
373  * disabled after stopping it. This ensures that the video buffers queue
374  * state can be properly initialized before buffers are accessed from the
375  * interrupt handler.
376  *
377  * Enabling the video queue initializes parameters (such as sequence number,
378  * sync pattern, ...). If the queue is already enabled, return -EBUSY.
379  *
380  * Disabling the video queue cancels the queue and removes all buffers from
381  * the main queue.
382  *
383  * This function can't be called from interrupt context. Use
384  * uvc_queue_cancel() instead.
385  */
386 int uvc_queue_enable(struct uvc_video_queue *queue, int enable)
387 {
388         unsigned int i;
389         int ret = 0;
390
391         mutex_lock(&queue->mutex);
392         if (enable) {
393                 if (uvc_queue_streaming(queue)) {
394                         ret = -EBUSY;
395                         goto done;
396                 }
397                 queue->sequence = 0;
398                 queue->flags |= UVC_QUEUE_STREAMING;
399         } else {
400                 uvc_queue_cancel(queue, 0);
401                 INIT_LIST_HEAD(&queue->mainqueue);
402
403                 for (i = 0; i < queue->count; ++i)
404                         queue->buffer[i].state = UVC_BUF_STATE_IDLE;
405
406                 queue->flags &= ~UVC_QUEUE_STREAMING;
407         }
408
409 done:
410         mutex_unlock(&queue->mutex);
411         return ret;
412 }
413
414 /*
415  * Cancel the video buffers queue.
416  *
417  * Cancelling the queue marks all buffers on the irq queue as erroneous,
418  * wakes them up and remove them from the queue.
419  *
420  * If the disconnect parameter is set, further calls to uvc_queue_buffer will
421  * fail with -ENODEV.
422  *
423  * This function acquires the irq spinlock and can be called from interrupt
424  * context.
425  */
426 void uvc_queue_cancel(struct uvc_video_queue *queue, int disconnect)
427 {
428         struct uvc_buffer *buf;
429         unsigned long flags;
430
431         spin_lock_irqsave(&queue->irqlock, flags);
432         while (!list_empty(&queue->irqqueue)) {
433                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
434                                        queue);
435                 list_del(&buf->queue);
436                 buf->state = UVC_BUF_STATE_ERROR;
437                 wake_up(&buf->wait);
438         }
439         /* This must be protected by the irqlock spinlock to avoid race
440          * conditions between uvc_queue_buffer and the disconnection event that
441          * could result in an interruptible wait in uvc_dequeue_buffer. Do not
442          * blindly replace this logic by checking for the UVC_DEV_DISCONNECTED
443          * state outside the queue code.
444          */
445         if (disconnect)
446                 queue->flags |= UVC_QUEUE_DISCONNECTED;
447         spin_unlock_irqrestore(&queue->irqlock, flags);
448 }
449
450 struct uvc_buffer *uvc_queue_next_buffer(struct uvc_video_queue *queue,
451                 struct uvc_buffer *buf)
452 {
453         struct uvc_buffer *nextbuf;
454         unsigned long flags;
455
456         if ((queue->flags & UVC_QUEUE_DROP_INCOMPLETE) &&
457             buf->buf.length != buf->buf.bytesused) {
458                 buf->state = UVC_BUF_STATE_QUEUED;
459                 buf->buf.bytesused = 0;
460                 return buf;
461         }
462
463         spin_lock_irqsave(&queue->irqlock, flags);
464         list_del(&buf->queue);
465         if (!list_empty(&queue->irqqueue))
466                 nextbuf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
467                                            queue);
468         else
469                 nextbuf = NULL;
470         spin_unlock_irqrestore(&queue->irqlock, flags);
471
472         buf->buf.sequence = queue->sequence++;
473         do_gettimeofday(&buf->buf.timestamp);
474
475         wake_up(&buf->wait);
476         return nextbuf;
477 }