GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / media / platform / vimc / vimc-capture.c
1 /*
2  * vimc-capture.c Virtual Media Controller Driver
3  *
4  * Copyright (C) 2015-2017 Helen Koike <helen.fornazier@gmail.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  */
17
18 #include <linux/component.h>
19 #include <linux/module.h>
20 #include <linux/mod_devicetable.h>
21 #include <linux/platform_device.h>
22 #include <media/v4l2-ioctl.h>
23 #include <media/videobuf2-core.h>
24 #include <media/videobuf2-vmalloc.h>
25
26 #include "vimc-common.h"
27 #include "vimc-streamer.h"
28
29 #define VIMC_CAP_DRV_NAME "vimc-capture"
30
31 struct vimc_cap_device {
32         struct vimc_ent_device ved;
33         struct video_device vdev;
34         struct device *dev;
35         struct v4l2_pix_format format;
36         struct vb2_queue queue;
37         struct list_head buf_list;
38         /*
39          * NOTE: in a real driver, a spin lock must be used to access the
40          * queue because the frames are generated from a hardware interruption
41          * and the isr is not allowed to sleep.
42          * Even if it is not necessary a spinlock in the vimc driver, we
43          * use it here as a code reference
44          */
45         spinlock_t qlock;
46         struct mutex lock;
47         u32 sequence;
48         struct vimc_stream stream;
49 };
50
51 static const struct v4l2_pix_format fmt_default = {
52         .width = 640,
53         .height = 480,
54         .pixelformat = V4L2_PIX_FMT_RGB24,
55         .field = V4L2_FIELD_NONE,
56         .colorspace = V4L2_COLORSPACE_DEFAULT,
57 };
58
59 struct vimc_cap_buffer {
60         /*
61          * struct vb2_v4l2_buffer must be the first element
62          * the videobuf2 framework will allocate this struct based on
63          * buf_struct_size and use the first sizeof(struct vb2_buffer) bytes of
64          * memory as a vb2_buffer
65          */
66         struct vb2_v4l2_buffer vb2;
67         struct list_head list;
68 };
69
70 static int vimc_cap_querycap(struct file *file, void *priv,
71                              struct v4l2_capability *cap)
72 {
73         struct vimc_cap_device *vcap = video_drvdata(file);
74
75         strlcpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
76         strlcpy(cap->card, KBUILD_MODNAME, sizeof(cap->card));
77         snprintf(cap->bus_info, sizeof(cap->bus_info),
78                  "platform:%s", vcap->vdev.v4l2_dev->name);
79
80         return 0;
81 }
82
83 static void vimc_cap_get_format(struct vimc_ent_device *ved,
84                                 struct v4l2_pix_format *fmt)
85 {
86         struct vimc_cap_device *vcap = container_of(ved, struct vimc_cap_device,
87                                                     ved);
88
89         *fmt = vcap->format;
90 }
91
92 static int vimc_cap_g_fmt_vid_cap(struct file *file, void *priv,
93                                   struct v4l2_format *f)
94 {
95         struct vimc_cap_device *vcap = video_drvdata(file);
96
97         f->fmt.pix = vcap->format;
98
99         return 0;
100 }
101
102 static int vimc_cap_try_fmt_vid_cap(struct file *file, void *priv,
103                                     struct v4l2_format *f)
104 {
105         struct v4l2_pix_format *format = &f->fmt.pix;
106         const struct vimc_pix_map *vpix;
107
108         format->width = clamp_t(u32, format->width, VIMC_FRAME_MIN_WIDTH,
109                                 VIMC_FRAME_MAX_WIDTH) & ~1;
110         format->height = clamp_t(u32, format->height, VIMC_FRAME_MIN_HEIGHT,
111                                  VIMC_FRAME_MAX_HEIGHT) & ~1;
112
113         /* Don't accept a pixelformat that is not on the table */
114         vpix = vimc_pix_map_by_pixelformat(format->pixelformat);
115         if (!vpix) {
116                 format->pixelformat = fmt_default.pixelformat;
117                 vpix = vimc_pix_map_by_pixelformat(format->pixelformat);
118         }
119         /* TODO: Add support for custom bytesperline values */
120         format->bytesperline = format->width * vpix->bpp;
121         format->sizeimage = format->bytesperline * format->height;
122
123         if (format->field == V4L2_FIELD_ANY)
124                 format->field = fmt_default.field;
125
126         vimc_colorimetry_clamp(format);
127
128         return 0;
129 }
130
131 static int vimc_cap_s_fmt_vid_cap(struct file *file, void *priv,
132                                   struct v4l2_format *f)
133 {
134         struct vimc_cap_device *vcap = video_drvdata(file);
135         int ret;
136
137         /* Do not change the format while stream is on */
138         if (vb2_is_busy(&vcap->queue))
139                 return -EBUSY;
140
141         ret = vimc_cap_try_fmt_vid_cap(file, priv, f);
142         if (ret)
143                 return ret;
144
145         dev_dbg(vcap->dev, "%s: format update: "
146                 "old:%dx%d (0x%x, %d, %d, %d, %d) "
147                 "new:%dx%d (0x%x, %d, %d, %d, %d)\n", vcap->vdev.name,
148                 /* old */
149                 vcap->format.width, vcap->format.height,
150                 vcap->format.pixelformat, vcap->format.colorspace,
151                 vcap->format.quantization, vcap->format.xfer_func,
152                 vcap->format.ycbcr_enc,
153                 /* new */
154                 f->fmt.pix.width, f->fmt.pix.height,
155                 f->fmt.pix.pixelformat, f->fmt.pix.colorspace,
156                 f->fmt.pix.quantization, f->fmt.pix.xfer_func,
157                 f->fmt.pix.ycbcr_enc);
158
159         vcap->format = f->fmt.pix;
160
161         return 0;
162 }
163
164 static int vimc_cap_enum_fmt_vid_cap(struct file *file, void *priv,
165                                      struct v4l2_fmtdesc *f)
166 {
167         const struct vimc_pix_map *vpix = vimc_pix_map_by_index(f->index);
168
169         if (!vpix)
170                 return -EINVAL;
171
172         f->pixelformat = vpix->pixelformat;
173
174         return 0;
175 }
176
177 static int vimc_cap_enum_framesizes(struct file *file, void *fh,
178                                     struct v4l2_frmsizeenum *fsize)
179 {
180         const struct vimc_pix_map *vpix;
181
182         if (fsize->index)
183                 return -EINVAL;
184
185         /* Only accept code in the pix map table */
186         vpix = vimc_pix_map_by_code(fsize->pixel_format);
187         if (!vpix)
188                 return -EINVAL;
189
190         fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS;
191         fsize->stepwise.min_width = VIMC_FRAME_MIN_WIDTH;
192         fsize->stepwise.max_width = VIMC_FRAME_MAX_WIDTH;
193         fsize->stepwise.min_height = VIMC_FRAME_MIN_HEIGHT;
194         fsize->stepwise.max_height = VIMC_FRAME_MAX_HEIGHT;
195         fsize->stepwise.step_width = 2;
196         fsize->stepwise.step_height = 2;
197
198         return 0;
199 }
200
201 static const struct v4l2_file_operations vimc_cap_fops = {
202         .owner          = THIS_MODULE,
203         .open           = v4l2_fh_open,
204         .release        = vb2_fop_release,
205         .read           = vb2_fop_read,
206         .poll           = vb2_fop_poll,
207         .unlocked_ioctl = video_ioctl2,
208         .mmap           = vb2_fop_mmap,
209 };
210
211 static const struct v4l2_ioctl_ops vimc_cap_ioctl_ops = {
212         .vidioc_querycap = vimc_cap_querycap,
213
214         .vidioc_g_fmt_vid_cap = vimc_cap_g_fmt_vid_cap,
215         .vidioc_s_fmt_vid_cap = vimc_cap_s_fmt_vid_cap,
216         .vidioc_try_fmt_vid_cap = vimc_cap_try_fmt_vid_cap,
217         .vidioc_enum_fmt_vid_cap = vimc_cap_enum_fmt_vid_cap,
218         .vidioc_enum_framesizes = vimc_cap_enum_framesizes,
219
220         .vidioc_reqbufs = vb2_ioctl_reqbufs,
221         .vidioc_create_bufs = vb2_ioctl_create_bufs,
222         .vidioc_prepare_buf = vb2_ioctl_prepare_buf,
223         .vidioc_querybuf = vb2_ioctl_querybuf,
224         .vidioc_qbuf = vb2_ioctl_qbuf,
225         .vidioc_dqbuf = vb2_ioctl_dqbuf,
226         .vidioc_expbuf = vb2_ioctl_expbuf,
227         .vidioc_streamon = vb2_ioctl_streamon,
228         .vidioc_streamoff = vb2_ioctl_streamoff,
229 };
230
231 static void vimc_cap_return_all_buffers(struct vimc_cap_device *vcap,
232                                         enum vb2_buffer_state state)
233 {
234         struct vimc_cap_buffer *vbuf, *node;
235
236         spin_lock(&vcap->qlock);
237
238         list_for_each_entry_safe(vbuf, node, &vcap->buf_list, list) {
239                 list_del(&vbuf->list);
240                 vb2_buffer_done(&vbuf->vb2.vb2_buf, state);
241         }
242
243         spin_unlock(&vcap->qlock);
244 }
245
246 static int vimc_cap_start_streaming(struct vb2_queue *vq, unsigned int count)
247 {
248         struct vimc_cap_device *vcap = vb2_get_drv_priv(vq);
249         struct media_entity *entity = &vcap->vdev.entity;
250         int ret;
251
252         vcap->sequence = 0;
253
254         /* Start the media pipeline */
255         ret = media_pipeline_start(entity, &vcap->stream.pipe);
256         if (ret) {
257                 vimc_cap_return_all_buffers(vcap, VB2_BUF_STATE_QUEUED);
258                 return ret;
259         }
260
261         ret = vimc_streamer_s_stream(&vcap->stream, &vcap->ved, 1);
262         if (ret) {
263                 media_pipeline_stop(entity);
264                 vimc_cap_return_all_buffers(vcap, VB2_BUF_STATE_QUEUED);
265                 return ret;
266         }
267
268         return 0;
269 }
270
271 /*
272  * Stop the stream engine. Any remaining buffers in the stream queue are
273  * dequeued and passed on to the vb2 framework marked as STATE_ERROR.
274  */
275 static void vimc_cap_stop_streaming(struct vb2_queue *vq)
276 {
277         struct vimc_cap_device *vcap = vb2_get_drv_priv(vq);
278
279         vimc_streamer_s_stream(&vcap->stream, &vcap->ved, 0);
280
281         /* Stop the media pipeline */
282         media_pipeline_stop(&vcap->vdev.entity);
283
284         /* Release all active buffers */
285         vimc_cap_return_all_buffers(vcap, VB2_BUF_STATE_ERROR);
286 }
287
288 static void vimc_cap_buf_queue(struct vb2_buffer *vb2_buf)
289 {
290         struct vimc_cap_device *vcap = vb2_get_drv_priv(vb2_buf->vb2_queue);
291         struct vimc_cap_buffer *buf = container_of(vb2_buf,
292                                                    struct vimc_cap_buffer,
293                                                    vb2.vb2_buf);
294
295         spin_lock(&vcap->qlock);
296         list_add_tail(&buf->list, &vcap->buf_list);
297         spin_unlock(&vcap->qlock);
298 }
299
300 static int vimc_cap_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers,
301                                 unsigned int *nplanes, unsigned int sizes[],
302                                 struct device *alloc_devs[])
303 {
304         struct vimc_cap_device *vcap = vb2_get_drv_priv(vq);
305
306         if (*nplanes)
307                 return sizes[0] < vcap->format.sizeimage ? -EINVAL : 0;
308         /* We don't support multiplanes for now */
309         *nplanes = 1;
310         sizes[0] = vcap->format.sizeimage;
311
312         return 0;
313 }
314
315 static int vimc_cap_buffer_prepare(struct vb2_buffer *vb)
316 {
317         struct vimc_cap_device *vcap = vb2_get_drv_priv(vb->vb2_queue);
318         unsigned long size = vcap->format.sizeimage;
319
320         if (vb2_plane_size(vb, 0) < size) {
321                 dev_err(vcap->dev, "%s: buffer too small (%lu < %lu)\n",
322                         vcap->vdev.name, vb2_plane_size(vb, 0), size);
323                 return -EINVAL;
324         }
325         return 0;
326 }
327
328 static const struct vb2_ops vimc_cap_qops = {
329         .start_streaming        = vimc_cap_start_streaming,
330         .stop_streaming         = vimc_cap_stop_streaming,
331         .buf_queue              = vimc_cap_buf_queue,
332         .queue_setup            = vimc_cap_queue_setup,
333         .buf_prepare            = vimc_cap_buffer_prepare,
334         /*
335          * Since q->lock is set we can use the standard
336          * vb2_ops_wait_prepare/finish helper functions.
337          */
338         .wait_prepare           = vb2_ops_wait_prepare,
339         .wait_finish            = vb2_ops_wait_finish,
340 };
341
342 static const struct media_entity_operations vimc_cap_mops = {
343         .link_validate          = vimc_link_validate,
344 };
345
346 static void vimc_cap_comp_unbind(struct device *comp, struct device *master,
347                                  void *master_data)
348 {
349         struct vimc_ent_device *ved = dev_get_drvdata(comp);
350         struct vimc_cap_device *vcap = container_of(ved, struct vimc_cap_device,
351                                                     ved);
352
353         vb2_queue_release(&vcap->queue);
354         media_entity_cleanup(ved->ent);
355         video_unregister_device(&vcap->vdev);
356         vimc_pads_cleanup(vcap->ved.pads);
357         kfree(vcap);
358 }
359
360 static void *vimc_cap_process_frame(struct vimc_ent_device *ved,
361                                     const void *frame)
362 {
363         struct vimc_cap_device *vcap = container_of(ved, struct vimc_cap_device,
364                                                     ved);
365         struct vimc_cap_buffer *vimc_buf;
366         void *vbuf;
367
368         spin_lock(&vcap->qlock);
369
370         /* Get the first entry of the list */
371         vimc_buf = list_first_entry_or_null(&vcap->buf_list,
372                                             typeof(*vimc_buf), list);
373         if (!vimc_buf) {
374                 spin_unlock(&vcap->qlock);
375                 return ERR_PTR(-EAGAIN);
376         }
377
378         /* Remove this entry from the list */
379         list_del(&vimc_buf->list);
380
381         spin_unlock(&vcap->qlock);
382
383         /* Fill the buffer */
384         vimc_buf->vb2.vb2_buf.timestamp = ktime_get_ns();
385         vimc_buf->vb2.sequence = vcap->sequence++;
386         vimc_buf->vb2.field = vcap->format.field;
387
388         vbuf = vb2_plane_vaddr(&vimc_buf->vb2.vb2_buf, 0);
389
390         memcpy(vbuf, frame, vcap->format.sizeimage);
391
392         /* Set it as ready */
393         vb2_set_plane_payload(&vimc_buf->vb2.vb2_buf, 0,
394                               vcap->format.sizeimage);
395         vb2_buffer_done(&vimc_buf->vb2.vb2_buf, VB2_BUF_STATE_DONE);
396         return NULL;
397 }
398
399 static int vimc_cap_comp_bind(struct device *comp, struct device *master,
400                               void *master_data)
401 {
402         struct v4l2_device *v4l2_dev = master_data;
403         struct vimc_platform_data *pdata = comp->platform_data;
404         const struct vimc_pix_map *vpix;
405         struct vimc_cap_device *vcap;
406         struct video_device *vdev;
407         struct vb2_queue *q;
408         int ret;
409
410         /* Allocate the vimc_cap_device struct */
411         vcap = kzalloc(sizeof(*vcap), GFP_KERNEL);
412         if (!vcap)
413                 return -ENOMEM;
414
415         /* Allocate the pads */
416         vcap->ved.pads =
417                 vimc_pads_init(1, (const unsigned long[1]) {MEDIA_PAD_FL_SINK});
418         if (IS_ERR(vcap->ved.pads)) {
419                 ret = PTR_ERR(vcap->ved.pads);
420                 goto err_free_vcap;
421         }
422
423         /* Initialize the media entity */
424         vcap->vdev.entity.name = pdata->entity_name;
425         vcap->vdev.entity.function = MEDIA_ENT_F_IO_V4L;
426         ret = media_entity_pads_init(&vcap->vdev.entity,
427                                      1, vcap->ved.pads);
428         if (ret)
429                 goto err_clean_pads;
430
431         /* Initialize the lock */
432         mutex_init(&vcap->lock);
433
434         /* Initialize the vb2 queue */
435         q = &vcap->queue;
436         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
437         q->io_modes = VB2_MMAP | VB2_DMABUF;
438         q->drv_priv = vcap;
439         q->buf_struct_size = sizeof(struct vimc_cap_buffer);
440         q->ops = &vimc_cap_qops;
441         q->mem_ops = &vb2_vmalloc_memops;
442         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
443         q->min_buffers_needed = 2;
444         q->lock = &vcap->lock;
445
446         ret = vb2_queue_init(q);
447         if (ret) {
448                 dev_err(comp, "%s: vb2 queue init failed (err=%d)\n",
449                         pdata->entity_name, ret);
450                 goto err_clean_m_ent;
451         }
452
453         /* Initialize buffer list and its lock */
454         INIT_LIST_HEAD(&vcap->buf_list);
455         spin_lock_init(&vcap->qlock);
456
457         /* Set default frame format */
458         vcap->format = fmt_default;
459         vpix = vimc_pix_map_by_pixelformat(vcap->format.pixelformat);
460         vcap->format.bytesperline = vcap->format.width * vpix->bpp;
461         vcap->format.sizeimage = vcap->format.bytesperline *
462                                  vcap->format.height;
463
464         /* Fill the vimc_ent_device struct */
465         vcap->ved.ent = &vcap->vdev.entity;
466         vcap->ved.process_frame = vimc_cap_process_frame;
467         vcap->ved.vdev_get_format = vimc_cap_get_format;
468         dev_set_drvdata(comp, &vcap->ved);
469         vcap->dev = comp;
470
471         /* Initialize the video_device struct */
472         vdev = &vcap->vdev;
473         vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
474         vdev->entity.ops = &vimc_cap_mops;
475         vdev->release = video_device_release_empty;
476         vdev->fops = &vimc_cap_fops;
477         vdev->ioctl_ops = &vimc_cap_ioctl_ops;
478         vdev->lock = &vcap->lock;
479         vdev->queue = q;
480         vdev->v4l2_dev = v4l2_dev;
481         vdev->vfl_dir = VFL_DIR_RX;
482         strlcpy(vdev->name, pdata->entity_name, sizeof(vdev->name));
483         video_set_drvdata(vdev, &vcap->ved);
484
485         /* Register the video_device with the v4l2 and the media framework */
486         ret = video_register_device(vdev, VFL_TYPE_GRABBER, -1);
487         if (ret) {
488                 dev_err(comp, "%s: video register failed (err=%d)\n",
489                         vcap->vdev.name, ret);
490                 goto err_release_queue;
491         }
492
493         return 0;
494
495 err_release_queue:
496         vb2_queue_release(q);
497 err_clean_m_ent:
498         media_entity_cleanup(&vcap->vdev.entity);
499 err_clean_pads:
500         vimc_pads_cleanup(vcap->ved.pads);
501 err_free_vcap:
502         kfree(vcap);
503
504         return ret;
505 }
506
507 static const struct component_ops vimc_cap_comp_ops = {
508         .bind = vimc_cap_comp_bind,
509         .unbind = vimc_cap_comp_unbind,
510 };
511
512 static int vimc_cap_probe(struct platform_device *pdev)
513 {
514         return component_add(&pdev->dev, &vimc_cap_comp_ops);
515 }
516
517 static int vimc_cap_remove(struct platform_device *pdev)
518 {
519         component_del(&pdev->dev, &vimc_cap_comp_ops);
520
521         return 0;
522 }
523
524 static const struct platform_device_id vimc_cap_driver_ids[] = {
525         {
526                 .name           = VIMC_CAP_DRV_NAME,
527         },
528         { }
529 };
530
531 static struct platform_driver vimc_cap_pdrv = {
532         .probe          = vimc_cap_probe,
533         .remove         = vimc_cap_remove,
534         .id_table       = vimc_cap_driver_ids,
535         .driver         = {
536                 .name   = VIMC_CAP_DRV_NAME,
537         },
538 };
539
540 module_platform_driver(vimc_cap_pdrv);
541
542 MODULE_DEVICE_TABLE(platform, vimc_cap_driver_ids);
543
544 MODULE_DESCRIPTION("Virtual Media Controller Driver (VIMC) Capture");
545 MODULE_AUTHOR("Helen Mae Koike Fornazier <helen.fornazier@gmail.com>");
546 MODULE_LICENSE("GPL");