GNU Linux-libre 4.19.245-gnu1
[releases.git] / drivers / media / platform / renesas-ceu.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * V4L2 Driver for Renesas Capture Engine Unit (CEU) interface
4  * Copyright (C) 2017-2018 Jacopo Mondi <jacopo+renesas@jmondi.org>
5  *
6  * Based on soc-camera driver "soc_camera/sh_mobile_ceu_camera.c"
7  * Copyright (C) 2008 Magnus Damm
8  *
9  * Based on V4L2 Driver for PXA camera host - "pxa_camera.c",
10  * Copyright (C) 2006, Sascha Hauer, Pengutronix
11  * Copyright (C) 2008, Guennadi Liakhovetski <kernel@pengutronix.de>
12  */
13
14 #include <linux/delay.h>
15 #include <linux/device.h>
16 #include <linux/dma-mapping.h>
17 #include <linux/err.h>
18 #include <linux/errno.h>
19 #include <linux/interrupt.h>
20 #include <linux/io.h>
21 #include <linux/kernel.h>
22 #include <linux/mm.h>
23 #include <linux/module.h>
24 #include <linux/of.h>
25 #include <linux/of_device.h>
26 #include <linux/of_graph.h>
27 #include <linux/platform_device.h>
28 #include <linux/pm_runtime.h>
29 #include <linux/slab.h>
30 #include <linux/time.h>
31 #include <linux/videodev2.h>
32
33 #include <media/v4l2-async.h>
34 #include <media/v4l2-common.h>
35 #include <media/v4l2-ctrls.h>
36 #include <media/v4l2-dev.h>
37 #include <media/v4l2-device.h>
38 #include <media/v4l2-event.h>
39 #include <media/v4l2-fwnode.h>
40 #include <media/v4l2-image-sizes.h>
41 #include <media/v4l2-ioctl.h>
42 #include <media/v4l2-mediabus.h>
43 #include <media/videobuf2-dma-contig.h>
44
45 #include <media/drv-intf/renesas-ceu.h>
46
47 #define DRIVER_NAME     "renesas-ceu"
48
49 /* CEU registers offsets and masks. */
50 #define CEU_CAPSR       0x00 /* Capture start register                  */
51 #define CEU_CAPCR       0x04 /* Capture control register                */
52 #define CEU_CAMCR       0x08 /* Capture interface control register      */
53 #define CEU_CAMOR       0x10 /* Capture interface offset register       */
54 #define CEU_CAPWR       0x14 /* Capture interface width register        */
55 #define CEU_CAIFR       0x18 /* Capture interface input format register */
56 #define CEU_CRCNTR      0x28 /* CEU register control register           */
57 #define CEU_CRCMPR      0x2c /* CEU register forcible control register  */
58 #define CEU_CFLCR       0x30 /* Capture filter control register         */
59 #define CEU_CFSZR       0x34 /* Capture filter size clip register       */
60 #define CEU_CDWDR       0x38 /* Capture destination width register      */
61 #define CEU_CDAYR       0x3c /* Capture data address Y register         */
62 #define CEU_CDACR       0x40 /* Capture data address C register         */
63 #define CEU_CFWCR       0x5c /* Firewall operation control register     */
64 #define CEU_CDOCR       0x64 /* Capture data output control register    */
65 #define CEU_CEIER       0x70 /* Capture event interrupt enable register */
66 #define CEU_CETCR       0x74 /* Capture event flag clear register       */
67 #define CEU_CSTSR       0x7c /* Capture status register                 */
68 #define CEU_CSRTR       0x80 /* Capture software reset register         */
69
70 /* Data synchronous fetch mode. */
71 #define CEU_CAMCR_JPEG                  BIT(4)
72
73 /* Input components ordering: CEU_CAMCR.DTARY field. */
74 #define CEU_CAMCR_DTARY_8_UYVY          (0x00 << 8)
75 #define CEU_CAMCR_DTARY_8_VYUY          (0x01 << 8)
76 #define CEU_CAMCR_DTARY_8_YUYV          (0x02 << 8)
77 #define CEU_CAMCR_DTARY_8_YVYU          (0x03 << 8)
78 /* TODO: input components ordering for 16 bits input. */
79
80 /* Bus transfer MTU. */
81 #define CEU_CAPCR_BUS_WIDTH256          (0x3 << 20)
82
83 /* Bus width configuration. */
84 #define CEU_CAMCR_DTIF_16BITS           BIT(12)
85
86 /* No downsampling to planar YUV420 in image fetch mode. */
87 #define CEU_CDOCR_NO_DOWSAMPLE          BIT(4)
88
89 /* Swap all input data in 8-bit, 16-bits and 32-bits units (Figure 46.45). */
90 #define CEU_CDOCR_SWAP_ENDIANNESS       (7)
91
92 /* Capture reset and enable bits. */
93 #define CEU_CAPSR_CPKIL                 BIT(16)
94 #define CEU_CAPSR_CE                    BIT(0)
95
96 /* CEU operating flag bit. */
97 #define CEU_CAPCR_CTNCP                 BIT(16)
98 #define CEU_CSTRST_CPTON                BIT(0)
99
100 /* Platform specific IRQ source flags. */
101 #define CEU_CETCR_ALL_IRQS_RZ           0x397f313
102 #define CEU_CETCR_ALL_IRQS_SH4          0x3d7f313
103
104 /* Prohibited register access interrupt bit. */
105 #define CEU_CETCR_IGRW                  BIT(4)
106 /* One-frame capture end interrupt. */
107 #define CEU_CEIER_CPE                   BIT(0)
108 /* VBP error. */
109 #define CEU_CEIER_VBP                   BIT(20)
110 #define CEU_CEIER_MASK                  (CEU_CEIER_CPE | CEU_CEIER_VBP)
111
112 #define CEU_MAX_WIDTH   2560
113 #define CEU_MAX_HEIGHT  1920
114 #define CEU_MAX_BPL     8188
115 #define CEU_W_MAX(w)    ((w) < CEU_MAX_WIDTH ? (w) : CEU_MAX_WIDTH)
116 #define CEU_H_MAX(h)    ((h) < CEU_MAX_HEIGHT ? (h) : CEU_MAX_HEIGHT)
117
118 /*
119  * ceu_bus_fmt - describe a 8-bits yuyv format the sensor can produce
120  *
121  * @mbus_code: bus format code
122  * @fmt_order: CEU_CAMCR.DTARY ordering of input components (Y, Cb, Cr)
123  * @fmt_order_swap: swapped CEU_CAMCR.DTARY ordering of input components
124  *                  (Y, Cr, Cb)
125  * @swapped: does Cr appear before Cb?
126  * @bps: number of bits sent over bus for each sample
127  * @bpp: number of bits per pixels unit
128  */
129 struct ceu_mbus_fmt {
130         u32     mbus_code;
131         u32     fmt_order;
132         u32     fmt_order_swap;
133         bool    swapped;
134         u8      bps;
135         u8      bpp;
136 };
137
138 /*
139  * ceu_buffer - Link vb2 buffer to the list of available buffers.
140  */
141 struct ceu_buffer {
142         struct vb2_v4l2_buffer vb;
143         struct list_head queue;
144 };
145
146 static inline struct ceu_buffer *vb2_to_ceu(struct vb2_v4l2_buffer *vbuf)
147 {
148         return container_of(vbuf, struct ceu_buffer, vb);
149 }
150
151 /*
152  * ceu_subdev - Wraps v4l2 sub-device and provides async subdevice.
153  */
154 struct ceu_subdev {
155         struct v4l2_subdev *v4l2_sd;
156         struct v4l2_async_subdev asd;
157
158         /* per-subdevice mbus configuration options */
159         unsigned int mbus_flags;
160         struct ceu_mbus_fmt mbus_fmt;
161 };
162
163 static struct ceu_subdev *to_ceu_subdev(struct v4l2_async_subdev *asd)
164 {
165         return container_of(asd, struct ceu_subdev, asd);
166 }
167
168 /*
169  * ceu_device - CEU device instance
170  */
171 struct ceu_device {
172         struct device           *dev;
173         struct video_device     vdev;
174         struct v4l2_device      v4l2_dev;
175
176         /* subdevices descriptors */
177         struct ceu_subdev       *subdevs;
178         /* the subdevice currently in use */
179         struct ceu_subdev       *sd;
180         unsigned int            sd_index;
181         unsigned int            num_sd;
182
183         /* platform specific mask with all IRQ sources flagged */
184         u32                     irq_mask;
185
186         /* currently configured field and pixel format */
187         enum v4l2_field field;
188         struct v4l2_pix_format_mplane v4l2_pix;
189
190         /* async subdev notification helpers */
191         struct v4l2_async_notifier notifier;
192         /* pointers to "struct ceu_subdevice -> asd" */
193         struct v4l2_async_subdev **asds;
194
195         /* vb2 queue, capture buffer list and active buffer pointer */
196         struct vb2_queue        vb2_vq;
197         struct list_head        capture;
198         struct vb2_v4l2_buffer  *active;
199         unsigned int            sequence;
200
201         /* mlock - lock access to interface reset and vb2 queue */
202         struct mutex    mlock;
203
204         /* lock - lock access to capture buffer queue and active buffer */
205         spinlock_t      lock;
206
207         /* base - CEU memory base address */
208         void __iomem    *base;
209 };
210
211 static inline struct ceu_device *v4l2_to_ceu(struct v4l2_device *v4l2_dev)
212 {
213         return container_of(v4l2_dev, struct ceu_device, v4l2_dev);
214 }
215
216 /* --- CEU memory output formats --- */
217
218 /*
219  * ceu_fmt - describe a memory output format supported by CEU interface.
220  *
221  * @fourcc: memory layout fourcc format code
222  * @bpp: number of bits for each pixel stored in memory
223  */
224 struct ceu_fmt {
225         u32     fourcc;
226         u32     bpp;
227 };
228
229 /*
230  * ceu_format_list - List of supported memory output formats
231  *
232  * If sensor provides any YUYV bus format, all the following planar memory
233  * formats are available thanks to CEU re-ordering and sub-sampling
234  * capabilities.
235  */
236 static const struct ceu_fmt ceu_fmt_list[] = {
237         {
238                 .fourcc = V4L2_PIX_FMT_NV16,
239                 .bpp    = 16,
240         },
241         {
242                 .fourcc = V4L2_PIX_FMT_NV61,
243                 .bpp    = 16,
244         },
245         {
246                 .fourcc = V4L2_PIX_FMT_NV12,
247                 .bpp    = 12,
248         },
249         {
250                 .fourcc = V4L2_PIX_FMT_NV21,
251                 .bpp    = 12,
252         },
253         {
254                 .fourcc = V4L2_PIX_FMT_YUYV,
255                 .bpp    = 16,
256         },
257         {
258                 .fourcc = V4L2_PIX_FMT_UYVY,
259                 .bpp    = 16,
260         },
261         {
262                 .fourcc = V4L2_PIX_FMT_YVYU,
263                 .bpp    = 16,
264         },
265         {
266                 .fourcc = V4L2_PIX_FMT_VYUY,
267                 .bpp    = 16,
268         },
269 };
270
271 static const struct ceu_fmt *get_ceu_fmt_from_fourcc(unsigned int fourcc)
272 {
273         const struct ceu_fmt *fmt = &ceu_fmt_list[0];
274         unsigned int i;
275
276         for (i = 0; i < ARRAY_SIZE(ceu_fmt_list); i++, fmt++)
277                 if (fmt->fourcc == fourcc)
278                         return fmt;
279
280         return NULL;
281 }
282
283 static bool ceu_fmt_mplane(struct v4l2_pix_format_mplane *pix)
284 {
285         switch (pix->pixelformat) {
286         case V4L2_PIX_FMT_YUYV:
287         case V4L2_PIX_FMT_UYVY:
288         case V4L2_PIX_FMT_YVYU:
289         case V4L2_PIX_FMT_VYUY:
290                 return false;
291         case V4L2_PIX_FMT_NV16:
292         case V4L2_PIX_FMT_NV61:
293         case V4L2_PIX_FMT_NV12:
294         case V4L2_PIX_FMT_NV21:
295                 return true;
296         default:
297                 return false;
298         }
299 }
300
301 /* --- CEU HW operations --- */
302
303 static void ceu_write(struct ceu_device *priv, unsigned int reg_offs, u32 data)
304 {
305         iowrite32(data, priv->base + reg_offs);
306 }
307
308 static u32 ceu_read(struct ceu_device *priv, unsigned int reg_offs)
309 {
310         return ioread32(priv->base + reg_offs);
311 }
312
313 /*
314  * ceu_soft_reset() - Software reset the CEU interface.
315  * @ceu_device: CEU device.
316  *
317  * Returns 0 for success, -EIO for error.
318  */
319 static int ceu_soft_reset(struct ceu_device *ceudev)
320 {
321         unsigned int i;
322
323         ceu_write(ceudev, CEU_CAPSR, CEU_CAPSR_CPKIL);
324
325         for (i = 0; i < 100; i++) {
326                 if (!(ceu_read(ceudev, CEU_CSTSR) & CEU_CSTRST_CPTON))
327                         break;
328                 udelay(1);
329         }
330
331         if (i == 100) {
332                 dev_err(ceudev->dev, "soft reset time out\n");
333                 return -EIO;
334         }
335
336         for (i = 0; i < 100; i++) {
337                 if (!(ceu_read(ceudev, CEU_CAPSR) & CEU_CAPSR_CPKIL))
338                         return 0;
339                 udelay(1);
340         }
341
342         /* If we get here, CEU has not reset properly. */
343         return -EIO;
344 }
345
346 /* --- CEU Capture Operations --- */
347
348 /*
349  * ceu_hw_config() - Configure CEU interface registers.
350  */
351 static int ceu_hw_config(struct ceu_device *ceudev)
352 {
353         u32 camcr, cdocr, cfzsr, cdwdr, capwr;
354         struct v4l2_pix_format_mplane *pix = &ceudev->v4l2_pix;
355         struct ceu_subdev *ceu_sd = ceudev->sd;
356         struct ceu_mbus_fmt *mbus_fmt = &ceu_sd->mbus_fmt;
357         unsigned int mbus_flags = ceu_sd->mbus_flags;
358
359         /* Start configuring CEU registers */
360         ceu_write(ceudev, CEU_CAIFR, 0);
361         ceu_write(ceudev, CEU_CFWCR, 0);
362         ceu_write(ceudev, CEU_CRCNTR, 0);
363         ceu_write(ceudev, CEU_CRCMPR, 0);
364
365         /* Set the frame capture period for both image capture and data sync. */
366         capwr = (pix->height << 16) | pix->width * mbus_fmt->bpp / 8;
367
368         /*
369          * Swap input data endianness by default.
370          * In data fetch mode bytes are received in chunks of 8 bytes.
371          * D0, D1, D2, D3, D4, D5, D6, D7 (D0 received first)
372          * The data is however by default written to memory in reverse order:
373          * D7, D6, D5, D4, D3, D2, D1, D0 (D7 written to lowest byte)
374          *
375          * Use CEU_CDOCR[2:0] to swap data ordering.
376          */
377         cdocr = CEU_CDOCR_SWAP_ENDIANNESS;
378
379         /*
380          * Configure CAMCR and CDOCR:
381          * match input components ordering with memory output format and
382          * handle downsampling to YUV420.
383          *
384          * If the memory output planar format is 'swapped' (Cr before Cb) and
385          * input format is not, use the swapped version of CAMCR.DTARY.
386          *
387          * If the memory output planar format is not 'swapped' (Cb before Cr)
388          * and input format is, use the swapped version of CAMCR.DTARY.
389          *
390          * CEU by default downsample to planar YUV420 (CDCOR[4] = 0).
391          * If output is planar YUV422 set CDOCR[4] = 1
392          *
393          * No downsample for data fetch sync mode.
394          */
395         switch (pix->pixelformat) {
396         /* Data fetch sync mode */
397         case V4L2_PIX_FMT_YUYV:
398         case V4L2_PIX_FMT_YVYU:
399         case V4L2_PIX_FMT_UYVY:
400         case V4L2_PIX_FMT_VYUY:
401                 camcr   = CEU_CAMCR_JPEG;
402                 cdocr   |= CEU_CDOCR_NO_DOWSAMPLE;
403                 cfzsr   = (pix->height << 16) | pix->width;
404                 cdwdr   = pix->plane_fmt[0].bytesperline;
405                 break;
406
407         /* Non-swapped planar image capture mode. */
408         case V4L2_PIX_FMT_NV16:
409                 cdocr   |= CEU_CDOCR_NO_DOWSAMPLE;
410                 /* fall-through */
411         case V4L2_PIX_FMT_NV12:
412                 if (mbus_fmt->swapped)
413                         camcr = mbus_fmt->fmt_order_swap;
414                 else
415                         camcr = mbus_fmt->fmt_order;
416
417                 cfzsr   = (pix->height << 16) | pix->width;
418                 cdwdr   = pix->width;
419                 break;
420
421         /* Swapped planar image capture mode. */
422         case V4L2_PIX_FMT_NV61:
423                 cdocr   |= CEU_CDOCR_NO_DOWSAMPLE;
424                 /* fall-through */
425         case V4L2_PIX_FMT_NV21:
426                 if (mbus_fmt->swapped)
427                         camcr = mbus_fmt->fmt_order;
428                 else
429                         camcr = mbus_fmt->fmt_order_swap;
430
431                 cfzsr   = (pix->height << 16) | pix->width;
432                 cdwdr   = pix->width;
433                 break;
434
435         default:
436                 return -EINVAL;
437         }
438
439         camcr |= mbus_flags & V4L2_MBUS_VSYNC_ACTIVE_LOW ? 1 << 1 : 0;
440         camcr |= mbus_flags & V4L2_MBUS_HSYNC_ACTIVE_LOW ? 1 << 0 : 0;
441
442         /* TODO: handle 16 bit bus width with DTIF bit in CAMCR */
443         ceu_write(ceudev, CEU_CAMCR, camcr);
444         ceu_write(ceudev, CEU_CDOCR, cdocr);
445         ceu_write(ceudev, CEU_CAPCR, CEU_CAPCR_BUS_WIDTH256);
446
447         /*
448          * TODO: make CAMOR offsets configurable.
449          * CAMOR wants to know the number of blanks between a VS/HS signal
450          * and valid data. This value should actually come from the sensor...
451          */
452         ceu_write(ceudev, CEU_CAMOR, 0);
453
454         /* TODO: 16 bit bus width require re-calculation of cdwdr and cfzsr */
455         ceu_write(ceudev, CEU_CAPWR, capwr);
456         ceu_write(ceudev, CEU_CFSZR, cfzsr);
457         ceu_write(ceudev, CEU_CDWDR, cdwdr);
458
459         return 0;
460 }
461
462 /*
463  * ceu_capture() - Trigger start of a capture sequence.
464  *
465  * Program the CEU DMA registers with addresses where to transfer image data.
466  */
467 static int ceu_capture(struct ceu_device *ceudev)
468 {
469         struct v4l2_pix_format_mplane *pix = &ceudev->v4l2_pix;
470         dma_addr_t phys_addr_top;
471
472         phys_addr_top =
473                 vb2_dma_contig_plane_dma_addr(&ceudev->active->vb2_buf, 0);
474         ceu_write(ceudev, CEU_CDAYR, phys_addr_top);
475
476         /* Ignore CbCr plane for non multi-planar image formats. */
477         if (ceu_fmt_mplane(pix)) {
478                 phys_addr_top =
479                         vb2_dma_contig_plane_dma_addr(&ceudev->active->vb2_buf,
480                                                       1);
481                 ceu_write(ceudev, CEU_CDACR, phys_addr_top);
482         }
483
484         /*
485          * Trigger new capture start: once for each frame, as we work in
486          * one-frame capture mode.
487          */
488         ceu_write(ceudev, CEU_CAPSR, CEU_CAPSR_CE);
489
490         return 0;
491 }
492
493 static irqreturn_t ceu_irq(int irq, void *data)
494 {
495         struct ceu_device *ceudev = data;
496         struct vb2_v4l2_buffer *vbuf;
497         struct ceu_buffer *buf;
498         u32 status;
499
500         /* Clean interrupt status. */
501         status = ceu_read(ceudev, CEU_CETCR);
502         ceu_write(ceudev, CEU_CETCR, ~ceudev->irq_mask);
503
504         /* Unexpected interrupt. */
505         if (!(status & CEU_CEIER_MASK))
506                 return IRQ_NONE;
507
508         spin_lock(&ceudev->lock);
509
510         /* Stale interrupt from a released buffer, ignore it. */
511         vbuf = ceudev->active;
512         if (!vbuf) {
513                 spin_unlock(&ceudev->lock);
514                 return IRQ_HANDLED;
515         }
516
517         /*
518          * When a VBP interrupt occurs, no capture end interrupt will occur
519          * and the image of that frame is not captured correctly.
520          */
521         if (status & CEU_CEIER_VBP) {
522                 dev_err(ceudev->dev, "VBP interrupt: abort capture\n");
523                 goto error_irq_out;
524         }
525
526         /* Prepare to return the 'previous' buffer. */
527         vbuf->vb2_buf.timestamp = ktime_get_ns();
528         vbuf->sequence = ceudev->sequence++;
529         vbuf->field = ceudev->field;
530
531         /* Prepare a new 'active' buffer and trigger a new capture. */
532         if (!list_empty(&ceudev->capture)) {
533                 buf = list_first_entry(&ceudev->capture, struct ceu_buffer,
534                                        queue);
535                 list_del(&buf->queue);
536                 ceudev->active = &buf->vb;
537
538                 ceu_capture(ceudev);
539         }
540
541         /* Return the 'previous' buffer. */
542         vb2_buffer_done(&vbuf->vb2_buf, VB2_BUF_STATE_DONE);
543
544         spin_unlock(&ceudev->lock);
545
546         return IRQ_HANDLED;
547
548 error_irq_out:
549         /* Return the 'previous' buffer and all queued ones. */
550         vb2_buffer_done(&vbuf->vb2_buf, VB2_BUF_STATE_ERROR);
551
552         list_for_each_entry(buf, &ceudev->capture, queue)
553                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
554
555         spin_unlock(&ceudev->lock);
556
557         return IRQ_HANDLED;
558 }
559
560 /* --- CEU Videobuf2 operations --- */
561
562 static void ceu_update_plane_sizes(struct v4l2_plane_pix_format *plane,
563                                    unsigned int bpl, unsigned int szimage)
564 {
565         memset(plane, 0, sizeof(*plane));
566
567         plane->sizeimage = szimage;
568         if (plane->bytesperline < bpl || plane->bytesperline > CEU_MAX_BPL)
569                 plane->bytesperline = bpl;
570 }
571
572 /*
573  * ceu_calc_plane_sizes() - Fill per-plane 'struct v4l2_plane_pix_format'
574  *                          information according to the currently configured
575  *                          pixel format.
576  * @ceu_device: CEU device.
577  * @ceu_fmt: Active image format.
578  * @pix: Pixel format information (store line width and image sizes)
579  */
580 static void ceu_calc_plane_sizes(struct ceu_device *ceudev,
581                                  const struct ceu_fmt *ceu_fmt,
582                                  struct v4l2_pix_format_mplane *pix)
583 {
584         unsigned int bpl, szimage;
585
586         switch (pix->pixelformat) {
587         case V4L2_PIX_FMT_YUYV:
588         case V4L2_PIX_FMT_UYVY:
589         case V4L2_PIX_FMT_YVYU:
590         case V4L2_PIX_FMT_VYUY:
591                 pix->num_planes = 1;
592                 bpl             = pix->width * ceu_fmt->bpp / 8;
593                 szimage         = pix->height * bpl;
594                 ceu_update_plane_sizes(&pix->plane_fmt[0], bpl, szimage);
595                 break;
596
597         case V4L2_PIX_FMT_NV12:
598         case V4L2_PIX_FMT_NV21:
599                 pix->num_planes = 2;
600                 bpl             = pix->width;
601                 szimage         = pix->height * pix->width;
602                 ceu_update_plane_sizes(&pix->plane_fmt[0], bpl, szimage);
603                 ceu_update_plane_sizes(&pix->plane_fmt[1], bpl, szimage / 2);
604                 break;
605
606         case V4L2_PIX_FMT_NV16:
607         case V4L2_PIX_FMT_NV61:
608         default:
609                 pix->num_planes = 2;
610                 bpl             = pix->width;
611                 szimage         = pix->height * pix->width;
612                 ceu_update_plane_sizes(&pix->plane_fmt[0], bpl, szimage);
613                 ceu_update_plane_sizes(&pix->plane_fmt[1], bpl, szimage);
614                 break;
615         }
616 }
617
618 /*
619  * ceu_vb2_setup() - is called to check whether the driver can accept the
620  *                   requested number of buffers and to fill in plane sizes
621  *                   for the current frame format, if required.
622  */
623 static int ceu_vb2_setup(struct vb2_queue *vq, unsigned int *count,
624                          unsigned int *num_planes, unsigned int sizes[],
625                          struct device *alloc_devs[])
626 {
627         struct ceu_device *ceudev = vb2_get_drv_priv(vq);
628         struct v4l2_pix_format_mplane *pix = &ceudev->v4l2_pix;
629         unsigned int i;
630
631         /* num_planes is set: just check plane sizes. */
632         if (*num_planes) {
633                 for (i = 0; i < pix->num_planes; i++)
634                         if (sizes[i] < pix->plane_fmt[i].sizeimage)
635                                 return -EINVAL;
636
637                 return 0;
638         }
639
640         /* num_planes not set: called from REQBUFS, just set plane sizes. */
641         *num_planes = pix->num_planes;
642         for (i = 0; i < pix->num_planes; i++)
643                 sizes[i] = pix->plane_fmt[i].sizeimage;
644
645         return 0;
646 }
647
648 static void ceu_vb2_queue(struct vb2_buffer *vb)
649 {
650         struct ceu_device *ceudev = vb2_get_drv_priv(vb->vb2_queue);
651         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
652         struct ceu_buffer *buf = vb2_to_ceu(vbuf);
653         unsigned long irqflags;
654
655         spin_lock_irqsave(&ceudev->lock, irqflags);
656         list_add_tail(&buf->queue, &ceudev->capture);
657         spin_unlock_irqrestore(&ceudev->lock, irqflags);
658 }
659
660 static int ceu_vb2_prepare(struct vb2_buffer *vb)
661 {
662         struct ceu_device *ceudev = vb2_get_drv_priv(vb->vb2_queue);
663         struct v4l2_pix_format_mplane *pix = &ceudev->v4l2_pix;
664         unsigned int i;
665
666         for (i = 0; i < pix->num_planes; i++) {
667                 if (vb2_plane_size(vb, i) < pix->plane_fmt[i].sizeimage) {
668                         dev_err(ceudev->dev,
669                                 "Plane size too small (%lu < %u)\n",
670                                 vb2_plane_size(vb, i),
671                                 pix->plane_fmt[i].sizeimage);
672                         return -EINVAL;
673                 }
674
675                 vb2_set_plane_payload(vb, i, pix->plane_fmt[i].sizeimage);
676         }
677
678         return 0;
679 }
680
681 static int ceu_start_streaming(struct vb2_queue *vq, unsigned int count)
682 {
683         struct ceu_device *ceudev = vb2_get_drv_priv(vq);
684         struct v4l2_subdev *v4l2_sd = ceudev->sd->v4l2_sd;
685         struct ceu_buffer *buf;
686         unsigned long irqflags;
687         int ret;
688
689         /* Program the CEU interface according to the CEU image format. */
690         ret = ceu_hw_config(ceudev);
691         if (ret)
692                 goto error_return_bufs;
693
694         ret = v4l2_subdev_call(v4l2_sd, video, s_stream, 1);
695         if (ret && ret != -ENOIOCTLCMD) {
696                 dev_dbg(ceudev->dev,
697                         "Subdevice failed to start streaming: %d\n", ret);
698                 goto error_return_bufs;
699         }
700
701         spin_lock_irqsave(&ceudev->lock, irqflags);
702         ceudev->sequence = 0;
703
704         /* Grab the first available buffer and trigger the first capture. */
705         buf = list_first_entry(&ceudev->capture, struct ceu_buffer,
706                                queue);
707         if (!buf) {
708                 spin_unlock_irqrestore(&ceudev->lock, irqflags);
709                 dev_dbg(ceudev->dev,
710                         "No buffer available for capture.\n");
711                 goto error_stop_sensor;
712         }
713
714         list_del(&buf->queue);
715         ceudev->active = &buf->vb;
716
717         /* Clean and program interrupts for first capture. */
718         ceu_write(ceudev, CEU_CETCR, ~ceudev->irq_mask);
719         ceu_write(ceudev, CEU_CEIER, CEU_CEIER_MASK);
720
721         ceu_capture(ceudev);
722
723         spin_unlock_irqrestore(&ceudev->lock, irqflags);
724
725         return 0;
726
727 error_stop_sensor:
728         v4l2_subdev_call(v4l2_sd, video, s_stream, 0);
729
730 error_return_bufs:
731         spin_lock_irqsave(&ceudev->lock, irqflags);
732         list_for_each_entry(buf, &ceudev->capture, queue)
733                 vb2_buffer_done(&ceudev->active->vb2_buf,
734                                 VB2_BUF_STATE_QUEUED);
735         ceudev->active = NULL;
736         spin_unlock_irqrestore(&ceudev->lock, irqflags);
737
738         return ret;
739 }
740
741 static void ceu_stop_streaming(struct vb2_queue *vq)
742 {
743         struct ceu_device *ceudev = vb2_get_drv_priv(vq);
744         struct v4l2_subdev *v4l2_sd = ceudev->sd->v4l2_sd;
745         struct ceu_buffer *buf;
746         unsigned long irqflags;
747
748         /* Clean and disable interrupt sources. */
749         ceu_write(ceudev, CEU_CETCR,
750                   ceu_read(ceudev, CEU_CETCR) & ceudev->irq_mask);
751         ceu_write(ceudev, CEU_CEIER, CEU_CEIER_MASK);
752
753         v4l2_subdev_call(v4l2_sd, video, s_stream, 0);
754
755         spin_lock_irqsave(&ceudev->lock, irqflags);
756         if (ceudev->active) {
757                 vb2_buffer_done(&ceudev->active->vb2_buf,
758                                 VB2_BUF_STATE_ERROR);
759                 ceudev->active = NULL;
760         }
761
762         /* Release all queued buffers. */
763         list_for_each_entry(buf, &ceudev->capture, queue)
764                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
765         INIT_LIST_HEAD(&ceudev->capture);
766
767         spin_unlock_irqrestore(&ceudev->lock, irqflags);
768
769         ceu_soft_reset(ceudev);
770 }
771
772 static const struct vb2_ops ceu_vb2_ops = {
773         .queue_setup            = ceu_vb2_setup,
774         .buf_queue              = ceu_vb2_queue,
775         .buf_prepare            = ceu_vb2_prepare,
776         .wait_prepare           = vb2_ops_wait_prepare,
777         .wait_finish            = vb2_ops_wait_finish,
778         .start_streaming        = ceu_start_streaming,
779         .stop_streaming         = ceu_stop_streaming,
780 };
781
782 /* --- CEU image formats handling --- */
783
784 /*
785  * __ceu_try_fmt() - test format on CEU and sensor
786  * @ceudev: The CEU device.
787  * @v4l2_fmt: format to test.
788  * @sd_mbus_code: the media bus code accepted by the subdevice; output param.
789  *
790  * Returns 0 for success, < 0 for errors.
791  */
792 static int __ceu_try_fmt(struct ceu_device *ceudev, struct v4l2_format *v4l2_fmt,
793                          u32 *sd_mbus_code)
794 {
795         struct ceu_subdev *ceu_sd = ceudev->sd;
796         struct v4l2_pix_format_mplane *pix = &v4l2_fmt->fmt.pix_mp;
797         struct v4l2_subdev *v4l2_sd = ceu_sd->v4l2_sd;
798         struct v4l2_subdev_pad_config pad_cfg;
799         const struct ceu_fmt *ceu_fmt;
800         u32 mbus_code_old;
801         u32 mbus_code;
802         int ret;
803
804         /*
805          * Set format on sensor sub device: bus format used to produce memory
806          * format is selected depending on YUV component ordering or
807          * at initialization time.
808          */
809         struct v4l2_subdev_format sd_format = {
810                 .which  = V4L2_SUBDEV_FORMAT_TRY,
811         };
812
813         mbus_code_old = ceu_sd->mbus_fmt.mbus_code;
814
815         switch (pix->pixelformat) {
816         case V4L2_PIX_FMT_YUYV:
817                 mbus_code = MEDIA_BUS_FMT_YUYV8_2X8;
818                 break;
819         case V4L2_PIX_FMT_UYVY:
820                 mbus_code = MEDIA_BUS_FMT_UYVY8_2X8;
821                 break;
822         case V4L2_PIX_FMT_YVYU:
823                 mbus_code = MEDIA_BUS_FMT_YVYU8_2X8;
824                 break;
825         case V4L2_PIX_FMT_VYUY:
826                 mbus_code = MEDIA_BUS_FMT_VYUY8_2X8;
827                 break;
828         case V4L2_PIX_FMT_NV16:
829         case V4L2_PIX_FMT_NV61:
830         case V4L2_PIX_FMT_NV12:
831         case V4L2_PIX_FMT_NV21:
832                 mbus_code = ceu_sd->mbus_fmt.mbus_code;
833                 break;
834
835         default:
836                 pix->pixelformat = V4L2_PIX_FMT_NV16;
837                 mbus_code = ceu_sd->mbus_fmt.mbus_code;
838                 break;
839         }
840
841         ceu_fmt = get_ceu_fmt_from_fourcc(pix->pixelformat);
842
843         /* CFSZR requires height and width to be 4-pixel aligned. */
844         v4l_bound_align_image(&pix->width, 2, CEU_MAX_WIDTH, 4,
845                               &pix->height, 4, CEU_MAX_HEIGHT, 4, 0);
846
847         v4l2_fill_mbus_format_mplane(&sd_format.format, pix);
848
849         /*
850          * Try with the mbus_code matching YUYV components ordering first,
851          * if that one fails, fallback to default selected at initialization
852          * time.
853          */
854         sd_format.format.code = mbus_code;
855         ret = v4l2_subdev_call(v4l2_sd, pad, set_fmt, &pad_cfg, &sd_format);
856         if (ret) {
857                 if (ret == -EINVAL) {
858                         /* fallback */
859                         sd_format.format.code = mbus_code_old;
860                         ret = v4l2_subdev_call(v4l2_sd, pad, set_fmt,
861                                                &pad_cfg, &sd_format);
862                 }
863
864                 if (ret)
865                         return ret;
866         }
867
868         /* Apply size returned by sensor as the CEU can't scale. */
869         v4l2_fill_pix_format_mplane(pix, &sd_format.format);
870
871         /* Calculate per-plane sizes based on image format. */
872         ceu_calc_plane_sizes(ceudev, ceu_fmt, pix);
873
874         /* Report to caller the configured mbus format. */
875         *sd_mbus_code = sd_format.format.code;
876
877         return 0;
878 }
879
880 /*
881  * ceu_try_fmt() - Wrapper for __ceu_try_fmt; discard configured mbus_fmt
882  */
883 static int ceu_try_fmt(struct ceu_device *ceudev, struct v4l2_format *v4l2_fmt)
884 {
885         u32 mbus_code;
886
887         return __ceu_try_fmt(ceudev, v4l2_fmt, &mbus_code);
888 }
889
890 /*
891  * ceu_set_fmt() - Apply the supplied format to both sensor and CEU
892  */
893 static int ceu_set_fmt(struct ceu_device *ceudev, struct v4l2_format *v4l2_fmt)
894 {
895         struct ceu_subdev *ceu_sd = ceudev->sd;
896         struct v4l2_subdev *v4l2_sd = ceu_sd->v4l2_sd;
897         u32 mbus_code;
898         int ret;
899
900         /*
901          * Set format on sensor sub device: bus format used to produce memory
902          * format is selected at initialization time.
903          */
904         struct v4l2_subdev_format format = {
905                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
906         };
907
908         ret = __ceu_try_fmt(ceudev, v4l2_fmt, &mbus_code);
909         if (ret)
910                 return ret;
911
912         format.format.code = mbus_code;
913         v4l2_fill_mbus_format_mplane(&format.format, &v4l2_fmt->fmt.pix_mp);
914         ret = v4l2_subdev_call(v4l2_sd, pad, set_fmt, NULL, &format);
915         if (ret)
916                 return ret;
917
918         ceudev->v4l2_pix = v4l2_fmt->fmt.pix_mp;
919         ceudev->field = V4L2_FIELD_NONE;
920
921         return 0;
922 }
923
924 /*
925  * ceu_set_default_fmt() - Apply default NV16 memory output format with VGA
926  *                         sizes.
927  */
928 static int ceu_set_default_fmt(struct ceu_device *ceudev)
929 {
930         int ret;
931
932         struct v4l2_format v4l2_fmt = {
933                 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
934                 .fmt.pix_mp = {
935                         .width          = VGA_WIDTH,
936                         .height         = VGA_HEIGHT,
937                         .field          = V4L2_FIELD_NONE,
938                         .pixelformat    = V4L2_PIX_FMT_NV16,
939                         .num_planes     = 2,
940                         .plane_fmt      = {
941                                 [0]     = {
942                                         .sizeimage = VGA_WIDTH * VGA_HEIGHT * 2,
943                                         .bytesperline = VGA_WIDTH * 2,
944                                 },
945                                 [1]     = {
946                                         .sizeimage = VGA_WIDTH * VGA_HEIGHT * 2,
947                                         .bytesperline = VGA_WIDTH * 2,
948                                 },
949                         },
950                 },
951         };
952
953         ret = ceu_try_fmt(ceudev, &v4l2_fmt);
954         if (ret)
955                 return ret;
956
957         ceudev->v4l2_pix = v4l2_fmt.fmt.pix_mp;
958         ceudev->field = V4L2_FIELD_NONE;
959
960         return 0;
961 }
962
963 /*
964  * ceu_init_mbus_fmt() - Query sensor for supported formats and initialize
965  *                       CEU media bus format used to produce memory formats.
966  *
967  * Find out if sensor can produce a permutation of 8-bits YUYV bus format.
968  * From a single 8-bits YUYV bus format the CEU can produce several memory
969  * output formats:
970  * - NV[12|21|16|61] through image fetch mode;
971  * - YUYV422 if sensor provides YUYV422
972  *
973  * TODO: Other YUYV422 permutations through data fetch sync mode and DTARY
974  * TODO: Binary data (eg. JPEG) and raw formats through data fetch sync mode
975  */
976 static int ceu_init_mbus_fmt(struct ceu_device *ceudev)
977 {
978         struct ceu_subdev *ceu_sd = ceudev->sd;
979         struct ceu_mbus_fmt *mbus_fmt = &ceu_sd->mbus_fmt;
980         struct v4l2_subdev *v4l2_sd = ceu_sd->v4l2_sd;
981         bool yuyv_bus_fmt = false;
982
983         struct v4l2_subdev_mbus_code_enum sd_mbus_fmt = {
984                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
985                 .index = 0,
986         };
987
988         /* Find out if sensor can produce any permutation of 8-bits YUYV422. */
989         while (!yuyv_bus_fmt &&
990                !v4l2_subdev_call(v4l2_sd, pad, enum_mbus_code,
991                                  NULL, &sd_mbus_fmt)) {
992                 switch (sd_mbus_fmt.code) {
993                 case MEDIA_BUS_FMT_YUYV8_2X8:
994                 case MEDIA_BUS_FMT_YVYU8_2X8:
995                 case MEDIA_BUS_FMT_UYVY8_2X8:
996                 case MEDIA_BUS_FMT_VYUY8_2X8:
997                         yuyv_bus_fmt = true;
998                         break;
999                 default:
1000                         /*
1001                          * Only support 8-bits YUYV bus formats at the moment;
1002                          *
1003                          * TODO: add support for binary formats (data sync
1004                          * fetch mode).
1005                          */
1006                         break;
1007                 }
1008
1009                 sd_mbus_fmt.index++;
1010         }
1011
1012         if (!yuyv_bus_fmt)
1013                 return -ENXIO;
1014
1015         /*
1016          * Save the first encountered YUYV format as "mbus_fmt" and use it
1017          * to output all planar YUV422 and YUV420 (NV*) formats to memory as
1018          * well as for data synch fetch mode (YUYV - YVYU etc. ).
1019          */
1020         mbus_fmt->mbus_code     = sd_mbus_fmt.code;
1021         mbus_fmt->bps           = 8;
1022
1023         /* Annotate the selected bus format components ordering. */
1024         switch (sd_mbus_fmt.code) {
1025         case MEDIA_BUS_FMT_YUYV8_2X8:
1026                 mbus_fmt->fmt_order             = CEU_CAMCR_DTARY_8_YUYV;
1027                 mbus_fmt->fmt_order_swap        = CEU_CAMCR_DTARY_8_YVYU;
1028                 mbus_fmt->swapped               = false;
1029                 mbus_fmt->bpp                   = 16;
1030                 break;
1031
1032         case MEDIA_BUS_FMT_YVYU8_2X8:
1033                 mbus_fmt->fmt_order             = CEU_CAMCR_DTARY_8_YVYU;
1034                 mbus_fmt->fmt_order_swap        = CEU_CAMCR_DTARY_8_YUYV;
1035                 mbus_fmt->swapped               = true;
1036                 mbus_fmt->bpp                   = 16;
1037                 break;
1038
1039         case MEDIA_BUS_FMT_UYVY8_2X8:
1040                 mbus_fmt->fmt_order             = CEU_CAMCR_DTARY_8_UYVY;
1041                 mbus_fmt->fmt_order_swap        = CEU_CAMCR_DTARY_8_VYUY;
1042                 mbus_fmt->swapped               = false;
1043                 mbus_fmt->bpp                   = 16;
1044                 break;
1045
1046         case MEDIA_BUS_FMT_VYUY8_2X8:
1047                 mbus_fmt->fmt_order             = CEU_CAMCR_DTARY_8_VYUY;
1048                 mbus_fmt->fmt_order_swap        = CEU_CAMCR_DTARY_8_UYVY;
1049                 mbus_fmt->swapped               = true;
1050                 mbus_fmt->bpp                   = 16;
1051                 break;
1052         }
1053
1054         return 0;
1055 }
1056
1057 /* --- Runtime PM Handlers --- */
1058
1059 /*
1060  * ceu_runtime_resume() - soft-reset the interface and turn sensor power on.
1061  */
1062 static int __maybe_unused ceu_runtime_resume(struct device *dev)
1063 {
1064         struct ceu_device *ceudev = dev_get_drvdata(dev);
1065         struct v4l2_subdev *v4l2_sd = ceudev->sd->v4l2_sd;
1066
1067         v4l2_subdev_call(v4l2_sd, core, s_power, 1);
1068
1069         ceu_soft_reset(ceudev);
1070
1071         return 0;
1072 }
1073
1074 /*
1075  * ceu_runtime_suspend() - disable capture and interrupts and soft-reset.
1076  *                         Turn sensor power off.
1077  */
1078 static int __maybe_unused ceu_runtime_suspend(struct device *dev)
1079 {
1080         struct ceu_device *ceudev = dev_get_drvdata(dev);
1081         struct v4l2_subdev *v4l2_sd = ceudev->sd->v4l2_sd;
1082
1083         v4l2_subdev_call(v4l2_sd, core, s_power, 0);
1084
1085         ceu_write(ceudev, CEU_CEIER, 0);
1086         ceu_soft_reset(ceudev);
1087
1088         return 0;
1089 }
1090
1091 /* --- File Operations --- */
1092
1093 static int ceu_open(struct file *file)
1094 {
1095         struct ceu_device *ceudev = video_drvdata(file);
1096         int ret;
1097
1098         ret = v4l2_fh_open(file);
1099         if (ret)
1100                 return ret;
1101
1102         mutex_lock(&ceudev->mlock);
1103         /* Causes soft-reset and sensor power on on first open */
1104         pm_runtime_get_sync(ceudev->dev);
1105         mutex_unlock(&ceudev->mlock);
1106
1107         return 0;
1108 }
1109
1110 static int ceu_release(struct file *file)
1111 {
1112         struct ceu_device *ceudev = video_drvdata(file);
1113
1114         vb2_fop_release(file);
1115
1116         mutex_lock(&ceudev->mlock);
1117         /* Causes soft-reset and sensor power down on last close */
1118         pm_runtime_put(ceudev->dev);
1119         mutex_unlock(&ceudev->mlock);
1120
1121         return 0;
1122 }
1123
1124 static const struct v4l2_file_operations ceu_fops = {
1125         .owner                  = THIS_MODULE,
1126         .open                   = ceu_open,
1127         .release                = ceu_release,
1128         .unlocked_ioctl         = video_ioctl2,
1129         .mmap                   = vb2_fop_mmap,
1130         .poll                   = vb2_fop_poll,
1131 };
1132
1133 /* --- Video Device IOCTLs --- */
1134
1135 static int ceu_querycap(struct file *file, void *priv,
1136                         struct v4l2_capability *cap)
1137 {
1138         struct ceu_device *ceudev = video_drvdata(file);
1139
1140         strlcpy(cap->card, "Renesas CEU", sizeof(cap->card));
1141         strlcpy(cap->driver, DRIVER_NAME, sizeof(cap->driver));
1142         snprintf(cap->bus_info, sizeof(cap->bus_info),
1143                  "platform:renesas-ceu-%s", dev_name(ceudev->dev));
1144
1145         return 0;
1146 }
1147
1148 static int ceu_enum_fmt_vid_cap(struct file *file, void *priv,
1149                                 struct v4l2_fmtdesc *f)
1150 {
1151         const struct ceu_fmt *fmt;
1152
1153         if (f->index >= ARRAY_SIZE(ceu_fmt_list))
1154                 return -EINVAL;
1155
1156         fmt = &ceu_fmt_list[f->index];
1157         f->pixelformat = fmt->fourcc;
1158
1159         return 0;
1160 }
1161
1162 static int ceu_try_fmt_vid_cap(struct file *file, void *priv,
1163                                struct v4l2_format *f)
1164 {
1165         struct ceu_device *ceudev = video_drvdata(file);
1166
1167         return ceu_try_fmt(ceudev, f);
1168 }
1169
1170 static int ceu_s_fmt_vid_cap(struct file *file, void *priv,
1171                              struct v4l2_format *f)
1172 {
1173         struct ceu_device *ceudev = video_drvdata(file);
1174
1175         if (vb2_is_streaming(&ceudev->vb2_vq))
1176                 return -EBUSY;
1177
1178         return ceu_set_fmt(ceudev, f);
1179 }
1180
1181 static int ceu_g_fmt_vid_cap(struct file *file, void *priv,
1182                              struct v4l2_format *f)
1183 {
1184         struct ceu_device *ceudev = video_drvdata(file);
1185
1186         f->fmt.pix_mp = ceudev->v4l2_pix;
1187
1188         return 0;
1189 }
1190
1191 static int ceu_enum_input(struct file *file, void *priv,
1192                           struct v4l2_input *inp)
1193 {
1194         struct ceu_device *ceudev = video_drvdata(file);
1195         struct ceu_subdev *ceusd;
1196
1197         if (inp->index >= ceudev->num_sd)
1198                 return -EINVAL;
1199
1200         ceusd = &ceudev->subdevs[inp->index];
1201
1202         inp->type = V4L2_INPUT_TYPE_CAMERA;
1203         inp->std = 0;
1204         snprintf(inp->name, sizeof(inp->name), "Camera%u: %s",
1205                  inp->index, ceusd->v4l2_sd->name);
1206
1207         return 0;
1208 }
1209
1210 static int ceu_g_input(struct file *file, void *priv, unsigned int *i)
1211 {
1212         struct ceu_device *ceudev = video_drvdata(file);
1213
1214         *i = ceudev->sd_index;
1215
1216         return 0;
1217 }
1218
1219 static int ceu_s_input(struct file *file, void *priv, unsigned int i)
1220 {
1221         struct ceu_device *ceudev = video_drvdata(file);
1222         struct ceu_subdev *ceu_sd_old;
1223         int ret;
1224
1225         if (i >= ceudev->num_sd)
1226                 return -EINVAL;
1227
1228         if (vb2_is_streaming(&ceudev->vb2_vq))
1229                 return -EBUSY;
1230
1231         if (i == ceudev->sd_index)
1232                 return 0;
1233
1234         ceu_sd_old = ceudev->sd;
1235         ceudev->sd = &ceudev->subdevs[i];
1236
1237         /*
1238          * Make sure we can generate output image formats and apply
1239          * default one.
1240          */
1241         ret = ceu_init_mbus_fmt(ceudev);
1242         if (ret) {
1243                 ceudev->sd = ceu_sd_old;
1244                 return -EINVAL;
1245         }
1246
1247         ret = ceu_set_default_fmt(ceudev);
1248         if (ret) {
1249                 ceudev->sd = ceu_sd_old;
1250                 return -EINVAL;
1251         }
1252
1253         /* Now that we're sure we can use the sensor, power off the old one. */
1254         v4l2_subdev_call(ceu_sd_old->v4l2_sd, core, s_power, 0);
1255         v4l2_subdev_call(ceudev->sd->v4l2_sd, core, s_power, 1);
1256
1257         ceudev->sd_index = i;
1258
1259         return 0;
1260 }
1261
1262 static int ceu_g_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1263 {
1264         struct ceu_device *ceudev = video_drvdata(file);
1265
1266         return v4l2_g_parm_cap(video_devdata(file), ceudev->sd->v4l2_sd, a);
1267 }
1268
1269 static int ceu_s_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1270 {
1271         struct ceu_device *ceudev = video_drvdata(file);
1272
1273         return v4l2_s_parm_cap(video_devdata(file), ceudev->sd->v4l2_sd, a);
1274 }
1275
1276 static int ceu_enum_framesizes(struct file *file, void *fh,
1277                                struct v4l2_frmsizeenum *fsize)
1278 {
1279         struct ceu_device *ceudev = video_drvdata(file);
1280         struct ceu_subdev *ceu_sd = ceudev->sd;
1281         const struct ceu_fmt *ceu_fmt;
1282         struct v4l2_subdev *v4l2_sd = ceu_sd->v4l2_sd;
1283         int ret;
1284
1285         struct v4l2_subdev_frame_size_enum fse = {
1286                 .code   = ceu_sd->mbus_fmt.mbus_code,
1287                 .index  = fsize->index,
1288                 .which  = V4L2_SUBDEV_FORMAT_ACTIVE,
1289         };
1290
1291         /* Just check if user supplied pixel format is supported. */
1292         ceu_fmt = get_ceu_fmt_from_fourcc(fsize->pixel_format);
1293         if (!ceu_fmt)
1294                 return -EINVAL;
1295
1296         ret = v4l2_subdev_call(v4l2_sd, pad, enum_frame_size,
1297                                NULL, &fse);
1298         if (ret)
1299                 return ret;
1300
1301         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1302         fsize->discrete.width = CEU_W_MAX(fse.max_width);
1303         fsize->discrete.height = CEU_H_MAX(fse.max_height);
1304
1305         return 0;
1306 }
1307
1308 static int ceu_enum_frameintervals(struct file *file, void *fh,
1309                                    struct v4l2_frmivalenum *fival)
1310 {
1311         struct ceu_device *ceudev = video_drvdata(file);
1312         struct ceu_subdev *ceu_sd = ceudev->sd;
1313         const struct ceu_fmt *ceu_fmt;
1314         struct v4l2_subdev *v4l2_sd = ceu_sd->v4l2_sd;
1315         int ret;
1316
1317         struct v4l2_subdev_frame_interval_enum fie = {
1318                 .code   = ceu_sd->mbus_fmt.mbus_code,
1319                 .index = fival->index,
1320                 .width = fival->width,
1321                 .height = fival->height,
1322                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1323         };
1324
1325         /* Just check if user supplied pixel format is supported. */
1326         ceu_fmt = get_ceu_fmt_from_fourcc(fival->pixel_format);
1327         if (!ceu_fmt)
1328                 return -EINVAL;
1329
1330         ret = v4l2_subdev_call(v4l2_sd, pad, enum_frame_interval, NULL,
1331                                &fie);
1332         if (ret)
1333                 return ret;
1334
1335         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1336         fival->discrete = fie.interval;
1337
1338         return 0;
1339 }
1340
1341 static const struct v4l2_ioctl_ops ceu_ioctl_ops = {
1342         .vidioc_querycap                = ceu_querycap,
1343
1344         .vidioc_enum_fmt_vid_cap_mplane = ceu_enum_fmt_vid_cap,
1345         .vidioc_try_fmt_vid_cap_mplane  = ceu_try_fmt_vid_cap,
1346         .vidioc_s_fmt_vid_cap_mplane    = ceu_s_fmt_vid_cap,
1347         .vidioc_g_fmt_vid_cap_mplane    = ceu_g_fmt_vid_cap,
1348
1349         .vidioc_enum_input              = ceu_enum_input,
1350         .vidioc_g_input                 = ceu_g_input,
1351         .vidioc_s_input                 = ceu_s_input,
1352
1353         .vidioc_reqbufs                 = vb2_ioctl_reqbufs,
1354         .vidioc_querybuf                = vb2_ioctl_querybuf,
1355         .vidioc_qbuf                    = vb2_ioctl_qbuf,
1356         .vidioc_expbuf                  = vb2_ioctl_expbuf,
1357         .vidioc_dqbuf                   = vb2_ioctl_dqbuf,
1358         .vidioc_create_bufs             = vb2_ioctl_create_bufs,
1359         .vidioc_prepare_buf             = vb2_ioctl_prepare_buf,
1360         .vidioc_streamon                = vb2_ioctl_streamon,
1361         .vidioc_streamoff               = vb2_ioctl_streamoff,
1362
1363         .vidioc_g_parm                  = ceu_g_parm,
1364         .vidioc_s_parm                  = ceu_s_parm,
1365         .vidioc_enum_framesizes         = ceu_enum_framesizes,
1366         .vidioc_enum_frameintervals     = ceu_enum_frameintervals,
1367
1368         .vidioc_log_status              = v4l2_ctrl_log_status,
1369         .vidioc_subscribe_event         = v4l2_ctrl_subscribe_event,
1370         .vidioc_unsubscribe_event       = v4l2_event_unsubscribe,
1371 };
1372
1373 /*
1374  * ceu_vdev_release() - release CEU video device memory when last reference
1375  *                      to this driver is closed
1376  */
1377 static void ceu_vdev_release(struct video_device *vdev)
1378 {
1379         struct ceu_device *ceudev = video_get_drvdata(vdev);
1380
1381         kfree(ceudev);
1382 }
1383
1384 static int ceu_notify_bound(struct v4l2_async_notifier *notifier,
1385                             struct v4l2_subdev *v4l2_sd,
1386                             struct v4l2_async_subdev *asd)
1387 {
1388         struct v4l2_device *v4l2_dev = notifier->v4l2_dev;
1389         struct ceu_device *ceudev = v4l2_to_ceu(v4l2_dev);
1390         struct ceu_subdev *ceu_sd = to_ceu_subdev(asd);
1391
1392         ceu_sd->v4l2_sd = v4l2_sd;
1393         ceudev->num_sd++;
1394
1395         return 0;
1396 }
1397
1398 static int ceu_notify_complete(struct v4l2_async_notifier *notifier)
1399 {
1400         struct v4l2_device *v4l2_dev = notifier->v4l2_dev;
1401         struct ceu_device *ceudev = v4l2_to_ceu(v4l2_dev);
1402         struct video_device *vdev = &ceudev->vdev;
1403         struct vb2_queue *q = &ceudev->vb2_vq;
1404         struct v4l2_subdev *v4l2_sd;
1405         int ret;
1406
1407         /* Initialize vb2 queue. */
1408         q->type                 = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1409         q->io_modes             = VB2_MMAP | VB2_DMABUF;
1410         q->drv_priv             = ceudev;
1411         q->ops                  = &ceu_vb2_ops;
1412         q->mem_ops              = &vb2_dma_contig_memops;
1413         q->buf_struct_size      = sizeof(struct ceu_buffer);
1414         q->timestamp_flags      = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1415         q->min_buffers_needed   = 2;
1416         q->lock                 = &ceudev->mlock;
1417         q->dev                  = ceudev->v4l2_dev.dev;
1418
1419         ret = vb2_queue_init(q);
1420         if (ret)
1421                 return ret;
1422
1423         /*
1424          * Make sure at least one sensor is primary and use it to initialize
1425          * ceu formats.
1426          */
1427         if (!ceudev->sd) {
1428                 ceudev->sd = &ceudev->subdevs[0];
1429                 ceudev->sd_index = 0;
1430         }
1431
1432         v4l2_sd = ceudev->sd->v4l2_sd;
1433
1434         ret = ceu_init_mbus_fmt(ceudev);
1435         if (ret)
1436                 return ret;
1437
1438         ret = ceu_set_default_fmt(ceudev);
1439         if (ret)
1440                 return ret;
1441
1442         /* Register the video device. */
1443         strlcpy(vdev->name, DRIVER_NAME, sizeof(vdev->name));
1444         vdev->v4l2_dev          = v4l2_dev;
1445         vdev->lock              = &ceudev->mlock;
1446         vdev->queue             = &ceudev->vb2_vq;
1447         vdev->ctrl_handler      = v4l2_sd->ctrl_handler;
1448         vdev->fops              = &ceu_fops;
1449         vdev->ioctl_ops         = &ceu_ioctl_ops;
1450         vdev->release           = ceu_vdev_release;
1451         vdev->device_caps       = V4L2_CAP_VIDEO_CAPTURE_MPLANE |
1452                                   V4L2_CAP_STREAMING;
1453         video_set_drvdata(vdev, ceudev);
1454
1455         ret = video_register_device(vdev, VFL_TYPE_GRABBER, -1);
1456         if (ret < 0) {
1457                 v4l2_err(vdev->v4l2_dev,
1458                          "video_register_device failed: %d\n", ret);
1459                 return ret;
1460         }
1461
1462         return 0;
1463 }
1464
1465 static const struct v4l2_async_notifier_operations ceu_notify_ops = {
1466         .bound          = ceu_notify_bound,
1467         .complete       = ceu_notify_complete,
1468 };
1469
1470 /*
1471  * ceu_init_async_subdevs() - Initialize CEU subdevices and async_subdevs in
1472  *                            ceu device. Both DT and platform data parsing use
1473  *                            this routine.
1474  *
1475  * Returns 0 for success, -ENOMEM for failure.
1476  */
1477 static int ceu_init_async_subdevs(struct ceu_device *ceudev, unsigned int n_sd)
1478 {
1479         /* Reserve memory for 'n_sd' ceu_subdev descriptors. */
1480         ceudev->subdevs = devm_kcalloc(ceudev->dev, n_sd,
1481                                        sizeof(*ceudev->subdevs), GFP_KERNEL);
1482         if (!ceudev->subdevs)
1483                 return -ENOMEM;
1484
1485         /*
1486          * Reserve memory for 'n_sd' pointers to async_subdevices.
1487          * ceudev->asds members will point to &ceu_subdev.asd
1488          */
1489         ceudev->asds = devm_kcalloc(ceudev->dev, n_sd,
1490                                     sizeof(*ceudev->asds), GFP_KERNEL);
1491         if (!ceudev->asds)
1492                 return -ENOMEM;
1493
1494         ceudev->sd = NULL;
1495         ceudev->sd_index = 0;
1496         ceudev->num_sd = 0;
1497
1498         return 0;
1499 }
1500
1501 /*
1502  * ceu_parse_platform_data() - Initialize async_subdevices using platform
1503  *                             device provided data.
1504  */
1505 static int ceu_parse_platform_data(struct ceu_device *ceudev,
1506                                    const struct ceu_platform_data *pdata)
1507 {
1508         const struct ceu_async_subdev *async_sd;
1509         struct ceu_subdev *ceu_sd;
1510         unsigned int i;
1511         int ret;
1512
1513         if (pdata->num_subdevs == 0)
1514                 return -ENODEV;
1515
1516         ret = ceu_init_async_subdevs(ceudev, pdata->num_subdevs);
1517         if (ret)
1518                 return ret;
1519
1520         for (i = 0; i < pdata->num_subdevs; i++) {
1521                 /* Setup the ceu subdevice and the async subdevice. */
1522                 async_sd = &pdata->subdevs[i];
1523                 ceu_sd = &ceudev->subdevs[i];
1524
1525                 INIT_LIST_HEAD(&ceu_sd->asd.list);
1526
1527                 ceu_sd->mbus_flags      = async_sd->flags;
1528                 ceu_sd->asd.match_type  = V4L2_ASYNC_MATCH_I2C;
1529                 ceu_sd->asd.match.i2c.adapter_id = async_sd->i2c_adapter_id;
1530                 ceu_sd->asd.match.i2c.address = async_sd->i2c_address;
1531
1532                 ceudev->asds[i] = &ceu_sd->asd;
1533         }
1534
1535         return pdata->num_subdevs;
1536 }
1537
1538 /*
1539  * ceu_parse_dt() - Initialize async_subdevs parsing device tree graph.
1540  */
1541 static int ceu_parse_dt(struct ceu_device *ceudev)
1542 {
1543         struct device_node *of = ceudev->dev->of_node;
1544         struct v4l2_fwnode_endpoint fw_ep;
1545         struct ceu_subdev *ceu_sd;
1546         struct device_node *ep;
1547         unsigned int i;
1548         int num_ep;
1549         int ret;
1550
1551         num_ep = of_graph_get_endpoint_count(of);
1552         if (!num_ep)
1553                 return -ENODEV;
1554
1555         ret = ceu_init_async_subdevs(ceudev, num_ep);
1556         if (ret)
1557                 return ret;
1558
1559         for (i = 0; i < num_ep; i++) {
1560                 ep = of_graph_get_endpoint_by_regs(of, 0, i);
1561                 if (!ep) {
1562                         dev_err(ceudev->dev,
1563                                 "No subdevice connected on endpoint %u.\n", i);
1564                         ret = -ENODEV;
1565                         goto error_put_node;
1566                 }
1567
1568                 ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(ep), &fw_ep);
1569                 if (ret) {
1570                         dev_err(ceudev->dev,
1571                                 "Unable to parse endpoint #%u.\n", i);
1572                         goto error_put_node;
1573                 }
1574
1575                 if (fw_ep.bus_type != V4L2_MBUS_PARALLEL) {
1576                         dev_err(ceudev->dev,
1577                                 "Only parallel input supported.\n");
1578                         ret = -EINVAL;
1579                         goto error_put_node;
1580                 }
1581
1582                 /* Setup the ceu subdevice and the async subdevice. */
1583                 ceu_sd = &ceudev->subdevs[i];
1584                 INIT_LIST_HEAD(&ceu_sd->asd.list);
1585
1586                 ceu_sd->mbus_flags = fw_ep.bus.parallel.flags;
1587                 ceu_sd->asd.match_type = V4L2_ASYNC_MATCH_FWNODE;
1588                 ceu_sd->asd.match.fwnode =
1589                         fwnode_graph_get_remote_port_parent(
1590                                         of_fwnode_handle(ep));
1591
1592                 ceudev->asds[i] = &ceu_sd->asd;
1593                 of_node_put(ep);
1594         }
1595
1596         return num_ep;
1597
1598 error_put_node:
1599         of_node_put(ep);
1600         return ret;
1601 }
1602
1603 /*
1604  * struct ceu_data - Platform specific CEU data
1605  * @irq_mask: CETCR mask with all interrupt sources enabled. The mask differs
1606  *            between SH4 and RZ platforms.
1607  */
1608 struct ceu_data {
1609         u32 irq_mask;
1610 };
1611
1612 static const struct ceu_data ceu_data_rz = {
1613         .irq_mask = CEU_CETCR_ALL_IRQS_RZ,
1614 };
1615
1616 static const struct ceu_data ceu_data_sh4 = {
1617         .irq_mask = CEU_CETCR_ALL_IRQS_SH4,
1618 };
1619
1620 #if IS_ENABLED(CONFIG_OF)
1621 static const struct of_device_id ceu_of_match[] = {
1622         { .compatible = "renesas,r7s72100-ceu", .data = &ceu_data_rz },
1623         { .compatible = "renesas,r8a7740-ceu", .data = &ceu_data_rz },
1624         { }
1625 };
1626 MODULE_DEVICE_TABLE(of, ceu_of_match);
1627 #endif
1628
1629 static int ceu_probe(struct platform_device *pdev)
1630 {
1631         struct device *dev = &pdev->dev;
1632         const struct ceu_data *ceu_data;
1633         struct ceu_device *ceudev;
1634         struct resource *res;
1635         unsigned int irq;
1636         int num_subdevs;
1637         int ret;
1638
1639         ceudev = kzalloc(sizeof(*ceudev), GFP_KERNEL);
1640         if (!ceudev)
1641                 return -ENOMEM;
1642
1643         platform_set_drvdata(pdev, ceudev);
1644         ceudev->dev = dev;
1645
1646         INIT_LIST_HEAD(&ceudev->capture);
1647         spin_lock_init(&ceudev->lock);
1648         mutex_init(&ceudev->mlock);
1649
1650         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1651         ceudev->base = devm_ioremap_resource(dev, res);
1652         if (IS_ERR(ceudev->base)) {
1653                 ret = PTR_ERR(ceudev->base);
1654                 goto error_free_ceudev;
1655         }
1656
1657         ret = platform_get_irq(pdev, 0);
1658         if (ret < 0) {
1659                 dev_err(dev, "Failed to get irq: %d\n", ret);
1660                 goto error_free_ceudev;
1661         }
1662         irq = ret;
1663
1664         ret = devm_request_irq(dev, irq, ceu_irq,
1665                                0, dev_name(dev), ceudev);
1666         if (ret) {
1667                 dev_err(&pdev->dev, "Unable to request CEU interrupt.\n");
1668                 goto error_free_ceudev;
1669         }
1670
1671         pm_runtime_enable(dev);
1672
1673         ret = v4l2_device_register(dev, &ceudev->v4l2_dev);
1674         if (ret)
1675                 goto error_pm_disable;
1676
1677         if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
1678                 ceu_data = of_match_device(ceu_of_match, dev)->data;
1679                 num_subdevs = ceu_parse_dt(ceudev);
1680         } else if (dev->platform_data) {
1681                 /* Assume SH4 if booting with platform data. */
1682                 ceu_data = &ceu_data_sh4;
1683                 num_subdevs = ceu_parse_platform_data(ceudev,
1684                                                       dev->platform_data);
1685         } else {
1686                 num_subdevs = -EINVAL;
1687         }
1688
1689         if (num_subdevs < 0) {
1690                 ret = num_subdevs;
1691                 goto error_v4l2_unregister;
1692         }
1693         ceudev->irq_mask = ceu_data->irq_mask;
1694
1695         ceudev->notifier.v4l2_dev       = &ceudev->v4l2_dev;
1696         ceudev->notifier.subdevs        = ceudev->asds;
1697         ceudev->notifier.num_subdevs    = num_subdevs;
1698         ceudev->notifier.ops            = &ceu_notify_ops;
1699         ret = v4l2_async_notifier_register(&ceudev->v4l2_dev,
1700                                            &ceudev->notifier);
1701         if (ret)
1702                 goto error_v4l2_unregister;
1703
1704         dev_info(dev, "Renesas Capture Engine Unit %s\n", dev_name(dev));
1705
1706         return 0;
1707
1708 error_v4l2_unregister:
1709         v4l2_device_unregister(&ceudev->v4l2_dev);
1710 error_pm_disable:
1711         pm_runtime_disable(dev);
1712 error_free_ceudev:
1713         kfree(ceudev);
1714
1715         return ret;
1716 }
1717
1718 static int ceu_remove(struct platform_device *pdev)
1719 {
1720         struct ceu_device *ceudev = platform_get_drvdata(pdev);
1721
1722         pm_runtime_disable(ceudev->dev);
1723
1724         v4l2_async_notifier_unregister(&ceudev->notifier);
1725
1726         v4l2_device_unregister(&ceudev->v4l2_dev);
1727
1728         video_unregister_device(&ceudev->vdev);
1729
1730         return 0;
1731 }
1732
1733 static const struct dev_pm_ops ceu_pm_ops = {
1734         SET_RUNTIME_PM_OPS(ceu_runtime_suspend,
1735                            ceu_runtime_resume,
1736                            NULL)
1737 };
1738
1739 static struct platform_driver ceu_driver = {
1740         .driver         = {
1741                 .name   = DRIVER_NAME,
1742                 .pm     = &ceu_pm_ops,
1743                 .of_match_table = of_match_ptr(ceu_of_match),
1744         },
1745         .probe          = ceu_probe,
1746         .remove         = ceu_remove,
1747 };
1748
1749 module_platform_driver(ceu_driver);
1750
1751 MODULE_DESCRIPTION("Renesas CEU camera driver");
1752 MODULE_AUTHOR("Jacopo Mondi <jacopo+renesas@jmondi.org>");
1753 MODULE_LICENSE("GPL v2");