GNU Linux-libre 4.9.309-gnu1
[releases.git] / drivers / media / v4l2-core / videobuf2-core.c
1 /*
2  * videobuf2-core.c - video buffer 2 core framework
3  *
4  * Copyright (C) 2010 Samsung Electronics
5  *
6  * Author: Pawel Osciak <pawel@osciak.com>
7  *         Marek Szyprowski <m.szyprowski@samsung.com>
8  *
9  * The vb2_thread implementation was based on code from videobuf-dvb.c:
10  *      (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SUSE Labs]
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation.
15  */
16
17 #include <linux/err.h>
18 #include <linux/kernel.h>
19 #include <linux/module.h>
20 #include <linux/mm.h>
21 #include <linux/poll.h>
22 #include <linux/slab.h>
23 #include <linux/sched.h>
24 #include <linux/freezer.h>
25 #include <linux/kthread.h>
26
27 #include <media/videobuf2-core.h>
28 #include <media/v4l2-mc.h>
29
30 #include <trace/events/vb2.h>
31
32 static int debug;
33 module_param(debug, int, 0644);
34
35 #define dprintk(level, fmt, arg...)                                           \
36         do {                                                                  \
37                 if (debug >= level)                                           \
38                         pr_info("vb2-core: %s: " fmt, __func__, ## arg); \
39         } while (0)
40
41 #ifdef CONFIG_VIDEO_ADV_DEBUG
42
43 /*
44  * If advanced debugging is on, then count how often each op is called
45  * successfully, which can either be per-buffer or per-queue.
46  *
47  * This makes it easy to check that the 'init' and 'cleanup'
48  * (and variations thereof) stay balanced.
49  */
50
51 #define log_memop(vb, op)                                               \
52         dprintk(2, "call_memop(%p, %d, %s)%s\n",                        \
53                 (vb)->vb2_queue, (vb)->index, #op,                      \
54                 (vb)->vb2_queue->mem_ops->op ? "" : " (nop)")
55
56 #define call_memop(vb, op, args...)                                     \
57 ({                                                                      \
58         struct vb2_queue *_q = (vb)->vb2_queue;                         \
59         int err;                                                        \
60                                                                         \
61         log_memop(vb, op);                                              \
62         err = _q->mem_ops->op ? _q->mem_ops->op(args) : 0;              \
63         if (!err)                                                       \
64                 (vb)->cnt_mem_ ## op++;                                 \
65         err;                                                            \
66 })
67
68 #define call_ptr_memop(vb, op, args...)                                 \
69 ({                                                                      \
70         struct vb2_queue *_q = (vb)->vb2_queue;                         \
71         void *ptr;                                                      \
72                                                                         \
73         log_memop(vb, op);                                              \
74         ptr = _q->mem_ops->op ? _q->mem_ops->op(args) : NULL;           \
75         if (!IS_ERR_OR_NULL(ptr))                                       \
76                 (vb)->cnt_mem_ ## op++;                                 \
77         ptr;                                                            \
78 })
79
80 #define call_void_memop(vb, op, args...)                                \
81 ({                                                                      \
82         struct vb2_queue *_q = (vb)->vb2_queue;                         \
83                                                                         \
84         log_memop(vb, op);                                              \
85         if (_q->mem_ops->op)                                            \
86                 _q->mem_ops->op(args);                                  \
87         (vb)->cnt_mem_ ## op++;                                         \
88 })
89
90 #define log_qop(q, op)                                                  \
91         dprintk(2, "call_qop(%p, %s)%s\n", q, #op,                      \
92                 (q)->ops->op ? "" : " (nop)")
93
94 #define call_qop(q, op, args...)                                        \
95 ({                                                                      \
96         int err;                                                        \
97                                                                         \
98         log_qop(q, op);                                                 \
99         err = (q)->ops->op ? (q)->ops->op(args) : 0;                    \
100         if (!err)                                                       \
101                 (q)->cnt_ ## op++;                                      \
102         err;                                                            \
103 })
104
105 #define call_void_qop(q, op, args...)                                   \
106 ({                                                                      \
107         log_qop(q, op);                                                 \
108         if ((q)->ops->op)                                               \
109                 (q)->ops->op(args);                                     \
110         (q)->cnt_ ## op++;                                              \
111 })
112
113 #define log_vb_qop(vb, op, args...)                                     \
114         dprintk(2, "call_vb_qop(%p, %d, %s)%s\n",                       \
115                 (vb)->vb2_queue, (vb)->index, #op,                      \
116                 (vb)->vb2_queue->ops->op ? "" : " (nop)")
117
118 #define call_vb_qop(vb, op, args...)                                    \
119 ({                                                                      \
120         int err;                                                        \
121                                                                         \
122         log_vb_qop(vb, op);                                             \
123         err = (vb)->vb2_queue->ops->op ?                                \
124                 (vb)->vb2_queue->ops->op(args) : 0;                     \
125         if (!err)                                                       \
126                 (vb)->cnt_ ## op++;                                     \
127         err;                                                            \
128 })
129
130 #define call_void_vb_qop(vb, op, args...)                               \
131 ({                                                                      \
132         log_vb_qop(vb, op);                                             \
133         if ((vb)->vb2_queue->ops->op)                                   \
134                 (vb)->vb2_queue->ops->op(args);                         \
135         (vb)->cnt_ ## op++;                                             \
136 })
137
138 #else
139
140 #define call_memop(vb, op, args...)                                     \
141         ((vb)->vb2_queue->mem_ops->op ?                                 \
142                 (vb)->vb2_queue->mem_ops->op(args) : 0)
143
144 #define call_ptr_memop(vb, op, args...)                                 \
145         ((vb)->vb2_queue->mem_ops->op ?                                 \
146                 (vb)->vb2_queue->mem_ops->op(args) : NULL)
147
148 #define call_void_memop(vb, op, args...)                                \
149         do {                                                            \
150                 if ((vb)->vb2_queue->mem_ops->op)                       \
151                         (vb)->vb2_queue->mem_ops->op(args);             \
152         } while (0)
153
154 #define call_qop(q, op, args...)                                        \
155         ((q)->ops->op ? (q)->ops->op(args) : 0)
156
157 #define call_void_qop(q, op, args...)                                   \
158         do {                                                            \
159                 if ((q)->ops->op)                                       \
160                         (q)->ops->op(args);                             \
161         } while (0)
162
163 #define call_vb_qop(vb, op, args...)                                    \
164         ((vb)->vb2_queue->ops->op ? (vb)->vb2_queue->ops->op(args) : 0)
165
166 #define call_void_vb_qop(vb, op, args...)                               \
167         do {                                                            \
168                 if ((vb)->vb2_queue->ops->op)                           \
169                         (vb)->vb2_queue->ops->op(args);                 \
170         } while (0)
171
172 #endif
173
174 #define call_bufop(q, op, args...)                                      \
175 ({                                                                      \
176         int ret = 0;                                                    \
177         if (q && q->buf_ops && q->buf_ops->op)                          \
178                 ret = q->buf_ops->op(args);                             \
179         ret;                                                            \
180 })
181
182 #define call_void_bufop(q, op, args...)                                 \
183 ({                                                                      \
184         if (q && q->buf_ops && q->buf_ops->op)                          \
185                 q->buf_ops->op(args);                                   \
186 })
187
188 static void __vb2_queue_cancel(struct vb2_queue *q);
189 static void __enqueue_in_driver(struct vb2_buffer *vb);
190
191 /**
192  * __vb2_buf_mem_alloc() - allocate video memory for the given buffer
193  */
194 static int __vb2_buf_mem_alloc(struct vb2_buffer *vb)
195 {
196         struct vb2_queue *q = vb->vb2_queue;
197         enum dma_data_direction dma_dir =
198                 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
199         void *mem_priv;
200         int plane;
201         int ret = -ENOMEM;
202
203         /*
204          * Allocate memory for all planes in this buffer
205          * NOTE: mmapped areas should be page aligned
206          */
207         for (plane = 0; plane < vb->num_planes; ++plane) {
208                 unsigned long size = PAGE_ALIGN(vb->planes[plane].length);
209
210                 mem_priv = call_ptr_memop(vb, alloc,
211                                 q->alloc_devs[plane] ? : q->dev,
212                                 q->dma_attrs, size, dma_dir, q->gfp_flags);
213                 if (IS_ERR(mem_priv)) {
214                         if (mem_priv)
215                                 ret = PTR_ERR(mem_priv);
216                         goto free;
217                 }
218
219                 /* Associate allocator private data with this plane */
220                 vb->planes[plane].mem_priv = mem_priv;
221         }
222
223         return 0;
224 free:
225         /* Free already allocated memory if one of the allocations failed */
226         for (; plane > 0; --plane) {
227                 call_void_memop(vb, put, vb->planes[plane - 1].mem_priv);
228                 vb->planes[plane - 1].mem_priv = NULL;
229         }
230
231         return ret;
232 }
233
234 /**
235  * __vb2_buf_mem_free() - free memory of the given buffer
236  */
237 static void __vb2_buf_mem_free(struct vb2_buffer *vb)
238 {
239         unsigned int plane;
240
241         for (plane = 0; plane < vb->num_planes; ++plane) {
242                 call_void_memop(vb, put, vb->planes[plane].mem_priv);
243                 vb->planes[plane].mem_priv = NULL;
244                 dprintk(3, "freed plane %d of buffer %d\n", plane, vb->index);
245         }
246 }
247
248 /**
249  * __vb2_buf_userptr_put() - release userspace memory associated with
250  * a USERPTR buffer
251  */
252 static void __vb2_buf_userptr_put(struct vb2_buffer *vb)
253 {
254         unsigned int plane;
255
256         for (plane = 0; plane < vb->num_planes; ++plane) {
257                 if (vb->planes[plane].mem_priv)
258                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
259                 vb->planes[plane].mem_priv = NULL;
260         }
261 }
262
263 /**
264  * __vb2_plane_dmabuf_put() - release memory associated with
265  * a DMABUF shared plane
266  */
267 static void __vb2_plane_dmabuf_put(struct vb2_buffer *vb, struct vb2_plane *p)
268 {
269         if (!p->mem_priv)
270                 return;
271
272         if (p->dbuf_mapped)
273                 call_void_memop(vb, unmap_dmabuf, p->mem_priv);
274
275         call_void_memop(vb, detach_dmabuf, p->mem_priv);
276         dma_buf_put(p->dbuf);
277         p->mem_priv = NULL;
278         p->dbuf = NULL;
279         p->dbuf_mapped = 0;
280 }
281
282 /**
283  * __vb2_buf_dmabuf_put() - release memory associated with
284  * a DMABUF shared buffer
285  */
286 static void __vb2_buf_dmabuf_put(struct vb2_buffer *vb)
287 {
288         unsigned int plane;
289
290         for (plane = 0; plane < vb->num_planes; ++plane)
291                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
292 }
293
294 /**
295  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
296  * the buffer.
297  */
298 static void __setup_offsets(struct vb2_buffer *vb)
299 {
300         struct vb2_queue *q = vb->vb2_queue;
301         unsigned int plane;
302         unsigned long off = 0;
303
304         if (vb->index) {
305                 struct vb2_buffer *prev = q->bufs[vb->index - 1];
306                 struct vb2_plane *p = &prev->planes[prev->num_planes - 1];
307
308                 off = PAGE_ALIGN(p->m.offset + p->length);
309         }
310
311         for (plane = 0; plane < vb->num_planes; ++plane) {
312                 vb->planes[plane].m.offset = off;
313
314                 dprintk(3, "buffer %d, plane %d offset 0x%08lx\n",
315                                 vb->index, plane, off);
316
317                 off += vb->planes[plane].length;
318                 off = PAGE_ALIGN(off);
319         }
320 }
321
322 /**
323  * __vb2_queue_alloc() - allocate videobuf buffer structures and (for MMAP type)
324  * video buffer memory for all buffers/planes on the queue and initializes the
325  * queue
326  *
327  * Returns the number of buffers successfully allocated.
328  */
329 static int __vb2_queue_alloc(struct vb2_queue *q, enum vb2_memory memory,
330                              unsigned int num_buffers, unsigned int num_planes,
331                              const unsigned plane_sizes[VB2_MAX_PLANES])
332 {
333         unsigned int buffer, plane;
334         struct vb2_buffer *vb;
335         int ret;
336
337         /* Ensure that q->num_buffers+num_buffers is below VB2_MAX_FRAME */
338         num_buffers = min_t(unsigned int, num_buffers,
339                             VB2_MAX_FRAME - q->num_buffers);
340
341         for (buffer = 0; buffer < num_buffers; ++buffer) {
342                 /* Allocate videobuf buffer structures */
343                 vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
344                 if (!vb) {
345                         dprintk(1, "memory alloc for buffer struct failed\n");
346                         break;
347                 }
348
349                 vb->state = VB2_BUF_STATE_DEQUEUED;
350                 vb->vb2_queue = q;
351                 vb->num_planes = num_planes;
352                 vb->index = q->num_buffers + buffer;
353                 vb->type = q->type;
354                 vb->memory = memory;
355                 for (plane = 0; plane < num_planes; ++plane) {
356                         vb->planes[plane].length = plane_sizes[plane];
357                         vb->planes[plane].min_length = plane_sizes[plane];
358                 }
359                 q->bufs[vb->index] = vb;
360
361                 /* Allocate video buffer memory for the MMAP type */
362                 if (memory == VB2_MEMORY_MMAP) {
363                         ret = __vb2_buf_mem_alloc(vb);
364                         if (ret) {
365                                 dprintk(1, "failed allocating memory for "
366                                                 "buffer %d\n", buffer);
367                                 q->bufs[vb->index] = NULL;
368                                 kfree(vb);
369                                 break;
370                         }
371                         __setup_offsets(vb);
372                         /*
373                          * Call the driver-provided buffer initialization
374                          * callback, if given. An error in initialization
375                          * results in queue setup failure.
376                          */
377                         ret = call_vb_qop(vb, buf_init, vb);
378                         if (ret) {
379                                 dprintk(1, "buffer %d %p initialization"
380                                         " failed\n", buffer, vb);
381                                 __vb2_buf_mem_free(vb);
382                                 q->bufs[vb->index] = NULL;
383                                 kfree(vb);
384                                 break;
385                         }
386                 }
387         }
388
389         dprintk(1, "allocated %d buffers, %d plane(s) each\n",
390                         buffer, num_planes);
391
392         return buffer;
393 }
394
395 /**
396  * __vb2_free_mem() - release all video buffer memory for a given queue
397  */
398 static void __vb2_free_mem(struct vb2_queue *q, unsigned int buffers)
399 {
400         unsigned int buffer;
401         struct vb2_buffer *vb;
402
403         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
404              ++buffer) {
405                 vb = q->bufs[buffer];
406                 if (!vb)
407                         continue;
408
409                 /* Free MMAP buffers or release USERPTR buffers */
410                 if (q->memory == VB2_MEMORY_MMAP)
411                         __vb2_buf_mem_free(vb);
412                 else if (q->memory == VB2_MEMORY_DMABUF)
413                         __vb2_buf_dmabuf_put(vb);
414                 else
415                         __vb2_buf_userptr_put(vb);
416         }
417 }
418
419 /**
420  * __vb2_queue_free() - free buffers at the end of the queue - video memory and
421  * related information, if no buffers are left return the queue to an
422  * uninitialized state. Might be called even if the queue has already been freed.
423  */
424 static int __vb2_queue_free(struct vb2_queue *q, unsigned int buffers)
425 {
426         unsigned int buffer;
427
428         /*
429          * Sanity check: when preparing a buffer the queue lock is released for
430          * a short while (see __buf_prepare for the details), which would allow
431          * a race with a reqbufs which can call this function. Removing the
432          * buffers from underneath __buf_prepare is obviously a bad idea, so we
433          * check if any of the buffers is in the state PREPARING, and if so we
434          * just return -EAGAIN.
435          */
436         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
437              ++buffer) {
438                 if (q->bufs[buffer] == NULL)
439                         continue;
440                 if (q->bufs[buffer]->state == VB2_BUF_STATE_PREPARING) {
441                         dprintk(1, "preparing buffers, cannot free\n");
442                         return -EAGAIN;
443                 }
444         }
445
446         /* Call driver-provided cleanup function for each buffer, if provided */
447         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
448              ++buffer) {
449                 struct vb2_buffer *vb = q->bufs[buffer];
450
451                 if (vb && vb->planes[0].mem_priv)
452                         call_void_vb_qop(vb, buf_cleanup, vb);
453         }
454
455         /* Release video buffer memory */
456         __vb2_free_mem(q, buffers);
457
458 #ifdef CONFIG_VIDEO_ADV_DEBUG
459         /*
460          * Check that all the calls were balances during the life-time of this
461          * queue. If not (or if the debug level is 1 or up), then dump the
462          * counters to the kernel log.
463          */
464         if (q->num_buffers) {
465                 bool unbalanced = q->cnt_start_streaming != q->cnt_stop_streaming ||
466                                   q->cnt_wait_prepare != q->cnt_wait_finish;
467
468                 if (unbalanced || debug) {
469                         pr_info("vb2: counters for queue %p:%s\n", q,
470                                 unbalanced ? " UNBALANCED!" : "");
471                         pr_info("vb2:     setup: %u start_streaming: %u stop_streaming: %u\n",
472                                 q->cnt_queue_setup, q->cnt_start_streaming,
473                                 q->cnt_stop_streaming);
474                         pr_info("vb2:     wait_prepare: %u wait_finish: %u\n",
475                                 q->cnt_wait_prepare, q->cnt_wait_finish);
476                 }
477                 q->cnt_queue_setup = 0;
478                 q->cnt_wait_prepare = 0;
479                 q->cnt_wait_finish = 0;
480                 q->cnt_start_streaming = 0;
481                 q->cnt_stop_streaming = 0;
482         }
483         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
484                 struct vb2_buffer *vb = q->bufs[buffer];
485                 bool unbalanced = vb->cnt_mem_alloc != vb->cnt_mem_put ||
486                                   vb->cnt_mem_prepare != vb->cnt_mem_finish ||
487                                   vb->cnt_mem_get_userptr != vb->cnt_mem_put_userptr ||
488                                   vb->cnt_mem_attach_dmabuf != vb->cnt_mem_detach_dmabuf ||
489                                   vb->cnt_mem_map_dmabuf != vb->cnt_mem_unmap_dmabuf ||
490                                   vb->cnt_buf_queue != vb->cnt_buf_done ||
491                                   vb->cnt_buf_prepare != vb->cnt_buf_finish ||
492                                   vb->cnt_buf_init != vb->cnt_buf_cleanup;
493
494                 if (unbalanced || debug) {
495                         pr_info("vb2:   counters for queue %p, buffer %d:%s\n",
496                                 q, buffer, unbalanced ? " UNBALANCED!" : "");
497                         pr_info("vb2:     buf_init: %u buf_cleanup: %u buf_prepare: %u buf_finish: %u\n",
498                                 vb->cnt_buf_init, vb->cnt_buf_cleanup,
499                                 vb->cnt_buf_prepare, vb->cnt_buf_finish);
500                         pr_info("vb2:     buf_queue: %u buf_done: %u\n",
501                                 vb->cnt_buf_queue, vb->cnt_buf_done);
502                         pr_info("vb2:     alloc: %u put: %u prepare: %u finish: %u mmap: %u\n",
503                                 vb->cnt_mem_alloc, vb->cnt_mem_put,
504                                 vb->cnt_mem_prepare, vb->cnt_mem_finish,
505                                 vb->cnt_mem_mmap);
506                         pr_info("vb2:     get_userptr: %u put_userptr: %u\n",
507                                 vb->cnt_mem_get_userptr, vb->cnt_mem_put_userptr);
508                         pr_info("vb2:     attach_dmabuf: %u detach_dmabuf: %u map_dmabuf: %u unmap_dmabuf: %u\n",
509                                 vb->cnt_mem_attach_dmabuf, vb->cnt_mem_detach_dmabuf,
510                                 vb->cnt_mem_map_dmabuf, vb->cnt_mem_unmap_dmabuf);
511                         pr_info("vb2:     get_dmabuf: %u num_users: %u vaddr: %u cookie: %u\n",
512                                 vb->cnt_mem_get_dmabuf,
513                                 vb->cnt_mem_num_users,
514                                 vb->cnt_mem_vaddr,
515                                 vb->cnt_mem_cookie);
516                 }
517         }
518 #endif
519
520         /* Free videobuf buffers */
521         for (buffer = q->num_buffers - buffers; buffer < q->num_buffers;
522              ++buffer) {
523                 kfree(q->bufs[buffer]);
524                 q->bufs[buffer] = NULL;
525         }
526
527         q->num_buffers -= buffers;
528         if (!q->num_buffers) {
529                 q->memory = 0;
530                 INIT_LIST_HEAD(&q->queued_list);
531         }
532         return 0;
533 }
534
535 bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
536 {
537         unsigned int plane;
538         for (plane = 0; plane < vb->num_planes; ++plane) {
539                 void *mem_priv = vb->planes[plane].mem_priv;
540                 /*
541                  * If num_users() has not been provided, call_memop
542                  * will return 0, apparently nobody cares about this
543                  * case anyway. If num_users() returns more than 1,
544                  * we are not the only user of the plane's memory.
545                  */
546                 if (mem_priv && call_memop(vb, num_users, mem_priv) > 1)
547                         return true;
548         }
549         return false;
550 }
551 EXPORT_SYMBOL(vb2_buffer_in_use);
552
553 /**
554  * __buffers_in_use() - return true if any buffers on the queue are in use and
555  * the queue cannot be freed (by the means of REQBUFS(0)) call
556  */
557 static bool __buffers_in_use(struct vb2_queue *q)
558 {
559         unsigned int buffer;
560         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
561                 if (vb2_buffer_in_use(q, q->bufs[buffer]))
562                         return true;
563         }
564         return false;
565 }
566
567 void vb2_core_querybuf(struct vb2_queue *q, unsigned int index, void *pb)
568 {
569         call_void_bufop(q, fill_user_buffer, q->bufs[index], pb);
570 }
571 EXPORT_SYMBOL_GPL(vb2_core_querybuf);
572
573 /**
574  * __verify_userptr_ops() - verify that all memory operations required for
575  * USERPTR queue type have been provided
576  */
577 static int __verify_userptr_ops(struct vb2_queue *q)
578 {
579         if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
580             !q->mem_ops->put_userptr)
581                 return -EINVAL;
582
583         return 0;
584 }
585
586 /**
587  * __verify_mmap_ops() - verify that all memory operations required for
588  * MMAP queue type have been provided
589  */
590 static int __verify_mmap_ops(struct vb2_queue *q)
591 {
592         if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
593             !q->mem_ops->put || !q->mem_ops->mmap)
594                 return -EINVAL;
595
596         return 0;
597 }
598
599 /**
600  * __verify_dmabuf_ops() - verify that all memory operations required for
601  * DMABUF queue type have been provided
602  */
603 static int __verify_dmabuf_ops(struct vb2_queue *q)
604 {
605         if (!(q->io_modes & VB2_DMABUF) || !q->mem_ops->attach_dmabuf ||
606             !q->mem_ops->detach_dmabuf  || !q->mem_ops->map_dmabuf ||
607             !q->mem_ops->unmap_dmabuf)
608                 return -EINVAL;
609
610         return 0;
611 }
612
613 int vb2_verify_memory_type(struct vb2_queue *q,
614                 enum vb2_memory memory, unsigned int type)
615 {
616         if (memory != VB2_MEMORY_MMAP && memory != VB2_MEMORY_USERPTR &&
617             memory != VB2_MEMORY_DMABUF) {
618                 dprintk(1, "unsupported memory type\n");
619                 return -EINVAL;
620         }
621
622         if (type != q->type) {
623                 dprintk(1, "requested type is incorrect\n");
624                 return -EINVAL;
625         }
626
627         /*
628          * Make sure all the required memory ops for given memory type
629          * are available.
630          */
631         if (memory == VB2_MEMORY_MMAP && __verify_mmap_ops(q)) {
632                 dprintk(1, "MMAP for current setup unsupported\n");
633                 return -EINVAL;
634         }
635
636         if (memory == VB2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
637                 dprintk(1, "USERPTR for current setup unsupported\n");
638                 return -EINVAL;
639         }
640
641         if (memory == VB2_MEMORY_DMABUF && __verify_dmabuf_ops(q)) {
642                 dprintk(1, "DMABUF for current setup unsupported\n");
643                 return -EINVAL;
644         }
645
646         /*
647          * Place the busy tests at the end: -EBUSY can be ignored when
648          * create_bufs is called with count == 0, but count == 0 should still
649          * do the memory and type validation.
650          */
651         if (vb2_fileio_is_active(q)) {
652                 dprintk(1, "file io in progress\n");
653                 return -EBUSY;
654         }
655         return 0;
656 }
657 EXPORT_SYMBOL(vb2_verify_memory_type);
658
659 int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory,
660                 unsigned int *count)
661 {
662         unsigned int num_buffers, allocated_buffers, num_planes = 0;
663         unsigned plane_sizes[VB2_MAX_PLANES] = { };
664         int ret;
665
666         if (q->streaming) {
667                 dprintk(1, "streaming active\n");
668                 return -EBUSY;
669         }
670
671         if (*count == 0 || q->num_buffers != 0 || q->memory != memory) {
672                 /*
673                  * We already have buffers allocated, so first check if they
674                  * are not in use and can be freed.
675                  */
676                 mutex_lock(&q->mmap_lock);
677                 if (q->memory == VB2_MEMORY_MMAP && __buffers_in_use(q)) {
678                         mutex_unlock(&q->mmap_lock);
679                         dprintk(1, "memory in use, cannot free\n");
680                         return -EBUSY;
681                 }
682
683                 /*
684                  * Call queue_cancel to clean up any buffers in the PREPARED or
685                  * QUEUED state which is possible if buffers were prepared or
686                  * queued without ever calling STREAMON.
687                  */
688                 __vb2_queue_cancel(q);
689                 ret = __vb2_queue_free(q, q->num_buffers);
690                 mutex_unlock(&q->mmap_lock);
691                 if (ret)
692                         return ret;
693
694                 /*
695                  * In case of REQBUFS(0) return immediately without calling
696                  * driver's queue_setup() callback and allocating resources.
697                  */
698                 if (*count == 0)
699                         return 0;
700         }
701
702         /*
703          * Make sure the requested values and current defaults are sane.
704          */
705         num_buffers = min_t(unsigned int, *count, VB2_MAX_FRAME);
706         num_buffers = max_t(unsigned int, num_buffers, q->min_buffers_needed);
707         memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
708         q->memory = memory;
709
710         /*
711          * Ask the driver how many buffers and planes per buffer it requires.
712          * Driver also sets the size and allocator context for each plane.
713          */
714         ret = call_qop(q, queue_setup, q, &num_buffers, &num_planes,
715                        plane_sizes, q->alloc_devs);
716         if (ret)
717                 return ret;
718
719         /* Finally, allocate buffers and video memory */
720         allocated_buffers =
721                 __vb2_queue_alloc(q, memory, num_buffers, num_planes, plane_sizes);
722         if (allocated_buffers == 0) {
723                 dprintk(1, "memory allocation failed\n");
724                 return -ENOMEM;
725         }
726
727         /*
728          * There is no point in continuing if we can't allocate the minimum
729          * number of buffers needed by this vb2_queue.
730          */
731         if (allocated_buffers < q->min_buffers_needed)
732                 ret = -ENOMEM;
733
734         /*
735          * Check if driver can handle the allocated number of buffers.
736          */
737         if (!ret && allocated_buffers < num_buffers) {
738                 num_buffers = allocated_buffers;
739                 /*
740                  * num_planes is set by the previous queue_setup(), but since it
741                  * signals to queue_setup() whether it is called from create_bufs()
742                  * vs reqbufs() we zero it here to signal that queue_setup() is
743                  * called for the reqbufs() case.
744                  */
745                 num_planes = 0;
746
747                 ret = call_qop(q, queue_setup, q, &num_buffers,
748                                &num_planes, plane_sizes, q->alloc_devs);
749
750                 if (!ret && allocated_buffers < num_buffers)
751                         ret = -ENOMEM;
752
753                 /*
754                  * Either the driver has accepted a smaller number of buffers,
755                  * or .queue_setup() returned an error
756                  */
757         }
758
759         mutex_lock(&q->mmap_lock);
760         q->num_buffers = allocated_buffers;
761
762         if (ret < 0) {
763                 /*
764                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
765                  * from q->num_buffers.
766                  */
767                 __vb2_queue_free(q, allocated_buffers);
768                 mutex_unlock(&q->mmap_lock);
769                 return ret;
770         }
771         mutex_unlock(&q->mmap_lock);
772
773         /*
774          * Return the number of successfully allocated buffers
775          * to the userspace.
776          */
777         *count = allocated_buffers;
778         q->waiting_for_buffers = !q->is_output;
779
780         return 0;
781 }
782 EXPORT_SYMBOL_GPL(vb2_core_reqbufs);
783
784 int vb2_core_create_bufs(struct vb2_queue *q, enum vb2_memory memory,
785                 unsigned int *count, unsigned requested_planes,
786                 const unsigned requested_sizes[])
787 {
788         unsigned int num_planes = 0, num_buffers, allocated_buffers;
789         unsigned plane_sizes[VB2_MAX_PLANES] = { };
790         int ret;
791
792         if (q->num_buffers == VB2_MAX_FRAME) {
793                 dprintk(1, "maximum number of buffers already allocated\n");
794                 return -ENOBUFS;
795         }
796
797         if (!q->num_buffers) {
798                 memset(q->alloc_devs, 0, sizeof(q->alloc_devs));
799                 q->memory = memory;
800                 q->waiting_for_buffers = !q->is_output;
801         }
802
803         num_buffers = min(*count, VB2_MAX_FRAME - q->num_buffers);
804
805         if (requested_planes && requested_sizes) {
806                 num_planes = requested_planes;
807                 memcpy(plane_sizes, requested_sizes, sizeof(plane_sizes));
808         }
809
810         /*
811          * Ask the driver, whether the requested number of buffers, planes per
812          * buffer and their sizes are acceptable
813          */
814         ret = call_qop(q, queue_setup, q, &num_buffers,
815                        &num_planes, plane_sizes, q->alloc_devs);
816         if (ret)
817                 return ret;
818
819         /* Finally, allocate buffers and video memory */
820         allocated_buffers = __vb2_queue_alloc(q, memory, num_buffers,
821                                 num_planes, plane_sizes);
822         if (allocated_buffers == 0) {
823                 dprintk(1, "memory allocation failed\n");
824                 return -ENOMEM;
825         }
826
827         /*
828          * Check if driver can handle the so far allocated number of buffers.
829          */
830         if (allocated_buffers < num_buffers) {
831                 num_buffers = allocated_buffers;
832
833                 /*
834                  * q->num_buffers contains the total number of buffers, that the
835                  * queue driver has set up
836                  */
837                 ret = call_qop(q, queue_setup, q, &num_buffers,
838                                &num_planes, plane_sizes, q->alloc_devs);
839
840                 if (!ret && allocated_buffers < num_buffers)
841                         ret = -ENOMEM;
842
843                 /*
844                  * Either the driver has accepted a smaller number of buffers,
845                  * or .queue_setup() returned an error
846                  */
847         }
848
849         mutex_lock(&q->mmap_lock);
850         q->num_buffers += allocated_buffers;
851
852         if (ret < 0) {
853                 /*
854                  * Note: __vb2_queue_free() will subtract 'allocated_buffers'
855                  * from q->num_buffers.
856                  */
857                 __vb2_queue_free(q, allocated_buffers);
858                 mutex_unlock(&q->mmap_lock);
859                 return -ENOMEM;
860         }
861         mutex_unlock(&q->mmap_lock);
862
863         /*
864          * Return the number of successfully allocated buffers
865          * to the userspace.
866          */
867         *count = allocated_buffers;
868
869         return 0;
870 }
871 EXPORT_SYMBOL_GPL(vb2_core_create_bufs);
872
873 void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
874 {
875         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
876                 return NULL;
877
878         return call_ptr_memop(vb, vaddr, vb->planes[plane_no].mem_priv);
879
880 }
881 EXPORT_SYMBOL_GPL(vb2_plane_vaddr);
882
883 void *vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
884 {
885         if (plane_no >= vb->num_planes || !vb->planes[plane_no].mem_priv)
886                 return NULL;
887
888         return call_ptr_memop(vb, cookie, vb->planes[plane_no].mem_priv);
889 }
890 EXPORT_SYMBOL_GPL(vb2_plane_cookie);
891
892 void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
893 {
894         struct vb2_queue *q = vb->vb2_queue;
895         unsigned long flags;
896         unsigned int plane;
897
898         if (WARN_ON(vb->state != VB2_BUF_STATE_ACTIVE))
899                 return;
900
901         if (WARN_ON(state != VB2_BUF_STATE_DONE &&
902                     state != VB2_BUF_STATE_ERROR &&
903                     state != VB2_BUF_STATE_QUEUED &&
904                     state != VB2_BUF_STATE_REQUEUEING))
905                 state = VB2_BUF_STATE_ERROR;
906
907 #ifdef CONFIG_VIDEO_ADV_DEBUG
908         /*
909          * Although this is not a callback, it still does have to balance
910          * with the buf_queue op. So update this counter manually.
911          */
912         vb->cnt_buf_done++;
913 #endif
914         dprintk(4, "done processing on buffer %d, state: %d\n",
915                         vb->index, state);
916
917         /* sync buffers */
918         for (plane = 0; plane < vb->num_planes; ++plane)
919                 call_void_memop(vb, finish, vb->planes[plane].mem_priv);
920
921         spin_lock_irqsave(&q->done_lock, flags);
922         if (state == VB2_BUF_STATE_QUEUED ||
923             state == VB2_BUF_STATE_REQUEUEING) {
924                 vb->state = VB2_BUF_STATE_QUEUED;
925         } else {
926                 /* Add the buffer to the done buffers list */
927                 list_add_tail(&vb->done_entry, &q->done_list);
928                 vb->state = state;
929         }
930         atomic_dec(&q->owned_by_drv_count);
931         spin_unlock_irqrestore(&q->done_lock, flags);
932
933         trace_vb2_buf_done(q, vb);
934
935         switch (state) {
936         case VB2_BUF_STATE_QUEUED:
937                 return;
938         case VB2_BUF_STATE_REQUEUEING:
939                 if (q->start_streaming_called)
940                         __enqueue_in_driver(vb);
941                 return;
942         default:
943                 /* Inform any processes that may be waiting for buffers */
944                 wake_up(&q->done_wq);
945                 break;
946         }
947 }
948 EXPORT_SYMBOL_GPL(vb2_buffer_done);
949
950 void vb2_discard_done(struct vb2_queue *q)
951 {
952         struct vb2_buffer *vb;
953         unsigned long flags;
954
955         spin_lock_irqsave(&q->done_lock, flags);
956         list_for_each_entry(vb, &q->done_list, done_entry)
957                 vb->state = VB2_BUF_STATE_ERROR;
958         spin_unlock_irqrestore(&q->done_lock, flags);
959 }
960 EXPORT_SYMBOL_GPL(vb2_discard_done);
961
962 /**
963  * __qbuf_mmap() - handle qbuf of an MMAP buffer
964  */
965 static int __qbuf_mmap(struct vb2_buffer *vb, const void *pb)
966 {
967         int ret = 0;
968
969         if (pb)
970                 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
971                                  vb, pb, vb->planes);
972         return ret ? ret : call_vb_qop(vb, buf_prepare, vb);
973 }
974
975 /**
976  * __qbuf_userptr() - handle qbuf of a USERPTR buffer
977  */
978 static int __qbuf_userptr(struct vb2_buffer *vb, const void *pb)
979 {
980         struct vb2_plane planes[VB2_MAX_PLANES];
981         struct vb2_queue *q = vb->vb2_queue;
982         void *mem_priv;
983         unsigned int plane;
984         int ret = 0;
985         enum dma_data_direction dma_dir =
986                 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
987         bool reacquired = vb->planes[0].mem_priv == NULL;
988
989         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
990         /* Copy relevant information provided by the userspace */
991         if (pb)
992                 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
993                                  vb, pb, planes);
994         if (ret)
995                 return ret;
996
997         for (plane = 0; plane < vb->num_planes; ++plane) {
998                 /* Skip the plane if already verified */
999                 if (vb->planes[plane].m.userptr &&
1000                         vb->planes[plane].m.userptr == planes[plane].m.userptr
1001                         && vb->planes[plane].length == planes[plane].length)
1002                         continue;
1003
1004                 dprintk(3, "userspace address for plane %d changed, "
1005                                 "reacquiring memory\n", plane);
1006
1007                 /* Check if the provided plane buffer is large enough */
1008                 if (planes[plane].length < vb->planes[plane].min_length) {
1009                         dprintk(1, "provided buffer size %u is less than "
1010                                                 "setup size %u for plane %d\n",
1011                                                 planes[plane].length,
1012                                                 vb->planes[plane].min_length,
1013                                                 plane);
1014                         ret = -EINVAL;
1015                         goto err;
1016                 }
1017
1018                 /* Release previously acquired memory if present */
1019                 if (vb->planes[plane].mem_priv) {
1020                         if (!reacquired) {
1021                                 reacquired = true;
1022                                 call_void_vb_qop(vb, buf_cleanup, vb);
1023                         }
1024                         call_void_memop(vb, put_userptr, vb->planes[plane].mem_priv);
1025                 }
1026
1027                 vb->planes[plane].mem_priv = NULL;
1028                 vb->planes[plane].bytesused = 0;
1029                 vb->planes[plane].length = 0;
1030                 vb->planes[plane].m.userptr = 0;
1031                 vb->planes[plane].data_offset = 0;
1032
1033                 /* Acquire each plane's memory */
1034                 mem_priv = call_ptr_memop(vb, get_userptr,
1035                                 q->alloc_devs[plane] ? : q->dev,
1036                                 planes[plane].m.userptr,
1037                                 planes[plane].length, dma_dir);
1038                 if (IS_ERR(mem_priv)) {
1039                         dprintk(1, "failed acquiring userspace "
1040                                                 "memory for plane %d\n", plane);
1041                         ret = PTR_ERR(mem_priv);
1042                         goto err;
1043                 }
1044                 vb->planes[plane].mem_priv = mem_priv;
1045         }
1046
1047         /*
1048          * Now that everything is in order, copy relevant information
1049          * provided by userspace.
1050          */
1051         for (plane = 0; plane < vb->num_planes; ++plane) {
1052                 vb->planes[plane].bytesused = planes[plane].bytesused;
1053                 vb->planes[plane].length = planes[plane].length;
1054                 vb->planes[plane].m.userptr = planes[plane].m.userptr;
1055                 vb->planes[plane].data_offset = planes[plane].data_offset;
1056         }
1057
1058         if (reacquired) {
1059                 /*
1060                  * One or more planes changed, so we must call buf_init to do
1061                  * the driver-specific initialization on the newly acquired
1062                  * buffer, if provided.
1063                  */
1064                 ret = call_vb_qop(vb, buf_init, vb);
1065                 if (ret) {
1066                         dprintk(1, "buffer initialization failed\n");
1067                         goto err;
1068                 }
1069         }
1070
1071         ret = call_vb_qop(vb, buf_prepare, vb);
1072         if (ret) {
1073                 dprintk(1, "buffer preparation failed\n");
1074                 call_void_vb_qop(vb, buf_cleanup, vb);
1075                 goto err;
1076         }
1077
1078         return 0;
1079 err:
1080         /* In case of errors, release planes that were already acquired */
1081         for (plane = 0; plane < vb->num_planes; ++plane) {
1082                 if (vb->planes[plane].mem_priv)
1083                         call_void_memop(vb, put_userptr,
1084                                 vb->planes[plane].mem_priv);
1085                 vb->planes[plane].mem_priv = NULL;
1086                 vb->planes[plane].m.userptr = 0;
1087                 vb->planes[plane].length = 0;
1088         }
1089
1090         return ret;
1091 }
1092
1093 /**
1094  * __qbuf_dmabuf() - handle qbuf of a DMABUF buffer
1095  */
1096 static int __qbuf_dmabuf(struct vb2_buffer *vb, const void *pb)
1097 {
1098         struct vb2_plane planes[VB2_MAX_PLANES];
1099         struct vb2_queue *q = vb->vb2_queue;
1100         void *mem_priv;
1101         unsigned int plane;
1102         int ret = 0;
1103         enum dma_data_direction dma_dir =
1104                 q->is_output ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1105         bool reacquired = vb->planes[0].mem_priv == NULL;
1106
1107         memset(planes, 0, sizeof(planes[0]) * vb->num_planes);
1108         /* Copy relevant information provided by the userspace */
1109         if (pb)
1110                 ret = call_bufop(vb->vb2_queue, fill_vb2_buffer,
1111                                  vb, pb, planes);
1112         if (ret)
1113                 return ret;
1114
1115         for (plane = 0; plane < vb->num_planes; ++plane) {
1116                 struct dma_buf *dbuf = dma_buf_get(planes[plane].m.fd);
1117
1118                 if (IS_ERR_OR_NULL(dbuf)) {
1119                         dprintk(1, "invalid dmabuf fd for plane %d\n",
1120                                 plane);
1121                         ret = -EINVAL;
1122                         goto err;
1123                 }
1124
1125                 /* use DMABUF size if length is not provided */
1126                 if (planes[plane].length == 0)
1127                         planes[plane].length = dbuf->size;
1128
1129                 if (planes[plane].length < vb->planes[plane].min_length) {
1130                         dprintk(1, "invalid dmabuf length %u for plane %d, "
1131                                 "minimum length %u\n",
1132                                 planes[plane].length, plane,
1133                                 vb->planes[plane].min_length);
1134                         dma_buf_put(dbuf);
1135                         ret = -EINVAL;
1136                         goto err;
1137                 }
1138
1139                 /* Skip the plane if already verified */
1140                 if (dbuf == vb->planes[plane].dbuf &&
1141                         vb->planes[plane].length == planes[plane].length) {
1142                         dma_buf_put(dbuf);
1143                         continue;
1144                 }
1145
1146                 dprintk(1, "buffer for plane %d changed\n", plane);
1147
1148                 if (!reacquired) {
1149                         reacquired = true;
1150                         call_void_vb_qop(vb, buf_cleanup, vb);
1151                 }
1152
1153                 /* Release previously acquired memory if present */
1154                 __vb2_plane_dmabuf_put(vb, &vb->planes[plane]);
1155                 vb->planes[plane].bytesused = 0;
1156                 vb->planes[plane].length = 0;
1157                 vb->planes[plane].m.fd = 0;
1158                 vb->planes[plane].data_offset = 0;
1159
1160                 /* Acquire each plane's memory */
1161                 mem_priv = call_ptr_memop(vb, attach_dmabuf,
1162                                 q->alloc_devs[plane] ? : q->dev,
1163                                 dbuf, planes[plane].length, dma_dir);
1164                 if (IS_ERR(mem_priv)) {
1165                         dprintk(1, "failed to attach dmabuf\n");
1166                         ret = PTR_ERR(mem_priv);
1167                         dma_buf_put(dbuf);
1168                         goto err;
1169                 }
1170
1171                 vb->planes[plane].dbuf = dbuf;
1172                 vb->planes[plane].mem_priv = mem_priv;
1173         }
1174
1175         /*
1176          * This pins the buffer(s) with dma_buf_map_attachment()). It's done
1177          * here instead just before the DMA, while queueing the buffer(s) so
1178          * userspace knows sooner rather than later if the dma-buf map fails.
1179          */
1180         for (plane = 0; plane < vb->num_planes; ++plane) {
1181                 ret = call_memop(vb, map_dmabuf, vb->planes[plane].mem_priv);
1182                 if (ret) {
1183                         dprintk(1, "failed to map dmabuf for plane %d\n",
1184                                 plane);
1185                         goto err;
1186                 }
1187                 vb->planes[plane].dbuf_mapped = 1;
1188         }
1189
1190         /*
1191          * Now that everything is in order, copy relevant information
1192          * provided by userspace.
1193          */
1194         for (plane = 0; plane < vb->num_planes; ++plane) {
1195                 vb->planes[plane].bytesused = planes[plane].bytesused;
1196                 vb->planes[plane].length = planes[plane].length;
1197                 vb->planes[plane].m.fd = planes[plane].m.fd;
1198                 vb->planes[plane].data_offset = planes[plane].data_offset;
1199         }
1200
1201         if (reacquired) {
1202                 /*
1203                  * Call driver-specific initialization on the newly acquired buffer,
1204                  * if provided.
1205                  */
1206                 ret = call_vb_qop(vb, buf_init, vb);
1207                 if (ret) {
1208                         dprintk(1, "buffer initialization failed\n");
1209                         goto err;
1210                 }
1211         }
1212
1213         ret = call_vb_qop(vb, buf_prepare, vb);
1214         if (ret) {
1215                 dprintk(1, "buffer preparation failed\n");
1216                 call_void_vb_qop(vb, buf_cleanup, vb);
1217                 goto err;
1218         }
1219
1220         return 0;
1221 err:
1222         /* In case of errors, release planes that were already acquired */
1223         __vb2_buf_dmabuf_put(vb);
1224
1225         return ret;
1226 }
1227
1228 /**
1229  * __enqueue_in_driver() - enqueue a vb2_buffer in driver for processing
1230  */
1231 static void __enqueue_in_driver(struct vb2_buffer *vb)
1232 {
1233         struct vb2_queue *q = vb->vb2_queue;
1234         unsigned int plane;
1235
1236         vb->state = VB2_BUF_STATE_ACTIVE;
1237         atomic_inc(&q->owned_by_drv_count);
1238
1239         trace_vb2_buf_queue(q, vb);
1240
1241         /* sync buffers */
1242         for (plane = 0; plane < vb->num_planes; ++plane)
1243                 call_void_memop(vb, prepare, vb->planes[plane].mem_priv);
1244
1245         call_void_vb_qop(vb, buf_queue, vb);
1246 }
1247
1248 static int __buf_prepare(struct vb2_buffer *vb, const void *pb)
1249 {
1250         struct vb2_queue *q = vb->vb2_queue;
1251         int ret;
1252
1253         if (q->error) {
1254                 dprintk(1, "fatal error occurred on queue\n");
1255                 return -EIO;
1256         }
1257
1258         vb->state = VB2_BUF_STATE_PREPARING;
1259
1260         switch (q->memory) {
1261         case VB2_MEMORY_MMAP:
1262                 ret = __qbuf_mmap(vb, pb);
1263                 break;
1264         case VB2_MEMORY_USERPTR:
1265                 ret = __qbuf_userptr(vb, pb);
1266                 break;
1267         case VB2_MEMORY_DMABUF:
1268                 ret = __qbuf_dmabuf(vb, pb);
1269                 break;
1270         default:
1271                 WARN(1, "Invalid queue type\n");
1272                 ret = -EINVAL;
1273         }
1274
1275         if (ret)
1276                 dprintk(1, "buffer preparation failed: %d\n", ret);
1277         vb->state = ret ? VB2_BUF_STATE_DEQUEUED : VB2_BUF_STATE_PREPARED;
1278
1279         return ret;
1280 }
1281
1282 int vb2_core_prepare_buf(struct vb2_queue *q, unsigned int index, void *pb)
1283 {
1284         struct vb2_buffer *vb;
1285         int ret;
1286
1287         vb = q->bufs[index];
1288         if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1289                 dprintk(1, "invalid buffer state %d\n",
1290                         vb->state);
1291                 return -EINVAL;
1292         }
1293
1294         ret = __buf_prepare(vb, pb);
1295         if (ret)
1296                 return ret;
1297
1298         /* Fill buffer information for the userspace */
1299         call_void_bufop(q, fill_user_buffer, vb, pb);
1300
1301         dprintk(1, "prepare of buffer %d succeeded\n", vb->index);
1302
1303         return ret;
1304 }
1305 EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
1306
1307 /**
1308  * vb2_start_streaming() - Attempt to start streaming.
1309  * @q:          videobuf2 queue
1310  *
1311  * Attempt to start streaming. When this function is called there must be
1312  * at least q->min_buffers_needed buffers queued up (i.e. the minimum
1313  * number of buffers required for the DMA engine to function). If the
1314  * @start_streaming op fails it is supposed to return all the driver-owned
1315  * buffers back to vb2 in state QUEUED. Check if that happened and if
1316  * not warn and reclaim them forcefully.
1317  */
1318 static int vb2_start_streaming(struct vb2_queue *q)
1319 {
1320         struct vb2_buffer *vb;
1321         int ret;
1322
1323         /*
1324          * If any buffers were queued before streamon,
1325          * we can now pass them to driver for processing.
1326          */
1327         list_for_each_entry(vb, &q->queued_list, queued_entry)
1328                 __enqueue_in_driver(vb);
1329
1330         /* Tell the driver to start streaming */
1331         q->start_streaming_called = 1;
1332         ret = call_qop(q, start_streaming, q,
1333                        atomic_read(&q->owned_by_drv_count));
1334         if (!ret)
1335                 return 0;
1336
1337         q->start_streaming_called = 0;
1338
1339         dprintk(1, "driver refused to start streaming\n");
1340         /*
1341          * If you see this warning, then the driver isn't cleaning up properly
1342          * after a failed start_streaming(). See the start_streaming()
1343          * documentation in videobuf2-core.h for more information how buffers
1344          * should be returned to vb2 in start_streaming().
1345          */
1346         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1347                 unsigned i;
1348
1349                 /*
1350                  * Forcefully reclaim buffers if the driver did not
1351                  * correctly return them to vb2.
1352                  */
1353                 for (i = 0; i < q->num_buffers; ++i) {
1354                         vb = q->bufs[i];
1355                         if (vb->state == VB2_BUF_STATE_ACTIVE)
1356                                 vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED);
1357                 }
1358                 /* Must be zero now */
1359                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1360         }
1361         /*
1362          * If done_list is not empty, then start_streaming() didn't call
1363          * vb2_buffer_done(vb, VB2_BUF_STATE_QUEUED) but STATE_ERROR or
1364          * STATE_DONE.
1365          */
1366         WARN_ON(!list_empty(&q->done_list));
1367         return ret;
1368 }
1369
1370 int vb2_core_qbuf(struct vb2_queue *q, unsigned int index, void *pb)
1371 {
1372         struct vb2_buffer *vb;
1373         enum vb2_buffer_state orig_state;
1374         int ret;
1375
1376         if (q->error) {
1377                 dprintk(1, "fatal error occurred on queue\n");
1378                 return -EIO;
1379         }
1380
1381         vb = q->bufs[index];
1382
1383         switch (vb->state) {
1384         case VB2_BUF_STATE_DEQUEUED:
1385                 ret = __buf_prepare(vb, pb);
1386                 if (ret)
1387                         return ret;
1388                 break;
1389         case VB2_BUF_STATE_PREPARED:
1390                 break;
1391         case VB2_BUF_STATE_PREPARING:
1392                 dprintk(1, "buffer still being prepared\n");
1393                 return -EINVAL;
1394         default:
1395                 dprintk(1, "invalid buffer state %d\n", vb->state);
1396                 return -EINVAL;
1397         }
1398
1399         /*
1400          * Add to the queued buffers list, a buffer will stay on it until
1401          * dequeued in dqbuf.
1402          */
1403         orig_state = vb->state;
1404         list_add_tail(&vb->queued_entry, &q->queued_list);
1405         q->queued_count++;
1406         q->waiting_for_buffers = false;
1407         vb->state = VB2_BUF_STATE_QUEUED;
1408
1409         if (pb)
1410                 call_void_bufop(q, copy_timestamp, vb, pb);
1411
1412         trace_vb2_qbuf(q, vb);
1413
1414         /*
1415          * If already streaming, give the buffer to driver for processing.
1416          * If not, the buffer will be given to driver on next streamon.
1417          */
1418         if (q->start_streaming_called)
1419                 __enqueue_in_driver(vb);
1420
1421         /* Fill buffer information for the userspace */
1422         if (pb)
1423                 call_void_bufop(q, fill_user_buffer, vb, pb);
1424
1425         /*
1426          * If streamon has been called, and we haven't yet called
1427          * start_streaming() since not enough buffers were queued, and
1428          * we now have reached the minimum number of queued buffers,
1429          * then we can finally call start_streaming().
1430          */
1431         if (q->streaming && !q->start_streaming_called &&
1432             q->queued_count >= q->min_buffers_needed) {
1433                 ret = vb2_start_streaming(q);
1434                 if (ret) {
1435                         /*
1436                          * Since vb2_core_qbuf will return with an error,
1437                          * we should return it to state DEQUEUED since
1438                          * the error indicates that the buffer wasn't queued.
1439                          */
1440                         list_del(&vb->queued_entry);
1441                         q->queued_count--;
1442                         vb->state = orig_state;
1443                         return ret;
1444                 }
1445         }
1446
1447         dprintk(1, "qbuf of buffer %d succeeded\n", vb->index);
1448         return 0;
1449 }
1450 EXPORT_SYMBOL_GPL(vb2_core_qbuf);
1451
1452 /**
1453  * __vb2_wait_for_done_vb() - wait for a buffer to become available
1454  * for dequeuing
1455  *
1456  * Will sleep if required for nonblocking == false.
1457  */
1458 static int __vb2_wait_for_done_vb(struct vb2_queue *q, int nonblocking)
1459 {
1460         /*
1461          * All operations on vb_done_list are performed under done_lock
1462          * spinlock protection. However, buffers may be removed from
1463          * it and returned to userspace only while holding both driver's
1464          * lock and the done_lock spinlock. Thus we can be sure that as
1465          * long as we hold the driver's lock, the list will remain not
1466          * empty if list_empty() check succeeds.
1467          */
1468
1469         for (;;) {
1470                 int ret;
1471
1472                 if (!q->streaming) {
1473                         dprintk(1, "streaming off, will not wait for buffers\n");
1474                         return -EINVAL;
1475                 }
1476
1477                 if (q->error) {
1478                         dprintk(1, "Queue in error state, will not wait for buffers\n");
1479                         return -EIO;
1480                 }
1481
1482                 if (q->last_buffer_dequeued) {
1483                         dprintk(3, "last buffer dequeued already, will not wait for buffers\n");
1484                         return -EPIPE;
1485                 }
1486
1487                 if (!list_empty(&q->done_list)) {
1488                         /*
1489                          * Found a buffer that we were waiting for.
1490                          */
1491                         break;
1492                 }
1493
1494                 if (nonblocking) {
1495                         dprintk(1, "nonblocking and no buffers to dequeue, "
1496                                                                 "will not wait\n");
1497                         return -EAGAIN;
1498                 }
1499
1500                 /*
1501                  * We are streaming and blocking, wait for another buffer to
1502                  * become ready or for streamoff. Driver's lock is released to
1503                  * allow streamoff or qbuf to be called while waiting.
1504                  */
1505                 call_void_qop(q, wait_prepare, q);
1506
1507                 /*
1508                  * All locks have been released, it is safe to sleep now.
1509                  */
1510                 dprintk(3, "will sleep waiting for buffers\n");
1511                 ret = wait_event_interruptible(q->done_wq,
1512                                 !list_empty(&q->done_list) || !q->streaming ||
1513                                 q->error);
1514
1515                 /*
1516                  * We need to reevaluate both conditions again after reacquiring
1517                  * the locks or return an error if one occurred.
1518                  */
1519                 call_void_qop(q, wait_finish, q);
1520                 if (ret) {
1521                         dprintk(1, "sleep was interrupted\n");
1522                         return ret;
1523                 }
1524         }
1525         return 0;
1526 }
1527
1528 /**
1529  * __vb2_get_done_vb() - get a buffer ready for dequeuing
1530  *
1531  * Will sleep if required for nonblocking == false.
1532  */
1533 static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
1534                              void *pb, int nonblocking)
1535 {
1536         unsigned long flags;
1537         int ret = 0;
1538
1539         /*
1540          * Wait for at least one buffer to become available on the done_list.
1541          */
1542         ret = __vb2_wait_for_done_vb(q, nonblocking);
1543         if (ret)
1544                 return ret;
1545
1546         /*
1547          * Driver's lock has been held since we last verified that done_list
1548          * is not empty, so no need for another list_empty(done_list) check.
1549          */
1550         spin_lock_irqsave(&q->done_lock, flags);
1551         *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
1552         /*
1553          * Only remove the buffer from done_list if all planes can be
1554          * handled. Some cases such as V4L2 file I/O and DVB have pb
1555          * == NULL; skip the check then as there's nothing to verify.
1556          */
1557         if (pb)
1558                 ret = call_bufop(q, verify_planes_array, *vb, pb);
1559         if (!ret)
1560                 list_del(&(*vb)->done_entry);
1561         spin_unlock_irqrestore(&q->done_lock, flags);
1562
1563         return ret;
1564 }
1565
1566 int vb2_wait_for_all_buffers(struct vb2_queue *q)
1567 {
1568         if (!q->streaming) {
1569                 dprintk(1, "streaming off, will not wait for buffers\n");
1570                 return -EINVAL;
1571         }
1572
1573         if (q->start_streaming_called)
1574                 wait_event(q->done_wq, !atomic_read(&q->owned_by_drv_count));
1575         return 0;
1576 }
1577 EXPORT_SYMBOL_GPL(vb2_wait_for_all_buffers);
1578
1579 /**
1580  * __vb2_dqbuf() - bring back the buffer to the DEQUEUED state
1581  */
1582 static void __vb2_dqbuf(struct vb2_buffer *vb)
1583 {
1584         struct vb2_queue *q = vb->vb2_queue;
1585         unsigned int i;
1586
1587         /* nothing to do if the buffer is already dequeued */
1588         if (vb->state == VB2_BUF_STATE_DEQUEUED)
1589                 return;
1590
1591         vb->state = VB2_BUF_STATE_DEQUEUED;
1592
1593         /* unmap DMABUF buffer */
1594         if (q->memory == VB2_MEMORY_DMABUF)
1595                 for (i = 0; i < vb->num_planes; ++i) {
1596                         if (!vb->planes[i].dbuf_mapped)
1597                                 continue;
1598                         call_void_memop(vb, unmap_dmabuf, vb->planes[i].mem_priv);
1599                         vb->planes[i].dbuf_mapped = 0;
1600                 }
1601 }
1602
1603 int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb,
1604                    bool nonblocking)
1605 {
1606         struct vb2_buffer *vb = NULL;
1607         int ret;
1608
1609         ret = __vb2_get_done_vb(q, &vb, pb, nonblocking);
1610         if (ret < 0)
1611                 return ret;
1612
1613         switch (vb->state) {
1614         case VB2_BUF_STATE_DONE:
1615                 dprintk(3, "returning done buffer\n");
1616                 break;
1617         case VB2_BUF_STATE_ERROR:
1618                 dprintk(3, "returning done buffer with errors\n");
1619                 break;
1620         default:
1621                 dprintk(1, "invalid buffer state\n");
1622                 return -EINVAL;
1623         }
1624
1625         call_void_vb_qop(vb, buf_finish, vb);
1626
1627         if (pindex)
1628                 *pindex = vb->index;
1629
1630         /* Fill buffer information for the userspace */
1631         if (pb)
1632                 call_void_bufop(q, fill_user_buffer, vb, pb);
1633
1634         /* Remove from videobuf queue */
1635         list_del(&vb->queued_entry);
1636         q->queued_count--;
1637
1638         trace_vb2_dqbuf(q, vb);
1639
1640         /* go back to dequeued state */
1641         __vb2_dqbuf(vb);
1642
1643         dprintk(1, "dqbuf of buffer %d, with state %d\n",
1644                         vb->index, vb->state);
1645
1646         return 0;
1647
1648 }
1649 EXPORT_SYMBOL_GPL(vb2_core_dqbuf);
1650
1651 /**
1652  * __vb2_queue_cancel() - cancel and stop (pause) streaming
1653  *
1654  * Removes all queued buffers from driver's queue and all buffers queued by
1655  * userspace from videobuf's queue. Returns to state after reqbufs.
1656  */
1657 static void __vb2_queue_cancel(struct vb2_queue *q)
1658 {
1659         unsigned int i;
1660
1661         /*
1662          * Tell driver to stop all transactions and release all queued
1663          * buffers.
1664          */
1665         if (q->start_streaming_called)
1666                 call_void_qop(q, stop_streaming, q);
1667
1668         /*
1669          * If you see this warning, then the driver isn't cleaning up properly
1670          * in stop_streaming(). See the stop_streaming() documentation in
1671          * videobuf2-core.h for more information how buffers should be returned
1672          * to vb2 in stop_streaming().
1673          */
1674         if (WARN_ON(atomic_read(&q->owned_by_drv_count))) {
1675                 for (i = 0; i < q->num_buffers; ++i)
1676                         if (q->bufs[i]->state == VB2_BUF_STATE_ACTIVE)
1677                                 vb2_buffer_done(q->bufs[i], VB2_BUF_STATE_ERROR);
1678                 /* Must be zero now */
1679                 WARN_ON(atomic_read(&q->owned_by_drv_count));
1680         }
1681
1682         q->streaming = 0;
1683         q->start_streaming_called = 0;
1684         q->queued_count = 0;
1685         q->error = 0;
1686
1687         /*
1688          * Remove all buffers from videobuf's list...
1689          */
1690         INIT_LIST_HEAD(&q->queued_list);
1691         /*
1692          * ...and done list; userspace will not receive any buffers it
1693          * has not already dequeued before initiating cancel.
1694          */
1695         INIT_LIST_HEAD(&q->done_list);
1696         atomic_set(&q->owned_by_drv_count, 0);
1697         wake_up_all(&q->done_wq);
1698
1699         /*
1700          * Reinitialize all buffers for next use.
1701          * Make sure to call buf_finish for any queued buffers. Normally
1702          * that's done in dqbuf, but that's not going to happen when we
1703          * cancel the whole queue. Note: this code belongs here, not in
1704          * __vb2_dqbuf() since in vb2_core_dqbuf() there is a critical
1705          * call to __fill_user_buffer() after buf_finish(). That order can't
1706          * be changed, so we can't move the buf_finish() to __vb2_dqbuf().
1707          */
1708         for (i = 0; i < q->num_buffers; ++i) {
1709                 struct vb2_buffer *vb = q->bufs[i];
1710
1711                 if (vb->state != VB2_BUF_STATE_DEQUEUED) {
1712                         vb->state = VB2_BUF_STATE_PREPARED;
1713                         call_void_vb_qop(vb, buf_finish, vb);
1714                 }
1715                 __vb2_dqbuf(vb);
1716         }
1717 }
1718
1719 int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
1720 {
1721         int ret;
1722
1723         if (type != q->type) {
1724                 dprintk(1, "invalid stream type\n");
1725                 return -EINVAL;
1726         }
1727
1728         if (q->streaming) {
1729                 dprintk(3, "already streaming\n");
1730                 return 0;
1731         }
1732
1733         if (!q->num_buffers) {
1734                 dprintk(1, "no buffers have been allocated\n");
1735                 return -EINVAL;
1736         }
1737
1738         if (q->num_buffers < q->min_buffers_needed) {
1739                 dprintk(1, "need at least %u allocated buffers\n",
1740                                 q->min_buffers_needed);
1741                 return -EINVAL;
1742         }
1743
1744         /*
1745          * Tell driver to start streaming provided sufficient buffers
1746          * are available.
1747          */
1748         if (q->queued_count >= q->min_buffers_needed) {
1749                 ret = v4l_vb2q_enable_media_source(q);
1750                 if (ret)
1751                         return ret;
1752                 ret = vb2_start_streaming(q);
1753                 if (ret) {
1754                         __vb2_queue_cancel(q);
1755                         return ret;
1756                 }
1757         }
1758
1759         q->streaming = 1;
1760
1761         dprintk(3, "successful\n");
1762         return 0;
1763 }
1764 EXPORT_SYMBOL_GPL(vb2_core_streamon);
1765
1766 void vb2_queue_error(struct vb2_queue *q)
1767 {
1768         q->error = 1;
1769
1770         wake_up_all(&q->done_wq);
1771 }
1772 EXPORT_SYMBOL_GPL(vb2_queue_error);
1773
1774 int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
1775 {
1776         if (type != q->type) {
1777                 dprintk(1, "invalid stream type\n");
1778                 return -EINVAL;
1779         }
1780
1781         /*
1782          * Cancel will pause streaming and remove all buffers from the driver
1783          * and videobuf, effectively returning control over them to userspace.
1784          *
1785          * Note that we do this even if q->streaming == 0: if you prepare or
1786          * queue buffers, and then call streamoff without ever having called
1787          * streamon, you would still expect those buffers to be returned to
1788          * their normal dequeued state.
1789          */
1790         __vb2_queue_cancel(q);
1791         q->waiting_for_buffers = !q->is_output;
1792         q->last_buffer_dequeued = false;
1793
1794         dprintk(3, "successful\n");
1795         return 0;
1796 }
1797 EXPORT_SYMBOL_GPL(vb2_core_streamoff);
1798
1799 /**
1800  * __find_plane_by_offset() - find plane associated with the given offset off
1801  */
1802 static int __find_plane_by_offset(struct vb2_queue *q, unsigned long off,
1803                         unsigned int *_buffer, unsigned int *_plane)
1804 {
1805         struct vb2_buffer *vb;
1806         unsigned int buffer, plane;
1807
1808         /*
1809          * Go over all buffers and their planes, comparing the given offset
1810          * with an offset assigned to each plane. If a match is found,
1811          * return its buffer and plane numbers.
1812          */
1813         for (buffer = 0; buffer < q->num_buffers; ++buffer) {
1814                 vb = q->bufs[buffer];
1815
1816                 for (plane = 0; plane < vb->num_planes; ++plane) {
1817                         if (vb->planes[plane].m.offset == off) {
1818                                 *_buffer = buffer;
1819                                 *_plane = plane;
1820                                 return 0;
1821                         }
1822                 }
1823         }
1824
1825         return -EINVAL;
1826 }
1827
1828 int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type,
1829                 unsigned int index, unsigned int plane, unsigned int flags)
1830 {
1831         struct vb2_buffer *vb = NULL;
1832         struct vb2_plane *vb_plane;
1833         int ret;
1834         struct dma_buf *dbuf;
1835
1836         if (q->memory != VB2_MEMORY_MMAP) {
1837                 dprintk(1, "queue is not currently set up for mmap\n");
1838                 return -EINVAL;
1839         }
1840
1841         if (!q->mem_ops->get_dmabuf) {
1842                 dprintk(1, "queue does not support DMA buffer exporting\n");
1843                 return -EINVAL;
1844         }
1845
1846         if (flags & ~(O_CLOEXEC | O_ACCMODE)) {
1847                 dprintk(1, "queue does support only O_CLOEXEC and access mode flags\n");
1848                 return -EINVAL;
1849         }
1850
1851         if (type != q->type) {
1852                 dprintk(1, "invalid buffer type\n");
1853                 return -EINVAL;
1854         }
1855
1856         if (index >= q->num_buffers) {
1857                 dprintk(1, "buffer index out of range\n");
1858                 return -EINVAL;
1859         }
1860
1861         vb = q->bufs[index];
1862
1863         if (plane >= vb->num_planes) {
1864                 dprintk(1, "buffer plane out of range\n");
1865                 return -EINVAL;
1866         }
1867
1868         if (vb2_fileio_is_active(q)) {
1869                 dprintk(1, "expbuf: file io in progress\n");
1870                 return -EBUSY;
1871         }
1872
1873         vb_plane = &vb->planes[plane];
1874
1875         dbuf = call_ptr_memop(vb, get_dmabuf, vb_plane->mem_priv,
1876                                 flags & O_ACCMODE);
1877         if (IS_ERR_OR_NULL(dbuf)) {
1878                 dprintk(1, "failed to export buffer %d, plane %d\n",
1879                         index, plane);
1880                 return -EINVAL;
1881         }
1882
1883         ret = dma_buf_fd(dbuf, flags & ~O_ACCMODE);
1884         if (ret < 0) {
1885                 dprintk(3, "buffer %d, plane %d failed to export (%d)\n",
1886                         index, plane, ret);
1887                 dma_buf_put(dbuf);
1888                 return ret;
1889         }
1890
1891         dprintk(3, "buffer %d, plane %d exported as %d descriptor\n",
1892                 index, plane, ret);
1893         *fd = ret;
1894
1895         return 0;
1896 }
1897 EXPORT_SYMBOL_GPL(vb2_core_expbuf);
1898
1899 int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
1900 {
1901         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1902         struct vb2_buffer *vb;
1903         unsigned int buffer = 0, plane = 0;
1904         int ret;
1905         unsigned long length;
1906
1907         if (q->memory != VB2_MEMORY_MMAP) {
1908                 dprintk(1, "queue is not currently set up for mmap\n");
1909                 return -EINVAL;
1910         }
1911
1912         /*
1913          * Check memory area access mode.
1914          */
1915         if (!(vma->vm_flags & VM_SHARED)) {
1916                 dprintk(1, "invalid vma flags, VM_SHARED needed\n");
1917                 return -EINVAL;
1918         }
1919         if (q->is_output) {
1920                 if (!(vma->vm_flags & VM_WRITE)) {
1921                         dprintk(1, "invalid vma flags, VM_WRITE needed\n");
1922                         return -EINVAL;
1923                 }
1924         } else {
1925                 if (!(vma->vm_flags & VM_READ)) {
1926                         dprintk(1, "invalid vma flags, VM_READ needed\n");
1927                         return -EINVAL;
1928                 }
1929         }
1930
1931         mutex_lock(&q->mmap_lock);
1932
1933         if (vb2_fileio_is_active(q)) {
1934                 dprintk(1, "mmap: file io in progress\n");
1935                 ret = -EBUSY;
1936                 goto unlock;
1937         }
1938
1939         /*
1940          * Find the plane corresponding to the offset passed by userspace.
1941          */
1942         ret = __find_plane_by_offset(q, off, &buffer, &plane);
1943         if (ret)
1944                 goto unlock;
1945
1946         vb = q->bufs[buffer];
1947
1948         /*
1949          * MMAP requires page_aligned buffers.
1950          * The buffer length was page_aligned at __vb2_buf_mem_alloc(),
1951          * so, we need to do the same here.
1952          */
1953         length = PAGE_ALIGN(vb->planes[plane].length);
1954         if (length < (vma->vm_end - vma->vm_start)) {
1955                 dprintk(1,
1956                         "MMAP invalid, as it would overflow buffer length\n");
1957                 ret = -EINVAL;
1958                 goto unlock;
1959         }
1960
1961         ret = call_memop(vb, mmap, vb->planes[plane].mem_priv, vma);
1962
1963 unlock:
1964         mutex_unlock(&q->mmap_lock);
1965         if (ret)
1966                 return ret;
1967
1968         dprintk(3, "buffer %d, plane %d successfully mapped\n", buffer, plane);
1969         return 0;
1970 }
1971 EXPORT_SYMBOL_GPL(vb2_mmap);
1972
1973 #ifndef CONFIG_MMU
1974 unsigned long vb2_get_unmapped_area(struct vb2_queue *q,
1975                                     unsigned long addr,
1976                                     unsigned long len,
1977                                     unsigned long pgoff,
1978                                     unsigned long flags)
1979 {
1980         unsigned long off = pgoff << PAGE_SHIFT;
1981         struct vb2_buffer *vb;
1982         unsigned int buffer, plane;
1983         void *vaddr;
1984         int ret;
1985
1986         if (q->memory != VB2_MEMORY_MMAP) {
1987                 dprintk(1, "queue is not currently set up for mmap\n");
1988                 return -EINVAL;
1989         }
1990
1991         /*
1992          * Find the plane corresponding to the offset passed by userspace.
1993          */
1994         ret = __find_plane_by_offset(q, off, &buffer, &plane);
1995         if (ret)
1996                 return ret;
1997
1998         vb = q->bufs[buffer];
1999
2000         vaddr = vb2_plane_vaddr(vb, plane);
2001         return vaddr ? (unsigned long)vaddr : -EINVAL;
2002 }
2003 EXPORT_SYMBOL_GPL(vb2_get_unmapped_area);
2004 #endif
2005
2006 int vb2_core_queue_init(struct vb2_queue *q)
2007 {
2008         /*
2009          * Sanity check
2010          */
2011         if (WARN_ON(!q)                   ||
2012             WARN_ON(!q->ops)              ||
2013             WARN_ON(!q->mem_ops)          ||
2014             WARN_ON(!q->type)             ||
2015             WARN_ON(!q->io_modes)         ||
2016             WARN_ON(!q->ops->queue_setup) ||
2017             WARN_ON(!q->ops->buf_queue))
2018                 return -EINVAL;
2019
2020         INIT_LIST_HEAD(&q->queued_list);
2021         INIT_LIST_HEAD(&q->done_list);
2022         spin_lock_init(&q->done_lock);
2023         mutex_init(&q->mmap_lock);
2024         init_waitqueue_head(&q->done_wq);
2025
2026         if (q->buf_struct_size == 0)
2027                 q->buf_struct_size = sizeof(struct vb2_buffer);
2028
2029         return 0;
2030 }
2031 EXPORT_SYMBOL_GPL(vb2_core_queue_init);
2032
2033 static int __vb2_init_fileio(struct vb2_queue *q, int read);
2034 static int __vb2_cleanup_fileio(struct vb2_queue *q);
2035 void vb2_core_queue_release(struct vb2_queue *q)
2036 {
2037         __vb2_cleanup_fileio(q);
2038         __vb2_queue_cancel(q);
2039         mutex_lock(&q->mmap_lock);
2040         __vb2_queue_free(q, q->num_buffers);
2041         mutex_unlock(&q->mmap_lock);
2042 }
2043 EXPORT_SYMBOL_GPL(vb2_core_queue_release);
2044
2045 unsigned int vb2_core_poll(struct vb2_queue *q, struct file *file,
2046                 poll_table *wait)
2047 {
2048         unsigned long req_events = poll_requested_events(wait);
2049         struct vb2_buffer *vb = NULL;
2050         unsigned long flags;
2051
2052         if (!q->is_output && !(req_events & (POLLIN | POLLRDNORM)))
2053                 return 0;
2054         if (q->is_output && !(req_events & (POLLOUT | POLLWRNORM)))
2055                 return 0;
2056
2057         /*
2058          * Start file I/O emulator only if streaming API has not been used yet.
2059          */
2060         if (q->num_buffers == 0 && !vb2_fileio_is_active(q)) {
2061                 if (!q->is_output && (q->io_modes & VB2_READ) &&
2062                                 (req_events & (POLLIN | POLLRDNORM))) {
2063                         if (__vb2_init_fileio(q, 1))
2064                                 return POLLERR;
2065                 }
2066                 if (q->is_output && (q->io_modes & VB2_WRITE) &&
2067                                 (req_events & (POLLOUT | POLLWRNORM))) {
2068                         if (__vb2_init_fileio(q, 0))
2069                                 return POLLERR;
2070                         /*
2071                          * Write to OUTPUT queue can be done immediately.
2072                          */
2073                         return POLLOUT | POLLWRNORM;
2074                 }
2075         }
2076
2077         /*
2078          * There is nothing to wait for if the queue isn't streaming, or if the
2079          * error flag is set.
2080          */
2081         if (!vb2_is_streaming(q) || q->error)
2082                 return POLLERR;
2083
2084         /*
2085          * If this quirk is set and QBUF hasn't been called yet then
2086          * return POLLERR as well. This only affects capture queues, output
2087          * queues will always initialize waiting_for_buffers to false.
2088          * This quirk is set by V4L2 for backwards compatibility reasons.
2089          */
2090         if (q->quirk_poll_must_check_waiting_for_buffers &&
2091             q->waiting_for_buffers && (req_events & (POLLIN | POLLRDNORM)))
2092                 return POLLERR;
2093
2094         /*
2095          * For output streams you can call write() as long as there are fewer
2096          * buffers queued than there are buffers available.
2097          */
2098         if (q->is_output && q->fileio && q->queued_count < q->num_buffers)
2099                 return POLLOUT | POLLWRNORM;
2100
2101         if (list_empty(&q->done_list)) {
2102                 /*
2103                  * If the last buffer was dequeued from a capture queue,
2104                  * return immediately. DQBUF will return -EPIPE.
2105                  */
2106                 if (q->last_buffer_dequeued)
2107                         return POLLIN | POLLRDNORM;
2108
2109                 poll_wait(file, &q->done_wq, wait);
2110         }
2111
2112         /*
2113          * Take first buffer available for dequeuing.
2114          */
2115         spin_lock_irqsave(&q->done_lock, flags);
2116         if (!list_empty(&q->done_list))
2117                 vb = list_first_entry(&q->done_list, struct vb2_buffer,
2118                                         done_entry);
2119         spin_unlock_irqrestore(&q->done_lock, flags);
2120
2121         if (vb && (vb->state == VB2_BUF_STATE_DONE
2122                         || vb->state == VB2_BUF_STATE_ERROR)) {
2123                 return (q->is_output) ?
2124                                 POLLOUT | POLLWRNORM :
2125                                 POLLIN | POLLRDNORM;
2126         }
2127         return 0;
2128 }
2129 EXPORT_SYMBOL_GPL(vb2_core_poll);
2130
2131 /**
2132  * struct vb2_fileio_buf - buffer context used by file io emulator
2133  *
2134  * vb2 provides a compatibility layer and emulator of file io (read and
2135  * write) calls on top of streaming API. This structure is used for
2136  * tracking context related to the buffers.
2137  */
2138 struct vb2_fileio_buf {
2139         void *vaddr;
2140         unsigned int size;
2141         unsigned int pos;
2142         unsigned int queued:1;
2143 };
2144
2145 /**
2146  * struct vb2_fileio_data - queue context used by file io emulator
2147  *
2148  * @cur_index:  the index of the buffer currently being read from or
2149  *              written to. If equal to q->num_buffers then a new buffer
2150  *              must be dequeued.
2151  * @initial_index: in the read() case all buffers are queued up immediately
2152  *              in __vb2_init_fileio() and __vb2_perform_fileio() just cycles
2153  *              buffers. However, in the write() case no buffers are initially
2154  *              queued, instead whenever a buffer is full it is queued up by
2155  *              __vb2_perform_fileio(). Only once all available buffers have
2156  *              been queued up will __vb2_perform_fileio() start to dequeue
2157  *              buffers. This means that initially __vb2_perform_fileio()
2158  *              needs to know what buffer index to use when it is queuing up
2159  *              the buffers for the first time. That initial index is stored
2160  *              in this field. Once it is equal to q->num_buffers all
2161  *              available buffers have been queued and __vb2_perform_fileio()
2162  *              should start the normal dequeue/queue cycle.
2163  *
2164  * vb2 provides a compatibility layer and emulator of file io (read and
2165  * write) calls on top of streaming API. For proper operation it required
2166  * this structure to save the driver state between each call of the read
2167  * or write function.
2168  */
2169 struct vb2_fileio_data {
2170         unsigned int count;
2171         unsigned int type;
2172         unsigned int memory;
2173         struct vb2_fileio_buf bufs[VB2_MAX_FRAME];
2174         unsigned int cur_index;
2175         unsigned int initial_index;
2176         unsigned int q_count;
2177         unsigned int dq_count;
2178         unsigned read_once:1;
2179         unsigned write_immediately:1;
2180 };
2181
2182 /**
2183  * __vb2_init_fileio() - initialize file io emulator
2184  * @q:          videobuf2 queue
2185  * @read:       mode selector (1 means read, 0 means write)
2186  */
2187 static int __vb2_init_fileio(struct vb2_queue *q, int read)
2188 {
2189         struct vb2_fileio_data *fileio;
2190         int i, ret;
2191         unsigned int count = 0;
2192
2193         /*
2194          * Sanity check
2195          */
2196         if (WARN_ON((read && !(q->io_modes & VB2_READ)) ||
2197                     (!read && !(q->io_modes & VB2_WRITE))))
2198                 return -EINVAL;
2199
2200         /*
2201          * Check if device supports mapping buffers to kernel virtual space.
2202          */
2203         if (!q->mem_ops->vaddr)
2204                 return -EBUSY;
2205
2206         /*
2207          * Check if streaming api has not been already activated.
2208          */
2209         if (q->streaming || q->num_buffers > 0)
2210                 return -EBUSY;
2211
2212         /*
2213          * Start with count 1, driver can increase it in queue_setup()
2214          */
2215         count = 1;
2216
2217         dprintk(3, "setting up file io: mode %s, count %d, read_once %d, write_immediately %d\n",
2218                 (read) ? "read" : "write", count, q->fileio_read_once,
2219                 q->fileio_write_immediately);
2220
2221         fileio = kzalloc(sizeof(*fileio), GFP_KERNEL);
2222         if (fileio == NULL)
2223                 return -ENOMEM;
2224
2225         fileio->read_once = q->fileio_read_once;
2226         fileio->write_immediately = q->fileio_write_immediately;
2227
2228         /*
2229          * Request buffers and use MMAP type to force driver
2230          * to allocate buffers by itself.
2231          */
2232         fileio->count = count;
2233         fileio->memory = VB2_MEMORY_MMAP;
2234         fileio->type = q->type;
2235         q->fileio = fileio;
2236         ret = vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2237         if (ret)
2238                 goto err_kfree;
2239
2240         /*
2241          * Check if plane_count is correct
2242          * (multiplane buffers are not supported).
2243          */
2244         if (q->bufs[0]->num_planes != 1) {
2245                 ret = -EBUSY;
2246                 goto err_reqbufs;
2247         }
2248
2249         /*
2250          * Get kernel address of each buffer.
2251          */
2252         for (i = 0; i < q->num_buffers; i++) {
2253                 fileio->bufs[i].vaddr = vb2_plane_vaddr(q->bufs[i], 0);
2254                 if (fileio->bufs[i].vaddr == NULL) {
2255                         ret = -EINVAL;
2256                         goto err_reqbufs;
2257                 }
2258                 fileio->bufs[i].size = vb2_plane_size(q->bufs[i], 0);
2259         }
2260
2261         /*
2262          * Read mode requires pre queuing of all buffers.
2263          */
2264         if (read) {
2265                 /*
2266                  * Queue all buffers.
2267                  */
2268                 for (i = 0; i < q->num_buffers; i++) {
2269                         ret = vb2_core_qbuf(q, i, NULL);
2270                         if (ret)
2271                                 goto err_reqbufs;
2272                         fileio->bufs[i].queued = 1;
2273                 }
2274                 /*
2275                  * All buffers have been queued, so mark that by setting
2276                  * initial_index to q->num_buffers
2277                  */
2278                 fileio->initial_index = q->num_buffers;
2279                 fileio->cur_index = q->num_buffers;
2280         }
2281
2282         /*
2283          * Start streaming.
2284          */
2285         ret = vb2_core_streamon(q, q->type);
2286         if (ret)
2287                 goto err_reqbufs;
2288
2289         return ret;
2290
2291 err_reqbufs:
2292         fileio->count = 0;
2293         vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2294
2295 err_kfree:
2296         q->fileio = NULL;
2297         kfree(fileio);
2298         return ret;
2299 }
2300
2301 /**
2302  * __vb2_cleanup_fileio() - free resourced used by file io emulator
2303  * @q:          videobuf2 queue
2304  */
2305 static int __vb2_cleanup_fileio(struct vb2_queue *q)
2306 {
2307         struct vb2_fileio_data *fileio = q->fileio;
2308
2309         if (fileio) {
2310                 vb2_core_streamoff(q, q->type);
2311                 q->fileio = NULL;
2312                 fileio->count = 0;
2313                 vb2_core_reqbufs(q, fileio->memory, &fileio->count);
2314                 kfree(fileio);
2315                 dprintk(3, "file io emulator closed\n");
2316         }
2317         return 0;
2318 }
2319
2320 /**
2321  * __vb2_perform_fileio() - perform a single file io (read or write) operation
2322  * @q:          videobuf2 queue
2323  * @data:       pointed to target userspace buffer
2324  * @count:      number of bytes to read or write
2325  * @ppos:       file handle position tracking pointer
2326  * @nonblock:   mode selector (1 means blocking calls, 0 means nonblocking)
2327  * @read:       access mode selector (1 means read, 0 means write)
2328  */
2329 static size_t __vb2_perform_fileio(struct vb2_queue *q, char __user *data, size_t count,
2330                 loff_t *ppos, int nonblock, int read)
2331 {
2332         struct vb2_fileio_data *fileio;
2333         struct vb2_fileio_buf *buf;
2334         bool is_multiplanar = q->is_multiplanar;
2335         /*
2336          * When using write() to write data to an output video node the vb2 core
2337          * should copy timestamps if V4L2_BUF_FLAG_TIMESTAMP_COPY is set. Nobody
2338          * else is able to provide this information with the write() operation.
2339          */
2340         bool copy_timestamp = !read && q->copy_timestamp;
2341         unsigned index;
2342         int ret;
2343
2344         dprintk(3, "mode %s, offset %ld, count %zd, %sblocking\n",
2345                 read ? "read" : "write", (long)*ppos, count,
2346                 nonblock ? "non" : "");
2347
2348         if (!data)
2349                 return -EINVAL;
2350
2351         /*
2352          * Initialize emulator on first call.
2353          */
2354         if (!vb2_fileio_is_active(q)) {
2355                 ret = __vb2_init_fileio(q, read);
2356                 dprintk(3, "vb2_init_fileio result: %d\n", ret);
2357                 if (ret)
2358                         return ret;
2359         }
2360         fileio = q->fileio;
2361
2362         /*
2363          * Check if we need to dequeue the buffer.
2364          */
2365         index = fileio->cur_index;
2366         if (index >= q->num_buffers) {
2367                 struct vb2_buffer *b;
2368
2369                 /*
2370                  * Call vb2_dqbuf to get buffer back.
2371                  */
2372                 ret = vb2_core_dqbuf(q, &index, NULL, nonblock);
2373                 dprintk(5, "vb2_dqbuf result: %d\n", ret);
2374                 if (ret)
2375                         return ret;
2376                 fileio->dq_count += 1;
2377
2378                 fileio->cur_index = index;
2379                 buf = &fileio->bufs[index];
2380                 b = q->bufs[index];
2381
2382                 /*
2383                  * Get number of bytes filled by the driver
2384                  */
2385                 buf->pos = 0;
2386                 buf->queued = 0;
2387                 buf->size = read ? vb2_get_plane_payload(q->bufs[index], 0)
2388                                  : vb2_plane_size(q->bufs[index], 0);
2389                 /* Compensate for data_offset on read in the multiplanar case. */
2390                 if (is_multiplanar && read &&
2391                                 b->planes[0].data_offset < buf->size) {
2392                         buf->pos = b->planes[0].data_offset;
2393                         buf->size -= buf->pos;
2394                 }
2395         } else {
2396                 buf = &fileio->bufs[index];
2397         }
2398
2399         /*
2400          * Limit count on last few bytes of the buffer.
2401          */
2402         if (buf->pos + count > buf->size) {
2403                 count = buf->size - buf->pos;
2404                 dprintk(5, "reducing read count: %zd\n", count);
2405         }
2406
2407         /*
2408          * Transfer data to userspace.
2409          */
2410         dprintk(3, "copying %zd bytes - buffer %d, offset %u\n",
2411                 count, index, buf->pos);
2412         if (read)
2413                 ret = copy_to_user(data, buf->vaddr + buf->pos, count);
2414         else
2415                 ret = copy_from_user(buf->vaddr + buf->pos, data, count);
2416         if (ret) {
2417                 dprintk(3, "error copying data\n");
2418                 return -EFAULT;
2419         }
2420
2421         /*
2422          * Update counters.
2423          */
2424         buf->pos += count;
2425         *ppos += count;
2426
2427         /*
2428          * Queue next buffer if required.
2429          */
2430         if (buf->pos == buf->size || (!read && fileio->write_immediately)) {
2431                 struct vb2_buffer *b = q->bufs[index];
2432
2433                 /*
2434                  * Check if this is the last buffer to read.
2435                  */
2436                 if (read && fileio->read_once && fileio->dq_count == 1) {
2437                         dprintk(3, "read limit reached\n");
2438                         return __vb2_cleanup_fileio(q);
2439                 }
2440
2441                 /*
2442                  * Call vb2_qbuf and give buffer to the driver.
2443                  */
2444                 b->planes[0].bytesused = buf->pos;
2445
2446                 if (copy_timestamp)
2447                         b->timestamp = ktime_get_ns();
2448                 ret = vb2_core_qbuf(q, index, NULL);
2449                 dprintk(5, "vb2_dbuf result: %d\n", ret);
2450                 if (ret)
2451                         return ret;
2452
2453                 /*
2454                  * Buffer has been queued, update the status
2455                  */
2456                 buf->pos = 0;
2457                 buf->queued = 1;
2458                 buf->size = vb2_plane_size(q->bufs[index], 0);
2459                 fileio->q_count += 1;
2460                 /*
2461                  * If we are queuing up buffers for the first time, then
2462                  * increase initial_index by one.
2463                  */
2464                 if (fileio->initial_index < q->num_buffers)
2465                         fileio->initial_index++;
2466                 /*
2467                  * The next buffer to use is either a buffer that's going to be
2468                  * queued for the first time (initial_index < q->num_buffers)
2469                  * or it is equal to q->num_buffers, meaning that the next
2470                  * time we need to dequeue a buffer since we've now queued up
2471                  * all the 'first time' buffers.
2472                  */
2473                 fileio->cur_index = fileio->initial_index;
2474         }
2475
2476         /*
2477          * Return proper number of bytes processed.
2478          */
2479         if (ret == 0)
2480                 ret = count;
2481         return ret;
2482 }
2483
2484 size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count,
2485                 loff_t *ppos, int nonblocking)
2486 {
2487         return __vb2_perform_fileio(q, data, count, ppos, nonblocking, 1);
2488 }
2489 EXPORT_SYMBOL_GPL(vb2_read);
2490
2491 size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count,
2492                 loff_t *ppos, int nonblocking)
2493 {
2494         return __vb2_perform_fileio(q, (char __user *) data, count,
2495                                                         ppos, nonblocking, 0);
2496 }
2497 EXPORT_SYMBOL_GPL(vb2_write);
2498
2499 struct vb2_threadio_data {
2500         struct task_struct *thread;
2501         vb2_thread_fnc fnc;
2502         void *priv;
2503         bool stop;
2504 };
2505
2506 static int vb2_thread(void *data)
2507 {
2508         struct vb2_queue *q = data;
2509         struct vb2_threadio_data *threadio = q->threadio;
2510         bool copy_timestamp = false;
2511         unsigned prequeue = 0;
2512         unsigned index = 0;
2513         int ret = 0;
2514
2515         if (q->is_output) {
2516                 prequeue = q->num_buffers;
2517                 copy_timestamp = q->copy_timestamp;
2518         }
2519
2520         set_freezable();
2521
2522         for (;;) {
2523                 struct vb2_buffer *vb;
2524
2525                 /*
2526                  * Call vb2_dqbuf to get buffer back.
2527                  */
2528                 if (prequeue) {
2529                         vb = q->bufs[index++];
2530                         prequeue--;
2531                 } else {
2532                         call_void_qop(q, wait_finish, q);
2533                         if (!threadio->stop)
2534                                 ret = vb2_core_dqbuf(q, &index, NULL, 0);
2535                         call_void_qop(q, wait_prepare, q);
2536                         dprintk(5, "file io: vb2_dqbuf result: %d\n", ret);
2537                         if (!ret)
2538                                 vb = q->bufs[index];
2539                 }
2540                 if (ret || threadio->stop)
2541                         break;
2542                 try_to_freeze();
2543
2544                 if (vb->state != VB2_BUF_STATE_ERROR)
2545                         if (threadio->fnc(vb, threadio->priv))
2546                                 break;
2547                 call_void_qop(q, wait_finish, q);
2548                 if (copy_timestamp)
2549                         vb->timestamp = ktime_get_ns();;
2550                 if (!threadio->stop)
2551                         ret = vb2_core_qbuf(q, vb->index, NULL);
2552                 call_void_qop(q, wait_prepare, q);
2553                 if (ret || threadio->stop)
2554                         break;
2555         }
2556
2557         /* Hmm, linux becomes *very* unhappy without this ... */
2558         while (!kthread_should_stop()) {
2559                 set_current_state(TASK_INTERRUPTIBLE);
2560                 schedule();
2561         }
2562         return 0;
2563 }
2564
2565 /*
2566  * This function should not be used for anything else but the videobuf2-dvb
2567  * support. If you think you have another good use-case for this, then please
2568  * contact the linux-media mailinglist first.
2569  */
2570 int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv,
2571                      const char *thread_name)
2572 {
2573         struct vb2_threadio_data *threadio;
2574         int ret = 0;
2575
2576         if (q->threadio)
2577                 return -EBUSY;
2578         if (vb2_is_busy(q))
2579                 return -EBUSY;
2580         if (WARN_ON(q->fileio))
2581                 return -EBUSY;
2582
2583         threadio = kzalloc(sizeof(*threadio), GFP_KERNEL);
2584         if (threadio == NULL)
2585                 return -ENOMEM;
2586         threadio->fnc = fnc;
2587         threadio->priv = priv;
2588
2589         ret = __vb2_init_fileio(q, !q->is_output);
2590         dprintk(3, "file io: vb2_init_fileio result: %d\n", ret);
2591         if (ret)
2592                 goto nomem;
2593         q->threadio = threadio;
2594         threadio->thread = kthread_run(vb2_thread, q, "vb2-%s", thread_name);
2595         if (IS_ERR(threadio->thread)) {
2596                 ret = PTR_ERR(threadio->thread);
2597                 threadio->thread = NULL;
2598                 goto nothread;
2599         }
2600         return 0;
2601
2602 nothread:
2603         __vb2_cleanup_fileio(q);
2604 nomem:
2605         kfree(threadio);
2606         return ret;
2607 }
2608 EXPORT_SYMBOL_GPL(vb2_thread_start);
2609
2610 int vb2_thread_stop(struct vb2_queue *q)
2611 {
2612         struct vb2_threadio_data *threadio = q->threadio;
2613         int err;
2614
2615         if (threadio == NULL)
2616                 return 0;
2617         threadio->stop = true;
2618         /* Wake up all pending sleeps in the thread */
2619         vb2_queue_error(q);
2620         err = kthread_stop(threadio->thread);
2621         __vb2_cleanup_fileio(q);
2622         threadio->thread = NULL;
2623         kfree(threadio);
2624         q->threadio = NULL;
2625         return err;
2626 }
2627 EXPORT_SYMBOL_GPL(vb2_thread_stop);
2628
2629 MODULE_DESCRIPTION("Media buffer core framework");
2630 MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
2631 MODULE_LICENSE("GPL");