Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net
[sfrench/cifs-2.6.git] / drivers / media / platform / vsp1 / vsp1_video.c
1 /*
2  * vsp1_video.c  --  R-Car VSP1 Video Node
3  *
4  * Copyright (C) 2013-2015 Renesas Electronics Corporation
5  *
6  * Contact: Laurent Pinchart (laurent.pinchart@ideasonboard.com)
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  */
13
14 #include <linux/list.h>
15 #include <linux/module.h>
16 #include <linux/mutex.h>
17 #include <linux/slab.h>
18 #include <linux/v4l2-mediabus.h>
19 #include <linux/videodev2.h>
20 #include <linux/wait.h>
21
22 #include <media/media-entity.h>
23 #include <media/v4l2-dev.h>
24 #include <media/v4l2-fh.h>
25 #include <media/v4l2-ioctl.h>
26 #include <media/v4l2-subdev.h>
27 #include <media/videobuf2-v4l2.h>
28 #include <media/videobuf2-dma-contig.h>
29
30 #include "vsp1.h"
31 #include "vsp1_bru.h"
32 #include "vsp1_dl.h"
33 #include "vsp1_entity.h"
34 #include "vsp1_hgo.h"
35 #include "vsp1_hgt.h"
36 #include "vsp1_pipe.h"
37 #include "vsp1_rwpf.h"
38 #include "vsp1_uds.h"
39 #include "vsp1_video.h"
40
41 #define VSP1_VIDEO_DEF_FORMAT           V4L2_PIX_FMT_YUYV
42 #define VSP1_VIDEO_DEF_WIDTH            1024
43 #define VSP1_VIDEO_DEF_HEIGHT           768
44
45 #define VSP1_VIDEO_MIN_WIDTH            2U
46 #define VSP1_VIDEO_MAX_WIDTH            8190U
47 #define VSP1_VIDEO_MIN_HEIGHT           2U
48 #define VSP1_VIDEO_MAX_HEIGHT           8190U
49
50 /* -----------------------------------------------------------------------------
51  * Helper functions
52  */
53
54 static struct v4l2_subdev *
55 vsp1_video_remote_subdev(struct media_pad *local, u32 *pad)
56 {
57         struct media_pad *remote;
58
59         remote = media_entity_remote_pad(local);
60         if (!remote || !is_media_entity_v4l2_subdev(remote->entity))
61                 return NULL;
62
63         if (pad)
64                 *pad = remote->index;
65
66         return media_entity_to_v4l2_subdev(remote->entity);
67 }
68
69 static int vsp1_video_verify_format(struct vsp1_video *video)
70 {
71         struct v4l2_subdev_format fmt;
72         struct v4l2_subdev *subdev;
73         int ret;
74
75         subdev = vsp1_video_remote_subdev(&video->pad, &fmt.pad);
76         if (subdev == NULL)
77                 return -EINVAL;
78
79         fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
80         ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt);
81         if (ret < 0)
82                 return ret == -ENOIOCTLCMD ? -EINVAL : ret;
83
84         if (video->rwpf->fmtinfo->mbus != fmt.format.code ||
85             video->rwpf->format.height != fmt.format.height ||
86             video->rwpf->format.width != fmt.format.width)
87                 return -EINVAL;
88
89         return 0;
90 }
91
92 static int __vsp1_video_try_format(struct vsp1_video *video,
93                                    struct v4l2_pix_format_mplane *pix,
94                                    const struct vsp1_format_info **fmtinfo)
95 {
96         static const u32 xrgb_formats[][2] = {
97                 { V4L2_PIX_FMT_RGB444, V4L2_PIX_FMT_XRGB444 },
98                 { V4L2_PIX_FMT_RGB555, V4L2_PIX_FMT_XRGB555 },
99                 { V4L2_PIX_FMT_BGR32, V4L2_PIX_FMT_XBGR32 },
100                 { V4L2_PIX_FMT_RGB32, V4L2_PIX_FMT_XRGB32 },
101         };
102
103         const struct vsp1_format_info *info;
104         unsigned int width = pix->width;
105         unsigned int height = pix->height;
106         unsigned int i;
107
108         /*
109          * Backward compatibility: replace deprecated RGB formats by their XRGB
110          * equivalent. This selects the format older userspace applications want
111          * while still exposing the new format.
112          */
113         for (i = 0; i < ARRAY_SIZE(xrgb_formats); ++i) {
114                 if (xrgb_formats[i][0] == pix->pixelformat) {
115                         pix->pixelformat = xrgb_formats[i][1];
116                         break;
117                 }
118         }
119
120         /*
121          * Retrieve format information and select the default format if the
122          * requested format isn't supported.
123          */
124         info = vsp1_get_format_info(video->vsp1, pix->pixelformat);
125         if (info == NULL)
126                 info = vsp1_get_format_info(video->vsp1, VSP1_VIDEO_DEF_FORMAT);
127
128         pix->pixelformat = info->fourcc;
129         pix->colorspace = V4L2_COLORSPACE_SRGB;
130         pix->field = V4L2_FIELD_NONE;
131
132         if (info->fourcc == V4L2_PIX_FMT_HSV24 ||
133             info->fourcc == V4L2_PIX_FMT_HSV32)
134                 pix->hsv_enc = V4L2_HSV_ENC_256;
135
136         memset(pix->reserved, 0, sizeof(pix->reserved));
137
138         /* Align the width and height for YUV 4:2:2 and 4:2:0 formats. */
139         width = round_down(width, info->hsub);
140         height = round_down(height, info->vsub);
141
142         /* Clamp the width and height. */
143         pix->width = clamp(width, VSP1_VIDEO_MIN_WIDTH, VSP1_VIDEO_MAX_WIDTH);
144         pix->height = clamp(height, VSP1_VIDEO_MIN_HEIGHT,
145                             VSP1_VIDEO_MAX_HEIGHT);
146
147         /*
148          * Compute and clamp the stride and image size. While not documented in
149          * the datasheet, strides not aligned to a multiple of 128 bytes result
150          * in image corruption.
151          */
152         for (i = 0; i < min(info->planes, 2U); ++i) {
153                 unsigned int hsub = i > 0 ? info->hsub : 1;
154                 unsigned int vsub = i > 0 ? info->vsub : 1;
155                 unsigned int align = 128;
156                 unsigned int bpl;
157
158                 bpl = clamp_t(unsigned int, pix->plane_fmt[i].bytesperline,
159                               pix->width / hsub * info->bpp[i] / 8,
160                               round_down(65535U, align));
161
162                 pix->plane_fmt[i].bytesperline = round_up(bpl, align);
163                 pix->plane_fmt[i].sizeimage = pix->plane_fmt[i].bytesperline
164                                             * pix->height / vsub;
165         }
166
167         if (info->planes == 3) {
168                 /* The second and third planes must have the same stride. */
169                 pix->plane_fmt[2].bytesperline = pix->plane_fmt[1].bytesperline;
170                 pix->plane_fmt[2].sizeimage = pix->plane_fmt[1].sizeimage;
171         }
172
173         pix->num_planes = info->planes;
174
175         if (fmtinfo)
176                 *fmtinfo = info;
177
178         return 0;
179 }
180
181 /* -----------------------------------------------------------------------------
182  * VSP1 Partition Algorithm support
183  */
184
185 static void vsp1_video_pipeline_setup_partitions(struct vsp1_pipeline *pipe)
186 {
187         struct vsp1_device *vsp1 = pipe->output->entity.vsp1;
188         const struct v4l2_mbus_framefmt *format;
189         struct vsp1_entity *entity;
190         unsigned int div_size;
191
192         /*
193          * Partitions are computed on the size before rotation, use the format
194          * at the WPF sink.
195          */
196         format = vsp1_entity_get_pad_format(&pipe->output->entity,
197                                             pipe->output->entity.config,
198                                             RWPF_PAD_SINK);
199         div_size = format->width;
200
201         /* Gen2 hardware doesn't require image partitioning. */
202         if (vsp1->info->gen == 2) {
203                 pipe->div_size = div_size;
204                 pipe->partitions = 1;
205                 return;
206         }
207
208         list_for_each_entry(entity, &pipe->entities, list_pipe) {
209                 unsigned int entity_max = VSP1_VIDEO_MAX_WIDTH;
210
211                 if (entity->ops->max_width) {
212                         entity_max = entity->ops->max_width(entity, pipe);
213                         if (entity_max)
214                                 div_size = min(div_size, entity_max);
215                 }
216         }
217
218         pipe->div_size = div_size;
219         pipe->partitions = DIV_ROUND_UP(format->width, div_size);
220 }
221
222 /**
223  * vsp1_video_partition - Calculate the active partition output window
224  *
225  * @div_size: pre-determined maximum partition division size
226  * @index: partition index
227  *
228  * Returns a v4l2_rect describing the partition window.
229  */
230 static struct v4l2_rect vsp1_video_partition(struct vsp1_pipeline *pipe,
231                                              unsigned int div_size,
232                                              unsigned int index)
233 {
234         const struct v4l2_mbus_framefmt *format;
235         struct v4l2_rect partition;
236         unsigned int modulus;
237
238         /*
239          * Partitions are computed on the size before rotation, use the format
240          * at the WPF sink.
241          */
242         format = vsp1_entity_get_pad_format(&pipe->output->entity,
243                                             pipe->output->entity.config,
244                                             RWPF_PAD_SINK);
245
246         /* A single partition simply processes the output size in full. */
247         if (pipe->partitions <= 1) {
248                 partition.left = 0;
249                 partition.top = 0;
250                 partition.width = format->width;
251                 partition.height = format->height;
252                 return partition;
253         }
254
255         /* Initialise the partition with sane starting conditions. */
256         partition.left = index * div_size;
257         partition.top = 0;
258         partition.width = div_size;
259         partition.height = format->height;
260
261         modulus = format->width % div_size;
262
263         /*
264          * We need to prevent the last partition from being smaller than the
265          * *minimum* width of the hardware capabilities.
266          *
267          * If the modulus is less than half of the partition size,
268          * the penultimate partition is reduced to half, which is added
269          * to the final partition: |1234|1234|1234|12|341|
270          * to prevents this:       |1234|1234|1234|1234|1|.
271          */
272         if (modulus) {
273                 /*
274                  * pipe->partitions is 1 based, whilst index is a 0 based index.
275                  * Normalise this locally.
276                  */
277                 unsigned int partitions = pipe->partitions - 1;
278
279                 if (modulus < div_size / 2) {
280                         if (index == partitions - 1) {
281                                 /* Halve the penultimate partition. */
282                                 partition.width = div_size / 2;
283                         } else if (index == partitions) {
284                                 /* Increase the final partition. */
285                                 partition.width = (div_size / 2) + modulus;
286                                 partition.left -= div_size / 2;
287                         }
288                 } else if (index == partitions) {
289                         partition.width = modulus;
290                 }
291         }
292
293         return partition;
294 }
295
296 /* -----------------------------------------------------------------------------
297  * Pipeline Management
298  */
299
300 /*
301  * vsp1_video_complete_buffer - Complete the current buffer
302  * @video: the video node
303  *
304  * This function completes the current buffer by filling its sequence number,
305  * time stamp and payload size, and hands it back to the videobuf core.
306  *
307  * When operating in DU output mode (deep pipeline to the DU through the LIF),
308  * the VSP1 needs to constantly supply frames to the display. In that case, if
309  * no other buffer is queued, reuse the one that has just been processed instead
310  * of handing it back to the videobuf core.
311  *
312  * Return the next queued buffer or NULL if the queue is empty.
313  */
314 static struct vsp1_vb2_buffer *
315 vsp1_video_complete_buffer(struct vsp1_video *video)
316 {
317         struct vsp1_pipeline *pipe = video->rwpf->pipe;
318         struct vsp1_vb2_buffer *next = NULL;
319         struct vsp1_vb2_buffer *done;
320         unsigned long flags;
321         unsigned int i;
322
323         spin_lock_irqsave(&video->irqlock, flags);
324
325         if (list_empty(&video->irqqueue)) {
326                 spin_unlock_irqrestore(&video->irqlock, flags);
327                 return NULL;
328         }
329
330         done = list_first_entry(&video->irqqueue,
331                                 struct vsp1_vb2_buffer, queue);
332
333         /* In DU output mode reuse the buffer if the list is singular. */
334         if (pipe->lif && list_is_singular(&video->irqqueue)) {
335                 spin_unlock_irqrestore(&video->irqlock, flags);
336                 return done;
337         }
338
339         list_del(&done->queue);
340
341         if (!list_empty(&video->irqqueue))
342                 next = list_first_entry(&video->irqqueue,
343                                         struct vsp1_vb2_buffer, queue);
344
345         spin_unlock_irqrestore(&video->irqlock, flags);
346
347         done->buf.sequence = pipe->sequence;
348         done->buf.vb2_buf.timestamp = ktime_get_ns();
349         for (i = 0; i < done->buf.vb2_buf.num_planes; ++i)
350                 vb2_set_plane_payload(&done->buf.vb2_buf, i,
351                                       vb2_plane_size(&done->buf.vb2_buf, i));
352         vb2_buffer_done(&done->buf.vb2_buf, VB2_BUF_STATE_DONE);
353
354         return next;
355 }
356
357 static void vsp1_video_frame_end(struct vsp1_pipeline *pipe,
358                                  struct vsp1_rwpf *rwpf)
359 {
360         struct vsp1_video *video = rwpf->video;
361         struct vsp1_vb2_buffer *buf;
362
363         buf = vsp1_video_complete_buffer(video);
364         if (buf == NULL)
365                 return;
366
367         video->rwpf->mem = buf->mem;
368         pipe->buffers_ready |= 1 << video->pipe_index;
369 }
370
371 static void vsp1_video_pipeline_run_partition(struct vsp1_pipeline *pipe,
372                                               struct vsp1_dl_list *dl)
373 {
374         struct vsp1_entity *entity;
375
376         pipe->partition = vsp1_video_partition(pipe, pipe->div_size,
377                                                pipe->current_partition);
378
379         list_for_each_entry(entity, &pipe->entities, list_pipe) {
380                 if (entity->ops->configure)
381                         entity->ops->configure(entity, pipe, dl,
382                                                VSP1_ENTITY_PARAMS_PARTITION);
383         }
384 }
385
386 static void vsp1_video_pipeline_run(struct vsp1_pipeline *pipe)
387 {
388         struct vsp1_device *vsp1 = pipe->output->entity.vsp1;
389         struct vsp1_entity *entity;
390
391         if (!pipe->dl)
392                 pipe->dl = vsp1_dl_list_get(pipe->output->dlm);
393
394         /*
395          * Start with the runtime parameters as the configure operation can
396          * compute/cache information needed when configuring partitions. This
397          * is the case with flipping in the WPF.
398          */
399         list_for_each_entry(entity, &pipe->entities, list_pipe) {
400                 if (entity->ops->configure)
401                         entity->ops->configure(entity, pipe, pipe->dl,
402                                                VSP1_ENTITY_PARAMS_RUNTIME);
403         }
404
405         /* Run the first partition */
406         pipe->current_partition = 0;
407         vsp1_video_pipeline_run_partition(pipe, pipe->dl);
408
409         /* Process consecutive partitions as necessary */
410         for (pipe->current_partition = 1;
411              pipe->current_partition < pipe->partitions;
412              pipe->current_partition++) {
413                 struct vsp1_dl_list *dl;
414
415                 /*
416                  * Partition configuration operations will utilise
417                  * the pipe->current_partition variable to determine
418                  * the work they should complete.
419                  */
420                 dl = vsp1_dl_list_get(pipe->output->dlm);
421
422                 /*
423                  * An incomplete chain will still function, but output only
424                  * the partitions that had a dl available. The frame end
425                  * interrupt will be marked on the last dl in the chain.
426                  */
427                 if (!dl) {
428                         dev_err(vsp1->dev, "Failed to obtain a dl list. Frame will be incomplete\n");
429                         break;
430                 }
431
432                 vsp1_video_pipeline_run_partition(pipe, dl);
433                 vsp1_dl_list_add_chain(pipe->dl, dl);
434         }
435
436         /* Complete, and commit the head display list. */
437         vsp1_dl_list_commit(pipe->dl);
438         pipe->dl = NULL;
439
440         vsp1_pipeline_run(pipe);
441 }
442
443 static void vsp1_video_pipeline_frame_end(struct vsp1_pipeline *pipe)
444 {
445         struct vsp1_device *vsp1 = pipe->output->entity.vsp1;
446         enum vsp1_pipeline_state state;
447         unsigned long flags;
448         unsigned int i;
449
450         spin_lock_irqsave(&pipe->irqlock, flags);
451
452         /* Complete buffers on all video nodes. */
453         for (i = 0; i < vsp1->info->rpf_count; ++i) {
454                 if (!pipe->inputs[i])
455                         continue;
456
457                 vsp1_video_frame_end(pipe, pipe->inputs[i]);
458         }
459
460         vsp1_video_frame_end(pipe, pipe->output);
461
462         state = pipe->state;
463         pipe->state = VSP1_PIPELINE_STOPPED;
464
465         /*
466          * If a stop has been requested, mark the pipeline as stopped and
467          * return. Otherwise restart the pipeline if ready.
468          */
469         if (state == VSP1_PIPELINE_STOPPING)
470                 wake_up(&pipe->wq);
471         else if (vsp1_pipeline_ready(pipe))
472                 vsp1_video_pipeline_run(pipe);
473
474         spin_unlock_irqrestore(&pipe->irqlock, flags);
475 }
476
477 static int vsp1_video_pipeline_build_branch(struct vsp1_pipeline *pipe,
478                                             struct vsp1_rwpf *input,
479                                             struct vsp1_rwpf *output)
480 {
481         struct media_entity_enum ent_enum;
482         struct vsp1_entity *entity;
483         struct media_pad *pad;
484         bool bru_found = false;
485         int ret;
486
487         ret = media_entity_enum_init(&ent_enum, &input->entity.vsp1->media_dev);
488         if (ret < 0)
489                 return ret;
490
491         /*
492          * The main data path doesn't include the HGO or HGT, use
493          * vsp1_entity_remote_pad() to traverse the graph.
494          */
495
496         pad = vsp1_entity_remote_pad(&input->entity.pads[RWPF_PAD_SOURCE]);
497
498         while (1) {
499                 if (pad == NULL) {
500                         ret = -EPIPE;
501                         goto out;
502                 }
503
504                 /* We've reached a video node, that shouldn't have happened. */
505                 if (!is_media_entity_v4l2_subdev(pad->entity)) {
506                         ret = -EPIPE;
507                         goto out;
508                 }
509
510                 entity = to_vsp1_entity(
511                         media_entity_to_v4l2_subdev(pad->entity));
512
513                 /*
514                  * A BRU is present in the pipeline, store the BRU input pad
515                  * number in the input RPF for use when configuring the RPF.
516                  */
517                 if (entity->type == VSP1_ENTITY_BRU) {
518                         struct vsp1_bru *bru = to_bru(&entity->subdev);
519
520                         bru->inputs[pad->index].rpf = input;
521                         input->bru_input = pad->index;
522
523                         bru_found = true;
524                 }
525
526                 /* We've reached the WPF, we're done. */
527                 if (entity->type == VSP1_ENTITY_WPF)
528                         break;
529
530                 /* Ensure the branch has no loop. */
531                 if (media_entity_enum_test_and_set(&ent_enum,
532                                                    &entity->subdev.entity)) {
533                         ret = -EPIPE;
534                         goto out;
535                 }
536
537                 /* UDS can't be chained. */
538                 if (entity->type == VSP1_ENTITY_UDS) {
539                         if (pipe->uds) {
540                                 ret = -EPIPE;
541                                 goto out;
542                         }
543
544                         pipe->uds = entity;
545                         pipe->uds_input = bru_found ? pipe->bru
546                                         : &input->entity;
547                 }
548
549                 /* Follow the source link, ignoring any HGO or HGT. */
550                 pad = &entity->pads[entity->source_pad];
551                 pad = vsp1_entity_remote_pad(pad);
552         }
553
554         /* The last entity must be the output WPF. */
555         if (entity != &output->entity)
556                 ret = -EPIPE;
557
558 out:
559         media_entity_enum_cleanup(&ent_enum);
560
561         return ret;
562 }
563
564 static int vsp1_video_pipeline_build(struct vsp1_pipeline *pipe,
565                                      struct vsp1_video *video)
566 {
567         struct media_graph graph;
568         struct media_entity *entity = &video->video.entity;
569         struct media_device *mdev = entity->graph_obj.mdev;
570         unsigned int i;
571         int ret;
572
573         /* Walk the graph to locate the entities and video nodes. */
574         ret = media_graph_walk_init(&graph, mdev);
575         if (ret)
576                 return ret;
577
578         media_graph_walk_start(&graph, entity);
579
580         while ((entity = media_graph_walk_next(&graph))) {
581                 struct v4l2_subdev *subdev;
582                 struct vsp1_rwpf *rwpf;
583                 struct vsp1_entity *e;
584
585                 if (!is_media_entity_v4l2_subdev(entity))
586                         continue;
587
588                 subdev = media_entity_to_v4l2_subdev(entity);
589                 e = to_vsp1_entity(subdev);
590                 list_add_tail(&e->list_pipe, &pipe->entities);
591
592                 if (e->type == VSP1_ENTITY_RPF) {
593                         rwpf = to_rwpf(subdev);
594                         pipe->inputs[rwpf->entity.index] = rwpf;
595                         rwpf->video->pipe_index = ++pipe->num_inputs;
596                         rwpf->pipe = pipe;
597                 } else if (e->type == VSP1_ENTITY_WPF) {
598                         rwpf = to_rwpf(subdev);
599                         pipe->output = rwpf;
600                         rwpf->video->pipe_index = 0;
601                         rwpf->pipe = pipe;
602                 } else if (e->type == VSP1_ENTITY_LIF) {
603                         pipe->lif = e;
604                 } else if (e->type == VSP1_ENTITY_BRU) {
605                         pipe->bru = e;
606                 } else if (e->type == VSP1_ENTITY_HGO) {
607                         struct vsp1_hgo *hgo = to_hgo(subdev);
608
609                         pipe->hgo = e;
610                         hgo->histo.pipe = pipe;
611                 } else if (e->type == VSP1_ENTITY_HGT) {
612                         struct vsp1_hgt *hgt = to_hgt(subdev);
613
614                         pipe->hgt = e;
615                         hgt->histo.pipe = pipe;
616                 }
617         }
618
619         media_graph_walk_cleanup(&graph);
620
621         /* We need one output and at least one input. */
622         if (pipe->num_inputs == 0 || !pipe->output)
623                 return -EPIPE;
624
625         /*
626          * Follow links downstream for each input and make sure the graph
627          * contains no loop and that all branches end at the output WPF.
628          */
629         for (i = 0; i < video->vsp1->info->rpf_count; ++i) {
630                 if (!pipe->inputs[i])
631                         continue;
632
633                 ret = vsp1_video_pipeline_build_branch(pipe, pipe->inputs[i],
634                                                        pipe->output);
635                 if (ret < 0)
636                         return ret;
637         }
638
639         return 0;
640 }
641
642 static int vsp1_video_pipeline_init(struct vsp1_pipeline *pipe,
643                                     struct vsp1_video *video)
644 {
645         vsp1_pipeline_init(pipe);
646
647         pipe->frame_end = vsp1_video_pipeline_frame_end;
648
649         return vsp1_video_pipeline_build(pipe, video);
650 }
651
652 static struct vsp1_pipeline *vsp1_video_pipeline_get(struct vsp1_video *video)
653 {
654         struct vsp1_pipeline *pipe;
655         int ret;
656
657         /*
658          * Get a pipeline object for the video node. If a pipeline has already
659          * been allocated just increment its reference count and return it.
660          * Otherwise allocate a new pipeline and initialize it, it will be freed
661          * when the last reference is released.
662          */
663         if (!video->rwpf->pipe) {
664                 pipe = kzalloc(sizeof(*pipe), GFP_KERNEL);
665                 if (!pipe)
666                         return ERR_PTR(-ENOMEM);
667
668                 ret = vsp1_video_pipeline_init(pipe, video);
669                 if (ret < 0) {
670                         vsp1_pipeline_reset(pipe);
671                         kfree(pipe);
672                         return ERR_PTR(ret);
673                 }
674         } else {
675                 pipe = video->rwpf->pipe;
676                 kref_get(&pipe->kref);
677         }
678
679         return pipe;
680 }
681
682 static void vsp1_video_pipeline_release(struct kref *kref)
683 {
684         struct vsp1_pipeline *pipe = container_of(kref, typeof(*pipe), kref);
685
686         vsp1_pipeline_reset(pipe);
687         kfree(pipe);
688 }
689
690 static void vsp1_video_pipeline_put(struct vsp1_pipeline *pipe)
691 {
692         struct media_device *mdev = &pipe->output->entity.vsp1->media_dev;
693
694         mutex_lock(&mdev->graph_mutex);
695         kref_put(&pipe->kref, vsp1_video_pipeline_release);
696         mutex_unlock(&mdev->graph_mutex);
697 }
698
699 /* -----------------------------------------------------------------------------
700  * videobuf2 Queue Operations
701  */
702
703 static int
704 vsp1_video_queue_setup(struct vb2_queue *vq,
705                        unsigned int *nbuffers, unsigned int *nplanes,
706                        unsigned int sizes[], struct device *alloc_devs[])
707 {
708         struct vsp1_video *video = vb2_get_drv_priv(vq);
709         const struct v4l2_pix_format_mplane *format = &video->rwpf->format;
710         unsigned int i;
711
712         if (*nplanes) {
713                 if (*nplanes != format->num_planes)
714                         return -EINVAL;
715
716                 for (i = 0; i < *nplanes; i++)
717                         if (sizes[i] < format->plane_fmt[i].sizeimage)
718                                 return -EINVAL;
719                 return 0;
720         }
721
722         *nplanes = format->num_planes;
723
724         for (i = 0; i < format->num_planes; ++i)
725                 sizes[i] = format->plane_fmt[i].sizeimage;
726
727         return 0;
728 }
729
730 static int vsp1_video_buffer_prepare(struct vb2_buffer *vb)
731 {
732         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
733         struct vsp1_video *video = vb2_get_drv_priv(vb->vb2_queue);
734         struct vsp1_vb2_buffer *buf = to_vsp1_vb2_buffer(vbuf);
735         const struct v4l2_pix_format_mplane *format = &video->rwpf->format;
736         unsigned int i;
737
738         if (vb->num_planes < format->num_planes)
739                 return -EINVAL;
740
741         for (i = 0; i < vb->num_planes; ++i) {
742                 buf->mem.addr[i] = vb2_dma_contig_plane_dma_addr(vb, i);
743
744                 if (vb2_plane_size(vb, i) < format->plane_fmt[i].sizeimage)
745                         return -EINVAL;
746         }
747
748         for ( ; i < 3; ++i)
749                 buf->mem.addr[i] = 0;
750
751         return 0;
752 }
753
754 static void vsp1_video_buffer_queue(struct vb2_buffer *vb)
755 {
756         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
757         struct vsp1_video *video = vb2_get_drv_priv(vb->vb2_queue);
758         struct vsp1_pipeline *pipe = video->rwpf->pipe;
759         struct vsp1_vb2_buffer *buf = to_vsp1_vb2_buffer(vbuf);
760         unsigned long flags;
761         bool empty;
762
763         spin_lock_irqsave(&video->irqlock, flags);
764         empty = list_empty(&video->irqqueue);
765         list_add_tail(&buf->queue, &video->irqqueue);
766         spin_unlock_irqrestore(&video->irqlock, flags);
767
768         if (!empty)
769                 return;
770
771         spin_lock_irqsave(&pipe->irqlock, flags);
772
773         video->rwpf->mem = buf->mem;
774         pipe->buffers_ready |= 1 << video->pipe_index;
775
776         if (vb2_is_streaming(&video->queue) &&
777             vsp1_pipeline_ready(pipe))
778                 vsp1_video_pipeline_run(pipe);
779
780         spin_unlock_irqrestore(&pipe->irqlock, flags);
781 }
782
783 static int vsp1_video_setup_pipeline(struct vsp1_pipeline *pipe)
784 {
785         struct vsp1_entity *entity;
786
787         /* Determine this pipelines sizes for image partitioning support. */
788         vsp1_video_pipeline_setup_partitions(pipe);
789
790         /* Prepare the display list. */
791         pipe->dl = vsp1_dl_list_get(pipe->output->dlm);
792         if (!pipe->dl)
793                 return -ENOMEM;
794
795         if (pipe->uds) {
796                 struct vsp1_uds *uds = to_uds(&pipe->uds->subdev);
797
798                 /*
799                  * If a BRU is present in the pipeline before the UDS, the alpha
800                  * component doesn't need to be scaled as the BRU output alpha
801                  * value is fixed to 255. Otherwise we need to scale the alpha
802                  * component only when available at the input RPF.
803                  */
804                 if (pipe->uds_input->type == VSP1_ENTITY_BRU) {
805                         uds->scale_alpha = false;
806                 } else {
807                         struct vsp1_rwpf *rpf =
808                                 to_rwpf(&pipe->uds_input->subdev);
809
810                         uds->scale_alpha = rpf->fmtinfo->alpha;
811                 }
812         }
813
814         list_for_each_entry(entity, &pipe->entities, list_pipe) {
815                 vsp1_entity_route_setup(entity, pipe, pipe->dl);
816
817                 if (entity->ops->configure)
818                         entity->ops->configure(entity, pipe, pipe->dl,
819                                                VSP1_ENTITY_PARAMS_INIT);
820         }
821
822         return 0;
823 }
824
825 static int vsp1_video_start_streaming(struct vb2_queue *vq, unsigned int count)
826 {
827         struct vsp1_video *video = vb2_get_drv_priv(vq);
828         struct vsp1_pipeline *pipe = video->rwpf->pipe;
829         bool start_pipeline = false;
830         unsigned long flags;
831         int ret;
832
833         mutex_lock(&pipe->lock);
834         if (pipe->stream_count == pipe->num_inputs) {
835                 ret = vsp1_video_setup_pipeline(pipe);
836                 if (ret < 0) {
837                         mutex_unlock(&pipe->lock);
838                         return ret;
839                 }
840
841                 start_pipeline = true;
842         }
843
844         pipe->stream_count++;
845         mutex_unlock(&pipe->lock);
846
847         /*
848          * vsp1_pipeline_ready() is not sufficient to establish that all streams
849          * are prepared and the pipeline is configured, as multiple streams
850          * can race through streamon with buffers already queued; Therefore we
851          * don't even attempt to start the pipeline until the last stream has
852          * called through here.
853          */
854         if (!start_pipeline)
855                 return 0;
856
857         spin_lock_irqsave(&pipe->irqlock, flags);
858         if (vsp1_pipeline_ready(pipe))
859                 vsp1_video_pipeline_run(pipe);
860         spin_unlock_irqrestore(&pipe->irqlock, flags);
861
862         return 0;
863 }
864
865 static void vsp1_video_stop_streaming(struct vb2_queue *vq)
866 {
867         struct vsp1_video *video = vb2_get_drv_priv(vq);
868         struct vsp1_pipeline *pipe = video->rwpf->pipe;
869         struct vsp1_vb2_buffer *buffer;
870         unsigned long flags;
871         int ret;
872
873         /*
874          * Clear the buffers ready flag to make sure the device won't be started
875          * by a QBUF on the video node on the other side of the pipeline.
876          */
877         spin_lock_irqsave(&video->irqlock, flags);
878         pipe->buffers_ready &= ~(1 << video->pipe_index);
879         spin_unlock_irqrestore(&video->irqlock, flags);
880
881         mutex_lock(&pipe->lock);
882         if (--pipe->stream_count == pipe->num_inputs) {
883                 /* Stop the pipeline. */
884                 ret = vsp1_pipeline_stop(pipe);
885                 if (ret == -ETIMEDOUT)
886                         dev_err(video->vsp1->dev, "pipeline stop timeout\n");
887
888                 vsp1_dl_list_put(pipe->dl);
889                 pipe->dl = NULL;
890         }
891         mutex_unlock(&pipe->lock);
892
893         media_pipeline_stop(&video->video.entity);
894         vsp1_video_pipeline_put(pipe);
895
896         /* Remove all buffers from the IRQ queue. */
897         spin_lock_irqsave(&video->irqlock, flags);
898         list_for_each_entry(buffer, &video->irqqueue, queue)
899                 vb2_buffer_done(&buffer->buf.vb2_buf, VB2_BUF_STATE_ERROR);
900         INIT_LIST_HEAD(&video->irqqueue);
901         spin_unlock_irqrestore(&video->irqlock, flags);
902 }
903
904 static const struct vb2_ops vsp1_video_queue_qops = {
905         .queue_setup = vsp1_video_queue_setup,
906         .buf_prepare = vsp1_video_buffer_prepare,
907         .buf_queue = vsp1_video_buffer_queue,
908         .wait_prepare = vb2_ops_wait_prepare,
909         .wait_finish = vb2_ops_wait_finish,
910         .start_streaming = vsp1_video_start_streaming,
911         .stop_streaming = vsp1_video_stop_streaming,
912 };
913
914 /* -----------------------------------------------------------------------------
915  * V4L2 ioctls
916  */
917
918 static int
919 vsp1_video_querycap(struct file *file, void *fh, struct v4l2_capability *cap)
920 {
921         struct v4l2_fh *vfh = file->private_data;
922         struct vsp1_video *video = to_vsp1_video(vfh->vdev);
923
924         cap->capabilities = V4L2_CAP_DEVICE_CAPS | V4L2_CAP_STREAMING
925                           | V4L2_CAP_VIDEO_CAPTURE_MPLANE
926                           | V4L2_CAP_VIDEO_OUTPUT_MPLANE;
927
928         if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
929                 cap->device_caps = V4L2_CAP_VIDEO_CAPTURE_MPLANE
930                                  | V4L2_CAP_STREAMING;
931         else
932                 cap->device_caps = V4L2_CAP_VIDEO_OUTPUT_MPLANE
933                                  | V4L2_CAP_STREAMING;
934
935         strlcpy(cap->driver, "vsp1", sizeof(cap->driver));
936         strlcpy(cap->card, video->video.name, sizeof(cap->card));
937         snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s",
938                  dev_name(video->vsp1->dev));
939
940         return 0;
941 }
942
943 static int
944 vsp1_video_get_format(struct file *file, void *fh, struct v4l2_format *format)
945 {
946         struct v4l2_fh *vfh = file->private_data;
947         struct vsp1_video *video = to_vsp1_video(vfh->vdev);
948
949         if (format->type != video->queue.type)
950                 return -EINVAL;
951
952         mutex_lock(&video->lock);
953         format->fmt.pix_mp = video->rwpf->format;
954         mutex_unlock(&video->lock);
955
956         return 0;
957 }
958
959 static int
960 vsp1_video_try_format(struct file *file, void *fh, struct v4l2_format *format)
961 {
962         struct v4l2_fh *vfh = file->private_data;
963         struct vsp1_video *video = to_vsp1_video(vfh->vdev);
964
965         if (format->type != video->queue.type)
966                 return -EINVAL;
967
968         return __vsp1_video_try_format(video, &format->fmt.pix_mp, NULL);
969 }
970
971 static int
972 vsp1_video_set_format(struct file *file, void *fh, struct v4l2_format *format)
973 {
974         struct v4l2_fh *vfh = file->private_data;
975         struct vsp1_video *video = to_vsp1_video(vfh->vdev);
976         const struct vsp1_format_info *info;
977         int ret;
978
979         if (format->type != video->queue.type)
980                 return -EINVAL;
981
982         ret = __vsp1_video_try_format(video, &format->fmt.pix_mp, &info);
983         if (ret < 0)
984                 return ret;
985
986         mutex_lock(&video->lock);
987
988         if (vb2_is_busy(&video->queue)) {
989                 ret = -EBUSY;
990                 goto done;
991         }
992
993         video->rwpf->format = format->fmt.pix_mp;
994         video->rwpf->fmtinfo = info;
995
996 done:
997         mutex_unlock(&video->lock);
998         return ret;
999 }
1000
1001 static int
1002 vsp1_video_streamon(struct file *file, void *fh, enum v4l2_buf_type type)
1003 {
1004         struct v4l2_fh *vfh = file->private_data;
1005         struct vsp1_video *video = to_vsp1_video(vfh->vdev);
1006         struct media_device *mdev = &video->vsp1->media_dev;
1007         struct vsp1_pipeline *pipe;
1008         int ret;
1009
1010         if (video->queue.owner && video->queue.owner != file->private_data)
1011                 return -EBUSY;
1012
1013         /*
1014          * Get a pipeline for the video node and start streaming on it. No link
1015          * touching an entity in the pipeline can be activated or deactivated
1016          * once streaming is started.
1017          */
1018         mutex_lock(&mdev->graph_mutex);
1019
1020         pipe = vsp1_video_pipeline_get(video);
1021         if (IS_ERR(pipe)) {
1022                 mutex_unlock(&mdev->graph_mutex);
1023                 return PTR_ERR(pipe);
1024         }
1025
1026         ret = __media_pipeline_start(&video->video.entity, &pipe->pipe);
1027         if (ret < 0) {
1028                 mutex_unlock(&mdev->graph_mutex);
1029                 goto err_pipe;
1030         }
1031
1032         mutex_unlock(&mdev->graph_mutex);
1033
1034         /*
1035          * Verify that the configured format matches the output of the connected
1036          * subdev.
1037          */
1038         ret = vsp1_video_verify_format(video);
1039         if (ret < 0)
1040                 goto err_stop;
1041
1042         /* Start the queue. */
1043         ret = vb2_streamon(&video->queue, type);
1044         if (ret < 0)
1045                 goto err_stop;
1046
1047         return 0;
1048
1049 err_stop:
1050         media_pipeline_stop(&video->video.entity);
1051 err_pipe:
1052         vsp1_video_pipeline_put(pipe);
1053         return ret;
1054 }
1055
1056 static const struct v4l2_ioctl_ops vsp1_video_ioctl_ops = {
1057         .vidioc_querycap                = vsp1_video_querycap,
1058         .vidioc_g_fmt_vid_cap_mplane    = vsp1_video_get_format,
1059         .vidioc_s_fmt_vid_cap_mplane    = vsp1_video_set_format,
1060         .vidioc_try_fmt_vid_cap_mplane  = vsp1_video_try_format,
1061         .vidioc_g_fmt_vid_out_mplane    = vsp1_video_get_format,
1062         .vidioc_s_fmt_vid_out_mplane    = vsp1_video_set_format,
1063         .vidioc_try_fmt_vid_out_mplane  = vsp1_video_try_format,
1064         .vidioc_reqbufs                 = vb2_ioctl_reqbufs,
1065         .vidioc_querybuf                = vb2_ioctl_querybuf,
1066         .vidioc_qbuf                    = vb2_ioctl_qbuf,
1067         .vidioc_dqbuf                   = vb2_ioctl_dqbuf,
1068         .vidioc_expbuf                  = vb2_ioctl_expbuf,
1069         .vidioc_create_bufs             = vb2_ioctl_create_bufs,
1070         .vidioc_prepare_buf             = vb2_ioctl_prepare_buf,
1071         .vidioc_streamon                = vsp1_video_streamon,
1072         .vidioc_streamoff               = vb2_ioctl_streamoff,
1073 };
1074
1075 /* -----------------------------------------------------------------------------
1076  * V4L2 File Operations
1077  */
1078
1079 static int vsp1_video_open(struct file *file)
1080 {
1081         struct vsp1_video *video = video_drvdata(file);
1082         struct v4l2_fh *vfh;
1083         int ret = 0;
1084
1085         vfh = kzalloc(sizeof(*vfh), GFP_KERNEL);
1086         if (vfh == NULL)
1087                 return -ENOMEM;
1088
1089         v4l2_fh_init(vfh, &video->video);
1090         v4l2_fh_add(vfh);
1091
1092         file->private_data = vfh;
1093
1094         ret = vsp1_device_get(video->vsp1);
1095         if (ret < 0) {
1096                 v4l2_fh_del(vfh);
1097                 v4l2_fh_exit(vfh);
1098                 kfree(vfh);
1099         }
1100
1101         return ret;
1102 }
1103
1104 static int vsp1_video_release(struct file *file)
1105 {
1106         struct vsp1_video *video = video_drvdata(file);
1107         struct v4l2_fh *vfh = file->private_data;
1108
1109         mutex_lock(&video->lock);
1110         if (video->queue.owner == vfh) {
1111                 vb2_queue_release(&video->queue);
1112                 video->queue.owner = NULL;
1113         }
1114         mutex_unlock(&video->lock);
1115
1116         vsp1_device_put(video->vsp1);
1117
1118         v4l2_fh_release(file);
1119
1120         file->private_data = NULL;
1121
1122         return 0;
1123 }
1124
1125 static const struct v4l2_file_operations vsp1_video_fops = {
1126         .owner = THIS_MODULE,
1127         .unlocked_ioctl = video_ioctl2,
1128         .open = vsp1_video_open,
1129         .release = vsp1_video_release,
1130         .poll = vb2_fop_poll,
1131         .mmap = vb2_fop_mmap,
1132 };
1133
1134 /* -----------------------------------------------------------------------------
1135  * Initialization and Cleanup
1136  */
1137
1138 struct vsp1_video *vsp1_video_create(struct vsp1_device *vsp1,
1139                                      struct vsp1_rwpf *rwpf)
1140 {
1141         struct vsp1_video *video;
1142         const char *direction;
1143         int ret;
1144
1145         video = devm_kzalloc(vsp1->dev, sizeof(*video), GFP_KERNEL);
1146         if (!video)
1147                 return ERR_PTR(-ENOMEM);
1148
1149         rwpf->video = video;
1150
1151         video->vsp1 = vsp1;
1152         video->rwpf = rwpf;
1153
1154         if (rwpf->entity.type == VSP1_ENTITY_RPF) {
1155                 direction = "input";
1156                 video->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1157                 video->pad.flags = MEDIA_PAD_FL_SOURCE;
1158                 video->video.vfl_dir = VFL_DIR_TX;
1159         } else {
1160                 direction = "output";
1161                 video->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1162                 video->pad.flags = MEDIA_PAD_FL_SINK;
1163                 video->video.vfl_dir = VFL_DIR_RX;
1164         }
1165
1166         mutex_init(&video->lock);
1167         spin_lock_init(&video->irqlock);
1168         INIT_LIST_HEAD(&video->irqqueue);
1169
1170         /* Initialize the media entity... */
1171         ret = media_entity_pads_init(&video->video.entity, 1, &video->pad);
1172         if (ret < 0)
1173                 return ERR_PTR(ret);
1174
1175         /* ... and the format ... */
1176         rwpf->format.pixelformat = VSP1_VIDEO_DEF_FORMAT;
1177         rwpf->format.width = VSP1_VIDEO_DEF_WIDTH;
1178         rwpf->format.height = VSP1_VIDEO_DEF_HEIGHT;
1179         __vsp1_video_try_format(video, &rwpf->format, &rwpf->fmtinfo);
1180
1181         /* ... and the video node... */
1182         video->video.v4l2_dev = &video->vsp1->v4l2_dev;
1183         video->video.fops = &vsp1_video_fops;
1184         snprintf(video->video.name, sizeof(video->video.name), "%s %s",
1185                  rwpf->entity.subdev.name, direction);
1186         video->video.vfl_type = VFL_TYPE_GRABBER;
1187         video->video.release = video_device_release_empty;
1188         video->video.ioctl_ops = &vsp1_video_ioctl_ops;
1189
1190         video_set_drvdata(&video->video, video);
1191
1192         video->queue.type = video->type;
1193         video->queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1194         video->queue.lock = &video->lock;
1195         video->queue.drv_priv = video;
1196         video->queue.buf_struct_size = sizeof(struct vsp1_vb2_buffer);
1197         video->queue.ops = &vsp1_video_queue_qops;
1198         video->queue.mem_ops = &vb2_dma_contig_memops;
1199         video->queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1200         video->queue.dev = video->vsp1->bus_master;
1201         ret = vb2_queue_init(&video->queue);
1202         if (ret < 0) {
1203                 dev_err(video->vsp1->dev, "failed to initialize vb2 queue\n");
1204                 goto error;
1205         }
1206
1207         /* ... and register the video device. */
1208         video->video.queue = &video->queue;
1209         ret = video_register_device(&video->video, VFL_TYPE_GRABBER, -1);
1210         if (ret < 0) {
1211                 dev_err(video->vsp1->dev, "failed to register video device\n");
1212                 goto error;
1213         }
1214
1215         return video;
1216
1217 error:
1218         vsp1_video_cleanup(video);
1219         return ERR_PTR(ret);
1220 }
1221
1222 void vsp1_video_cleanup(struct vsp1_video *video)
1223 {
1224         if (video_is_registered(&video->video))
1225                 video_unregister_device(&video->video);
1226
1227         media_entity_cleanup(&video->video.entity);
1228 }