]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/media/platform/stm32/stm32-dcmi.c
Merge tag 'v5.4-rc3' into spi-5.4
[linux.git] / drivers / media / platform / stm32 / stm32-dcmi.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Driver for STM32 Digital Camera Memory Interface
4  *
5  * Copyright (C) STMicroelectronics SA 2017
6  * Authors: Yannick Fertre <yannick.fertre@st.com>
7  *          Hugues Fruchet <hugues.fruchet@st.com>
8  *          for STMicroelectronics.
9  *
10  * This driver is based on atmel_isi.c
11  *
12  */
13
14 #include <linux/clk.h>
15 #include <linux/completion.h>
16 #include <linux/delay.h>
17 #include <linux/dmaengine.h>
18 #include <linux/init.h>
19 #include <linux/interrupt.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/of.h>
23 #include <linux/of_device.h>
24 #include <linux/of_graph.h>
25 #include <linux/pinctrl/consumer.h>
26 #include <linux/platform_device.h>
27 #include <linux/pm_runtime.h>
28 #include <linux/reset.h>
29 #include <linux/videodev2.h>
30
31 #include <media/v4l2-ctrls.h>
32 #include <media/v4l2-dev.h>
33 #include <media/v4l2-device.h>
34 #include <media/v4l2-event.h>
35 #include <media/v4l2-fwnode.h>
36 #include <media/v4l2-image-sizes.h>
37 #include <media/v4l2-ioctl.h>
38 #include <media/v4l2-rect.h>
39 #include <media/videobuf2-dma-contig.h>
40
41 #define DRV_NAME "stm32-dcmi"
42
43 /* Registers offset for DCMI */
44 #define DCMI_CR         0x00 /* Control Register */
45 #define DCMI_SR         0x04 /* Status Register */
46 #define DCMI_RIS        0x08 /* Raw Interrupt Status register */
47 #define DCMI_IER        0x0C /* Interrupt Enable Register */
48 #define DCMI_MIS        0x10 /* Masked Interrupt Status register */
49 #define DCMI_ICR        0x14 /* Interrupt Clear Register */
50 #define DCMI_ESCR       0x18 /* Embedded Synchronization Code Register */
51 #define DCMI_ESUR       0x1C /* Embedded Synchronization Unmask Register */
52 #define DCMI_CWSTRT     0x20 /* Crop Window STaRT */
53 #define DCMI_CWSIZE     0x24 /* Crop Window SIZE */
54 #define DCMI_DR         0x28 /* Data Register */
55 #define DCMI_IDR        0x2C /* IDentifier Register */
56
57 /* Bits definition for control register (DCMI_CR) */
58 #define CR_CAPTURE      BIT(0)
59 #define CR_CM           BIT(1)
60 #define CR_CROP         BIT(2)
61 #define CR_JPEG         BIT(3)
62 #define CR_ESS          BIT(4)
63 #define CR_PCKPOL       BIT(5)
64 #define CR_HSPOL        BIT(6)
65 #define CR_VSPOL        BIT(7)
66 #define CR_FCRC_0       BIT(8)
67 #define CR_FCRC_1       BIT(9)
68 #define CR_EDM_0        BIT(10)
69 #define CR_EDM_1        BIT(11)
70 #define CR_ENABLE       BIT(14)
71
72 /* Bits definition for status register (DCMI_SR) */
73 #define SR_HSYNC        BIT(0)
74 #define SR_VSYNC        BIT(1)
75 #define SR_FNE          BIT(2)
76
77 /*
78  * Bits definition for interrupt registers
79  * (DCMI_RIS, DCMI_IER, DCMI_MIS, DCMI_ICR)
80  */
81 #define IT_FRAME        BIT(0)
82 #define IT_OVR          BIT(1)
83 #define IT_ERR          BIT(2)
84 #define IT_VSYNC        BIT(3)
85 #define IT_LINE         BIT(4)
86
87 enum state {
88         STOPPED = 0,
89         WAIT_FOR_BUFFER,
90         RUNNING,
91 };
92
93 #define MIN_WIDTH       16U
94 #define MAX_WIDTH       2592U
95 #define MIN_HEIGHT      16U
96 #define MAX_HEIGHT      2592U
97
98 #define TIMEOUT_MS      1000
99
100 #define OVERRUN_ERROR_THRESHOLD 3
101
102 struct dcmi_graph_entity {
103         struct v4l2_async_subdev asd;
104
105         struct device_node *remote_node;
106         struct v4l2_subdev *source;
107 };
108
109 struct dcmi_format {
110         u32     fourcc;
111         u32     mbus_code;
112         u8      bpp;
113 };
114
115 struct dcmi_framesize {
116         u32     width;
117         u32     height;
118 };
119
120 struct dcmi_buf {
121         struct vb2_v4l2_buffer  vb;
122         bool                    prepared;
123         dma_addr_t              paddr;
124         size_t                  size;
125         struct list_head        list;
126 };
127
128 struct stm32_dcmi {
129         /* Protects the access of variables shared within the interrupt */
130         spinlock_t                      irqlock;
131         struct device                   *dev;
132         void __iomem                    *regs;
133         struct resource                 *res;
134         struct reset_control            *rstc;
135         int                             sequence;
136         struct list_head                buffers;
137         struct dcmi_buf                 *active;
138
139         struct v4l2_device              v4l2_dev;
140         struct video_device             *vdev;
141         struct v4l2_async_notifier      notifier;
142         struct dcmi_graph_entity        entity;
143         struct v4l2_format              fmt;
144         struct v4l2_rect                crop;
145         bool                            do_crop;
146
147         const struct dcmi_format        **sd_formats;
148         unsigned int                    num_of_sd_formats;
149         const struct dcmi_format        *sd_format;
150         struct dcmi_framesize           *sd_framesizes;
151         unsigned int                    num_of_sd_framesizes;
152         struct dcmi_framesize           sd_framesize;
153         struct v4l2_rect                sd_bounds;
154
155         /* Protect this data structure */
156         struct mutex                    lock;
157         struct vb2_queue                queue;
158
159         struct v4l2_fwnode_bus_parallel bus;
160         struct completion               complete;
161         struct clk                      *mclk;
162         enum state                      state;
163         struct dma_chan                 *dma_chan;
164         dma_cookie_t                    dma_cookie;
165         u32                             misr;
166         int                             errors_count;
167         int                             overrun_count;
168         int                             buffers_count;
169
170         /* Ensure DMA operations atomicity */
171         struct mutex                    dma_lock;
172
173         struct media_device             mdev;
174         struct media_pad                vid_cap_pad;
175         struct media_pipeline           pipeline;
176 };
177
178 static inline struct stm32_dcmi *notifier_to_dcmi(struct v4l2_async_notifier *n)
179 {
180         return container_of(n, struct stm32_dcmi, notifier);
181 }
182
183 static inline u32 reg_read(void __iomem *base, u32 reg)
184 {
185         return readl_relaxed(base + reg);
186 }
187
188 static inline void reg_write(void __iomem *base, u32 reg, u32 val)
189 {
190         writel_relaxed(val, base + reg);
191 }
192
193 static inline void reg_set(void __iomem *base, u32 reg, u32 mask)
194 {
195         reg_write(base, reg, reg_read(base, reg) | mask);
196 }
197
198 static inline void reg_clear(void __iomem *base, u32 reg, u32 mask)
199 {
200         reg_write(base, reg, reg_read(base, reg) & ~mask);
201 }
202
203 static int dcmi_start_capture(struct stm32_dcmi *dcmi, struct dcmi_buf *buf);
204
205 static void dcmi_buffer_done(struct stm32_dcmi *dcmi,
206                              struct dcmi_buf *buf,
207                              size_t bytesused,
208                              int err)
209 {
210         struct vb2_v4l2_buffer *vbuf;
211
212         if (!buf)
213                 return;
214
215         list_del_init(&buf->list);
216
217         vbuf = &buf->vb;
218
219         vbuf->sequence = dcmi->sequence++;
220         vbuf->field = V4L2_FIELD_NONE;
221         vbuf->vb2_buf.timestamp = ktime_get_ns();
222         vb2_set_plane_payload(&vbuf->vb2_buf, 0, bytesused);
223         vb2_buffer_done(&vbuf->vb2_buf,
224                         err ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
225         dev_dbg(dcmi->dev, "buffer[%d] done seq=%d, bytesused=%zu\n",
226                 vbuf->vb2_buf.index, vbuf->sequence, bytesused);
227
228         dcmi->buffers_count++;
229         dcmi->active = NULL;
230 }
231
232 static int dcmi_restart_capture(struct stm32_dcmi *dcmi)
233 {
234         struct dcmi_buf *buf;
235
236         spin_lock_irq(&dcmi->irqlock);
237
238         if (dcmi->state != RUNNING) {
239                 spin_unlock_irq(&dcmi->irqlock);
240                 return -EINVAL;
241         }
242
243         /* Restart a new DMA transfer with next buffer */
244         if (list_empty(&dcmi->buffers)) {
245                 dev_dbg(dcmi->dev, "Capture restart is deferred to next buffer queueing\n");
246                 dcmi->state = WAIT_FOR_BUFFER;
247                 spin_unlock_irq(&dcmi->irqlock);
248                 return 0;
249         }
250         buf = list_entry(dcmi->buffers.next, struct dcmi_buf, list);
251         dcmi->active = buf;
252
253         spin_unlock_irq(&dcmi->irqlock);
254
255         return dcmi_start_capture(dcmi, buf);
256 }
257
258 static void dcmi_dma_callback(void *param)
259 {
260         struct stm32_dcmi *dcmi = (struct stm32_dcmi *)param;
261         struct dma_tx_state state;
262         enum dma_status status;
263         struct dcmi_buf *buf = dcmi->active;
264
265         spin_lock_irq(&dcmi->irqlock);
266
267         /* Check DMA status */
268         status = dmaengine_tx_status(dcmi->dma_chan, dcmi->dma_cookie, &state);
269
270         switch (status) {
271         case DMA_IN_PROGRESS:
272                 dev_dbg(dcmi->dev, "%s: Received DMA_IN_PROGRESS\n", __func__);
273                 break;
274         case DMA_PAUSED:
275                 dev_err(dcmi->dev, "%s: Received DMA_PAUSED\n", __func__);
276                 break;
277         case DMA_ERROR:
278                 dev_err(dcmi->dev, "%s: Received DMA_ERROR\n", __func__);
279
280                 /* Return buffer to V4L2 in error state */
281                 dcmi_buffer_done(dcmi, buf, 0, -EIO);
282                 break;
283         case DMA_COMPLETE:
284                 dev_dbg(dcmi->dev, "%s: Received DMA_COMPLETE\n", __func__);
285
286                 /* Return buffer to V4L2 */
287                 dcmi_buffer_done(dcmi, buf, buf->size, 0);
288
289                 spin_unlock_irq(&dcmi->irqlock);
290
291                 /* Restart capture */
292                 if (dcmi_restart_capture(dcmi))
293                         dev_err(dcmi->dev, "%s: Cannot restart capture on DMA complete\n",
294                                 __func__);
295                 return;
296         default:
297                 dev_err(dcmi->dev, "%s: Received unknown status\n", __func__);
298                 break;
299         }
300
301         spin_unlock_irq(&dcmi->irqlock);
302 }
303
304 static int dcmi_start_dma(struct stm32_dcmi *dcmi,
305                           struct dcmi_buf *buf)
306 {
307         struct dma_async_tx_descriptor *desc = NULL;
308         struct dma_slave_config config;
309         int ret;
310
311         memset(&config, 0, sizeof(config));
312
313         config.src_addr = (dma_addr_t)dcmi->res->start + DCMI_DR;
314         config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
315         config.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
316         config.dst_maxburst = 4;
317
318         /* Configure DMA channel */
319         ret = dmaengine_slave_config(dcmi->dma_chan, &config);
320         if (ret < 0) {
321                 dev_err(dcmi->dev, "%s: DMA channel config failed (%d)\n",
322                         __func__, ret);
323                 return ret;
324         }
325
326         /*
327          * Avoid call of dmaengine_terminate_all() between
328          * dmaengine_prep_slave_single() and dmaengine_submit()
329          * by locking the whole DMA submission sequence
330          */
331         mutex_lock(&dcmi->dma_lock);
332
333         /* Prepare a DMA transaction */
334         desc = dmaengine_prep_slave_single(dcmi->dma_chan, buf->paddr,
335                                            buf->size,
336                                            DMA_DEV_TO_MEM,
337                                            DMA_PREP_INTERRUPT);
338         if (!desc) {
339                 dev_err(dcmi->dev, "%s: DMA dmaengine_prep_slave_single failed for buffer phy=%pad size=%zu\n",
340                         __func__, &buf->paddr, buf->size);
341                 mutex_unlock(&dcmi->dma_lock);
342                 return -EINVAL;
343         }
344
345         /* Set completion callback routine for notification */
346         desc->callback = dcmi_dma_callback;
347         desc->callback_param = dcmi;
348
349         /* Push current DMA transaction in the pending queue */
350         dcmi->dma_cookie = dmaengine_submit(desc);
351         if (dma_submit_error(dcmi->dma_cookie)) {
352                 dev_err(dcmi->dev, "%s: DMA submission failed\n", __func__);
353                 mutex_unlock(&dcmi->dma_lock);
354                 return -ENXIO;
355         }
356
357         mutex_unlock(&dcmi->dma_lock);
358
359         dma_async_issue_pending(dcmi->dma_chan);
360
361         return 0;
362 }
363
364 static int dcmi_start_capture(struct stm32_dcmi *dcmi, struct dcmi_buf *buf)
365 {
366         int ret;
367
368         if (!buf)
369                 return -EINVAL;
370
371         ret = dcmi_start_dma(dcmi, buf);
372         if (ret) {
373                 dcmi->errors_count++;
374                 return ret;
375         }
376
377         /* Enable capture */
378         reg_set(dcmi->regs, DCMI_CR, CR_CAPTURE);
379
380         return 0;
381 }
382
383 static void dcmi_set_crop(struct stm32_dcmi *dcmi)
384 {
385         u32 size, start;
386
387         /* Crop resolution */
388         size = ((dcmi->crop.height - 1) << 16) |
389                 ((dcmi->crop.width << 1) - 1);
390         reg_write(dcmi->regs, DCMI_CWSIZE, size);
391
392         /* Crop start point */
393         start = ((dcmi->crop.top) << 16) |
394                  ((dcmi->crop.left << 1));
395         reg_write(dcmi->regs, DCMI_CWSTRT, start);
396
397         dev_dbg(dcmi->dev, "Cropping to %ux%u@%u:%u\n",
398                 dcmi->crop.width, dcmi->crop.height,
399                 dcmi->crop.left, dcmi->crop.top);
400
401         /* Enable crop */
402         reg_set(dcmi->regs, DCMI_CR, CR_CROP);
403 }
404
405 static void dcmi_process_jpeg(struct stm32_dcmi *dcmi)
406 {
407         struct dma_tx_state state;
408         enum dma_status status;
409         struct dcmi_buf *buf = dcmi->active;
410
411         if (!buf)
412                 return;
413
414         /*
415          * Because of variable JPEG buffer size sent by sensor,
416          * DMA transfer never completes due to transfer size never reached.
417          * In order to ensure that all the JPEG data are transferred
418          * in active buffer memory, DMA is drained.
419          * Then DMA tx status gives the amount of data transferred
420          * to memory, which is then returned to V4L2 through the active
421          * buffer payload.
422          */
423
424         /* Drain DMA */
425         dmaengine_synchronize(dcmi->dma_chan);
426
427         /* Get DMA residue to get JPEG size */
428         status = dmaengine_tx_status(dcmi->dma_chan, dcmi->dma_cookie, &state);
429         if (status != DMA_ERROR && state.residue < buf->size) {
430                 /* Return JPEG buffer to V4L2 with received JPEG buffer size */
431                 dcmi_buffer_done(dcmi, buf, buf->size - state.residue, 0);
432         } else {
433                 dcmi->errors_count++;
434                 dev_err(dcmi->dev, "%s: Cannot get JPEG size from DMA\n",
435                         __func__);
436                 /* Return JPEG buffer to V4L2 in ERROR state */
437                 dcmi_buffer_done(dcmi, buf, 0, -EIO);
438         }
439
440         /* Abort DMA operation */
441         dmaengine_terminate_all(dcmi->dma_chan);
442
443         /* Restart capture */
444         if (dcmi_restart_capture(dcmi))
445                 dev_err(dcmi->dev, "%s: Cannot restart capture on JPEG received\n",
446                         __func__);
447 }
448
449 static irqreturn_t dcmi_irq_thread(int irq, void *arg)
450 {
451         struct stm32_dcmi *dcmi = arg;
452
453         spin_lock_irq(&dcmi->irqlock);
454
455         if (dcmi->misr & IT_OVR) {
456                 dcmi->overrun_count++;
457                 if (dcmi->overrun_count > OVERRUN_ERROR_THRESHOLD)
458                         dcmi->errors_count++;
459         }
460         if (dcmi->misr & IT_ERR)
461                 dcmi->errors_count++;
462
463         if (dcmi->sd_format->fourcc == V4L2_PIX_FMT_JPEG &&
464             dcmi->misr & IT_FRAME) {
465                 /* JPEG received */
466                 spin_unlock_irq(&dcmi->irqlock);
467                 dcmi_process_jpeg(dcmi);
468                 return IRQ_HANDLED;
469         }
470
471         spin_unlock_irq(&dcmi->irqlock);
472         return IRQ_HANDLED;
473 }
474
475 static irqreturn_t dcmi_irq_callback(int irq, void *arg)
476 {
477         struct stm32_dcmi *dcmi = arg;
478         unsigned long flags;
479
480         spin_lock_irqsave(&dcmi->irqlock, flags);
481
482         dcmi->misr = reg_read(dcmi->regs, DCMI_MIS);
483
484         /* Clear interrupt */
485         reg_set(dcmi->regs, DCMI_ICR, IT_FRAME | IT_OVR | IT_ERR);
486
487         spin_unlock_irqrestore(&dcmi->irqlock, flags);
488
489         return IRQ_WAKE_THREAD;
490 }
491
492 static int dcmi_queue_setup(struct vb2_queue *vq,
493                             unsigned int *nbuffers,
494                             unsigned int *nplanes,
495                             unsigned int sizes[],
496                             struct device *alloc_devs[])
497 {
498         struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
499         unsigned int size;
500
501         size = dcmi->fmt.fmt.pix.sizeimage;
502
503         /* Make sure the image size is large enough */
504         if (*nplanes)
505                 return sizes[0] < size ? -EINVAL : 0;
506
507         *nplanes = 1;
508         sizes[0] = size;
509
510         dev_dbg(dcmi->dev, "Setup queue, count=%d, size=%d\n",
511                 *nbuffers, size);
512
513         return 0;
514 }
515
516 static int dcmi_buf_init(struct vb2_buffer *vb)
517 {
518         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
519         struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
520
521         INIT_LIST_HEAD(&buf->list);
522
523         return 0;
524 }
525
526 static int dcmi_buf_prepare(struct vb2_buffer *vb)
527 {
528         struct stm32_dcmi *dcmi =  vb2_get_drv_priv(vb->vb2_queue);
529         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
530         struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
531         unsigned long size;
532
533         size = dcmi->fmt.fmt.pix.sizeimage;
534
535         if (vb2_plane_size(vb, 0) < size) {
536                 dev_err(dcmi->dev, "%s data will not fit into plane (%lu < %lu)\n",
537                         __func__, vb2_plane_size(vb, 0), size);
538                 return -EINVAL;
539         }
540
541         vb2_set_plane_payload(vb, 0, size);
542
543         if (!buf->prepared) {
544                 /* Get memory addresses */
545                 buf->paddr =
546                         vb2_dma_contig_plane_dma_addr(&buf->vb.vb2_buf, 0);
547                 buf->size = vb2_plane_size(&buf->vb.vb2_buf, 0);
548                 buf->prepared = true;
549
550                 vb2_set_plane_payload(&buf->vb.vb2_buf, 0, buf->size);
551
552                 dev_dbg(dcmi->dev, "buffer[%d] phy=%pad size=%zu\n",
553                         vb->index, &buf->paddr, buf->size);
554         }
555
556         return 0;
557 }
558
559 static void dcmi_buf_queue(struct vb2_buffer *vb)
560 {
561         struct stm32_dcmi *dcmi =  vb2_get_drv_priv(vb->vb2_queue);
562         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
563         struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
564
565         spin_lock_irq(&dcmi->irqlock);
566
567         /* Enqueue to video buffers list */
568         list_add_tail(&buf->list, &dcmi->buffers);
569
570         if (dcmi->state == WAIT_FOR_BUFFER) {
571                 dcmi->state = RUNNING;
572                 dcmi->active = buf;
573
574                 dev_dbg(dcmi->dev, "Starting capture on buffer[%d] queued\n",
575                         buf->vb.vb2_buf.index);
576
577                 spin_unlock_irq(&dcmi->irqlock);
578                 if (dcmi_start_capture(dcmi, buf))
579                         dev_err(dcmi->dev, "%s: Cannot restart capture on overflow or error\n",
580                                 __func__);
581                 return;
582         }
583
584         spin_unlock_irq(&dcmi->irqlock);
585 }
586
587 static struct media_entity *dcmi_find_source(struct stm32_dcmi *dcmi)
588 {
589         struct media_entity *entity = &dcmi->vdev->entity;
590         struct media_pad *pad;
591
592         /* Walk searching for entity having no sink */
593         while (1) {
594                 pad = &entity->pads[0];
595                 if (!(pad->flags & MEDIA_PAD_FL_SINK))
596                         break;
597
598                 pad = media_entity_remote_pad(pad);
599                 if (!pad || !is_media_entity_v4l2_subdev(pad->entity))
600                         break;
601
602                 entity = pad->entity;
603         }
604
605         return entity;
606 }
607
608 static int dcmi_pipeline_s_fmt(struct stm32_dcmi *dcmi,
609                                struct v4l2_subdev_pad_config *pad_cfg,
610                                struct v4l2_subdev_format *format)
611 {
612         struct media_entity *entity = &dcmi->entity.source->entity;
613         struct v4l2_subdev *subdev;
614         struct media_pad *sink_pad = NULL;
615         struct media_pad *src_pad = NULL;
616         struct media_pad *pad = NULL;
617         struct v4l2_subdev_format fmt = *format;
618         bool found = false;
619         int ret;
620
621         /*
622          * Starting from sensor subdevice, walk within
623          * pipeline and set format on each subdevice
624          */
625         while (1) {
626                 unsigned int i;
627
628                 /* Search if current entity has a source pad */
629                 for (i = 0; i < entity->num_pads; i++) {
630                         pad = &entity->pads[i];
631                         if (pad->flags & MEDIA_PAD_FL_SOURCE) {
632                                 src_pad = pad;
633                                 found = true;
634                                 break;
635                         }
636                 }
637                 if (!found)
638                         break;
639
640                 subdev = media_entity_to_v4l2_subdev(entity);
641
642                 /* Propagate format on sink pad if any, otherwise source pad */
643                 if (sink_pad)
644                         pad = sink_pad;
645
646                 dev_dbg(dcmi->dev, "\"%s\":%d pad format set to 0x%x %ux%u\n",
647                         subdev->name, pad->index, format->format.code,
648                         format->format.width, format->format.height);
649
650                 fmt.pad = pad->index;
651                 ret = v4l2_subdev_call(subdev, pad, set_fmt, pad_cfg, &fmt);
652                 if (ret < 0) {
653                         dev_err(dcmi->dev, "%s: Failed to set format 0x%x %ux%u on \"%s\":%d pad (%d)\n",
654                                 __func__, format->format.code,
655                                 format->format.width, format->format.height,
656                                 subdev->name, pad->index, ret);
657                         return ret;
658                 }
659
660                 if (fmt.format.code != format->format.code ||
661                     fmt.format.width != format->format.width ||
662                     fmt.format.height != format->format.height) {
663                         dev_dbg(dcmi->dev, "\"%s\":%d pad format has been changed to 0x%x %ux%u\n",
664                                 subdev->name, pad->index, fmt.format.code,
665                                 fmt.format.width, fmt.format.height);
666                 }
667
668                 /* Walk to next entity */
669                 sink_pad = media_entity_remote_pad(src_pad);
670                 if (!sink_pad || !is_media_entity_v4l2_subdev(sink_pad->entity))
671                         break;
672
673                 entity = sink_pad->entity;
674         }
675         *format = fmt;
676
677         return 0;
678 }
679
680 static int dcmi_pipeline_s_stream(struct stm32_dcmi *dcmi, int state)
681 {
682         struct media_entity *entity = &dcmi->vdev->entity;
683         struct v4l2_subdev *subdev;
684         struct media_pad *pad;
685         int ret;
686
687         /* Start/stop all entities within pipeline */
688         while (1) {
689                 pad = &entity->pads[0];
690                 if (!(pad->flags & MEDIA_PAD_FL_SINK))
691                         break;
692
693                 pad = media_entity_remote_pad(pad);
694                 if (!pad || !is_media_entity_v4l2_subdev(pad->entity))
695                         break;
696
697                 entity = pad->entity;
698                 subdev = media_entity_to_v4l2_subdev(entity);
699
700                 ret = v4l2_subdev_call(subdev, video, s_stream, state);
701                 if (ret < 0 && ret != -ENOIOCTLCMD) {
702                         dev_err(dcmi->dev, "%s: \"%s\" failed to %s streaming (%d)\n",
703                                 __func__, subdev->name,
704                                 state ? "start" : "stop", ret);
705                         return ret;
706                 }
707
708                 dev_dbg(dcmi->dev, "\"%s\" is %s\n",
709                         subdev->name, state ? "started" : "stopped");
710         }
711
712         return 0;
713 }
714
715 static int dcmi_pipeline_start(struct stm32_dcmi *dcmi)
716 {
717         return dcmi_pipeline_s_stream(dcmi, 1);
718 }
719
720 static void dcmi_pipeline_stop(struct stm32_dcmi *dcmi)
721 {
722         dcmi_pipeline_s_stream(dcmi, 0);
723 }
724
725 static int dcmi_start_streaming(struct vb2_queue *vq, unsigned int count)
726 {
727         struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
728         struct dcmi_buf *buf, *node;
729         u32 val = 0;
730         int ret;
731
732         ret = pm_runtime_get_sync(dcmi->dev);
733         if (ret < 0) {
734                 dev_err(dcmi->dev, "%s: Failed to start streaming, cannot get sync (%d)\n",
735                         __func__, ret);
736                 goto err_release_buffers;
737         }
738
739         ret = media_pipeline_start(&dcmi->vdev->entity, &dcmi->pipeline);
740         if (ret < 0) {
741                 dev_err(dcmi->dev, "%s: Failed to start streaming, media pipeline start error (%d)\n",
742                         __func__, ret);
743                 goto err_pm_put;
744         }
745
746         ret = dcmi_pipeline_start(dcmi);
747         if (ret)
748                 goto err_media_pipeline_stop;
749
750         spin_lock_irq(&dcmi->irqlock);
751
752         /* Set bus width */
753         switch (dcmi->bus.bus_width) {
754         case 14:
755                 val |= CR_EDM_0 | CR_EDM_1;
756                 break;
757         case 12:
758                 val |= CR_EDM_1;
759                 break;
760         case 10:
761                 val |= CR_EDM_0;
762                 break;
763         default:
764                 /* Set bus width to 8 bits by default */
765                 break;
766         }
767
768         /* Set vertical synchronization polarity */
769         if (dcmi->bus.flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH)
770                 val |= CR_VSPOL;
771
772         /* Set horizontal synchronization polarity */
773         if (dcmi->bus.flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH)
774                 val |= CR_HSPOL;
775
776         /* Set pixel clock polarity */
777         if (dcmi->bus.flags & V4L2_MBUS_PCLK_SAMPLE_RISING)
778                 val |= CR_PCKPOL;
779
780         reg_write(dcmi->regs, DCMI_CR, val);
781
782         /* Set crop */
783         if (dcmi->do_crop)
784                 dcmi_set_crop(dcmi);
785
786         /* Enable jpeg capture */
787         if (dcmi->sd_format->fourcc == V4L2_PIX_FMT_JPEG)
788                 reg_set(dcmi->regs, DCMI_CR, CR_CM);/* Snapshot mode */
789
790         /* Enable dcmi */
791         reg_set(dcmi->regs, DCMI_CR, CR_ENABLE);
792
793         dcmi->sequence = 0;
794         dcmi->errors_count = 0;
795         dcmi->overrun_count = 0;
796         dcmi->buffers_count = 0;
797
798         /*
799          * Start transfer if at least one buffer has been queued,
800          * otherwise transfer is deferred at buffer queueing
801          */
802         if (list_empty(&dcmi->buffers)) {
803                 dev_dbg(dcmi->dev, "Start streaming is deferred to next buffer queueing\n");
804                 dcmi->state = WAIT_FOR_BUFFER;
805                 spin_unlock_irq(&dcmi->irqlock);
806                 return 0;
807         }
808
809         buf = list_entry(dcmi->buffers.next, struct dcmi_buf, list);
810         dcmi->active = buf;
811
812         dcmi->state = RUNNING;
813
814         dev_dbg(dcmi->dev, "Start streaming, starting capture\n");
815
816         spin_unlock_irq(&dcmi->irqlock);
817         ret = dcmi_start_capture(dcmi, buf);
818         if (ret) {
819                 dev_err(dcmi->dev, "%s: Start streaming failed, cannot start capture\n",
820                         __func__);
821                 goto err_pipeline_stop;
822         }
823
824         /* Enable interruptions */
825         if (dcmi->sd_format->fourcc == V4L2_PIX_FMT_JPEG)
826                 reg_set(dcmi->regs, DCMI_IER, IT_FRAME | IT_OVR | IT_ERR);
827         else
828                 reg_set(dcmi->regs, DCMI_IER, IT_OVR | IT_ERR);
829
830         return 0;
831
832 err_pipeline_stop:
833         dcmi_pipeline_stop(dcmi);
834
835 err_media_pipeline_stop:
836         media_pipeline_stop(&dcmi->vdev->entity);
837
838 err_pm_put:
839         pm_runtime_put(dcmi->dev);
840
841 err_release_buffers:
842         spin_lock_irq(&dcmi->irqlock);
843         /*
844          * Return all buffers to vb2 in QUEUED state.
845          * This will give ownership back to userspace
846          */
847         list_for_each_entry_safe(buf, node, &dcmi->buffers, list) {
848                 list_del_init(&buf->list);
849                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED);
850         }
851         dcmi->active = NULL;
852         spin_unlock_irq(&dcmi->irqlock);
853
854         return ret;
855 }
856
857 static void dcmi_stop_streaming(struct vb2_queue *vq)
858 {
859         struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
860         struct dcmi_buf *buf, *node;
861
862         dcmi_pipeline_stop(dcmi);
863
864         media_pipeline_stop(&dcmi->vdev->entity);
865
866         spin_lock_irq(&dcmi->irqlock);
867
868         /* Disable interruptions */
869         reg_clear(dcmi->regs, DCMI_IER, IT_FRAME | IT_OVR | IT_ERR);
870
871         /* Disable DCMI */
872         reg_clear(dcmi->regs, DCMI_CR, CR_ENABLE);
873
874         /* Return all queued buffers to vb2 in ERROR state */
875         list_for_each_entry_safe(buf, node, &dcmi->buffers, list) {
876                 list_del_init(&buf->list);
877                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
878         }
879
880         dcmi->active = NULL;
881         dcmi->state = STOPPED;
882
883         spin_unlock_irq(&dcmi->irqlock);
884
885         /* Stop all pending DMA operations */
886         mutex_lock(&dcmi->dma_lock);
887         dmaengine_terminate_all(dcmi->dma_chan);
888         mutex_unlock(&dcmi->dma_lock);
889
890         pm_runtime_put(dcmi->dev);
891
892         if (dcmi->errors_count)
893                 dev_warn(dcmi->dev, "Some errors found while streaming: errors=%d (overrun=%d), buffers=%d\n",
894                          dcmi->errors_count, dcmi->overrun_count,
895                          dcmi->buffers_count);
896         dev_dbg(dcmi->dev, "Stop streaming, errors=%d (overrun=%d), buffers=%d\n",
897                 dcmi->errors_count, dcmi->overrun_count,
898                 dcmi->buffers_count);
899 }
900
901 static const struct vb2_ops dcmi_video_qops = {
902         .queue_setup            = dcmi_queue_setup,
903         .buf_init               = dcmi_buf_init,
904         .buf_prepare            = dcmi_buf_prepare,
905         .buf_queue              = dcmi_buf_queue,
906         .start_streaming        = dcmi_start_streaming,
907         .stop_streaming         = dcmi_stop_streaming,
908         .wait_prepare           = vb2_ops_wait_prepare,
909         .wait_finish            = vb2_ops_wait_finish,
910 };
911
912 static int dcmi_g_fmt_vid_cap(struct file *file, void *priv,
913                               struct v4l2_format *fmt)
914 {
915         struct stm32_dcmi *dcmi = video_drvdata(file);
916
917         *fmt = dcmi->fmt;
918
919         return 0;
920 }
921
922 static const struct dcmi_format *find_format_by_fourcc(struct stm32_dcmi *dcmi,
923                                                        unsigned int fourcc)
924 {
925         unsigned int num_formats = dcmi->num_of_sd_formats;
926         const struct dcmi_format *fmt;
927         unsigned int i;
928
929         for (i = 0; i < num_formats; i++) {
930                 fmt = dcmi->sd_formats[i];
931                 if (fmt->fourcc == fourcc)
932                         return fmt;
933         }
934
935         return NULL;
936 }
937
938 static void __find_outer_frame_size(struct stm32_dcmi *dcmi,
939                                     struct v4l2_pix_format *pix,
940                                     struct dcmi_framesize *framesize)
941 {
942         struct dcmi_framesize *match = NULL;
943         unsigned int i;
944         unsigned int min_err = UINT_MAX;
945
946         for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
947                 struct dcmi_framesize *fsize = &dcmi->sd_framesizes[i];
948                 int w_err = (fsize->width - pix->width);
949                 int h_err = (fsize->height - pix->height);
950                 int err = w_err + h_err;
951
952                 if (w_err >= 0 && h_err >= 0 && err < min_err) {
953                         min_err = err;
954                         match = fsize;
955                 }
956         }
957         if (!match)
958                 match = &dcmi->sd_framesizes[0];
959
960         *framesize = *match;
961 }
962
963 static int dcmi_try_fmt(struct stm32_dcmi *dcmi, struct v4l2_format *f,
964                         const struct dcmi_format **sd_format,
965                         struct dcmi_framesize *sd_framesize)
966 {
967         const struct dcmi_format *sd_fmt;
968         struct dcmi_framesize sd_fsize;
969         struct v4l2_pix_format *pix = &f->fmt.pix;
970         struct v4l2_subdev_pad_config pad_cfg;
971         struct v4l2_subdev_format format = {
972                 .which = V4L2_SUBDEV_FORMAT_TRY,
973         };
974         bool do_crop;
975         int ret;
976
977         sd_fmt = find_format_by_fourcc(dcmi, pix->pixelformat);
978         if (!sd_fmt) {
979                 if (!dcmi->num_of_sd_formats)
980                         return -ENODATA;
981
982                 sd_fmt = dcmi->sd_formats[dcmi->num_of_sd_formats - 1];
983                 pix->pixelformat = sd_fmt->fourcc;
984         }
985
986         /* Limit to hardware capabilities */
987         pix->width = clamp(pix->width, MIN_WIDTH, MAX_WIDTH);
988         pix->height = clamp(pix->height, MIN_HEIGHT, MAX_HEIGHT);
989
990         /* No crop if JPEG is requested */
991         do_crop = dcmi->do_crop && (pix->pixelformat != V4L2_PIX_FMT_JPEG);
992
993         if (do_crop && dcmi->num_of_sd_framesizes) {
994                 struct dcmi_framesize outer_sd_fsize;
995                 /*
996                  * If crop is requested and sensor have discrete frame sizes,
997                  * select the frame size that is just larger than request
998                  */
999                 __find_outer_frame_size(dcmi, pix, &outer_sd_fsize);
1000                 pix->width = outer_sd_fsize.width;
1001                 pix->height = outer_sd_fsize.height;
1002         }
1003
1004         v4l2_fill_mbus_format(&format.format, pix, sd_fmt->mbus_code);
1005         ret = v4l2_subdev_call(dcmi->entity.source, pad, set_fmt,
1006                                &pad_cfg, &format);
1007         if (ret < 0)
1008                 return ret;
1009
1010         /* Update pix regarding to what sensor can do */
1011         v4l2_fill_pix_format(pix, &format.format);
1012
1013         /* Save resolution that sensor can actually do */
1014         sd_fsize.width = pix->width;
1015         sd_fsize.height = pix->height;
1016
1017         if (do_crop) {
1018                 struct v4l2_rect c = dcmi->crop;
1019                 struct v4l2_rect max_rect;
1020
1021                 /*
1022                  * Adjust crop by making the intersection between
1023                  * format resolution request and crop request
1024                  */
1025                 max_rect.top = 0;
1026                 max_rect.left = 0;
1027                 max_rect.width = pix->width;
1028                 max_rect.height = pix->height;
1029                 v4l2_rect_map_inside(&c, &max_rect);
1030                 c.top  = clamp_t(s32, c.top, 0, pix->height - c.height);
1031                 c.left = clamp_t(s32, c.left, 0, pix->width - c.width);
1032                 dcmi->crop = c;
1033
1034                 /* Adjust format resolution request to crop */
1035                 pix->width = dcmi->crop.width;
1036                 pix->height = dcmi->crop.height;
1037         }
1038
1039         pix->field = V4L2_FIELD_NONE;
1040         pix->bytesperline = pix->width * sd_fmt->bpp;
1041         pix->sizeimage = pix->bytesperline * pix->height;
1042
1043         if (sd_format)
1044                 *sd_format = sd_fmt;
1045         if (sd_framesize)
1046                 *sd_framesize = sd_fsize;
1047
1048         return 0;
1049 }
1050
1051 static int dcmi_set_fmt(struct stm32_dcmi *dcmi, struct v4l2_format *f)
1052 {
1053         struct v4l2_subdev_format format = {
1054                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1055         };
1056         const struct dcmi_format *sd_format;
1057         struct dcmi_framesize sd_framesize;
1058         struct v4l2_mbus_framefmt *mf = &format.format;
1059         struct v4l2_pix_format *pix = &f->fmt.pix;
1060         int ret;
1061
1062         /*
1063          * Try format, fmt.width/height could have been changed
1064          * to match sensor capability or crop request
1065          * sd_format & sd_framesize will contain what subdev
1066          * can do for this request.
1067          */
1068         ret = dcmi_try_fmt(dcmi, f, &sd_format, &sd_framesize);
1069         if (ret)
1070                 return ret;
1071
1072         /* Disable crop if JPEG is requested */
1073         if (pix->pixelformat == V4L2_PIX_FMT_JPEG)
1074                 dcmi->do_crop = false;
1075
1076         /* pix to mbus format */
1077         v4l2_fill_mbus_format(mf, pix,
1078                               sd_format->mbus_code);
1079         mf->width = sd_framesize.width;
1080         mf->height = sd_framesize.height;
1081
1082         ret = dcmi_pipeline_s_fmt(dcmi, NULL, &format);
1083         if (ret < 0)
1084                 return ret;
1085
1086         dev_dbg(dcmi->dev, "Sensor format set to 0x%x %ux%u\n",
1087                 mf->code, mf->width, mf->height);
1088         dev_dbg(dcmi->dev, "Buffer format set to %4.4s %ux%u\n",
1089                 (char *)&pix->pixelformat,
1090                 pix->width, pix->height);
1091
1092         dcmi->fmt = *f;
1093         dcmi->sd_format = sd_format;
1094         dcmi->sd_framesize = sd_framesize;
1095
1096         return 0;
1097 }
1098
1099 static int dcmi_s_fmt_vid_cap(struct file *file, void *priv,
1100                               struct v4l2_format *f)
1101 {
1102         struct stm32_dcmi *dcmi = video_drvdata(file);
1103
1104         if (vb2_is_streaming(&dcmi->queue))
1105                 return -EBUSY;
1106
1107         return dcmi_set_fmt(dcmi, f);
1108 }
1109
1110 static int dcmi_try_fmt_vid_cap(struct file *file, void *priv,
1111                                 struct v4l2_format *f)
1112 {
1113         struct stm32_dcmi *dcmi = video_drvdata(file);
1114
1115         return dcmi_try_fmt(dcmi, f, NULL, NULL);
1116 }
1117
1118 static int dcmi_enum_fmt_vid_cap(struct file *file, void  *priv,
1119                                  struct v4l2_fmtdesc *f)
1120 {
1121         struct stm32_dcmi *dcmi = video_drvdata(file);
1122
1123         if (f->index >= dcmi->num_of_sd_formats)
1124                 return -EINVAL;
1125
1126         f->pixelformat = dcmi->sd_formats[f->index]->fourcc;
1127         return 0;
1128 }
1129
1130 static int dcmi_get_sensor_format(struct stm32_dcmi *dcmi,
1131                                   struct v4l2_pix_format *pix)
1132 {
1133         struct v4l2_subdev_format fmt = {
1134                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1135         };
1136         int ret;
1137
1138         ret = v4l2_subdev_call(dcmi->entity.source, pad, get_fmt, NULL, &fmt);
1139         if (ret)
1140                 return ret;
1141
1142         v4l2_fill_pix_format(pix, &fmt.format);
1143
1144         return 0;
1145 }
1146
1147 static int dcmi_set_sensor_format(struct stm32_dcmi *dcmi,
1148                                   struct v4l2_pix_format *pix)
1149 {
1150         const struct dcmi_format *sd_fmt;
1151         struct v4l2_subdev_format format = {
1152                 .which = V4L2_SUBDEV_FORMAT_TRY,
1153         };
1154         struct v4l2_subdev_pad_config pad_cfg;
1155         int ret;
1156
1157         sd_fmt = find_format_by_fourcc(dcmi, pix->pixelformat);
1158         if (!sd_fmt) {
1159                 if (!dcmi->num_of_sd_formats)
1160                         return -ENODATA;
1161
1162                 sd_fmt = dcmi->sd_formats[dcmi->num_of_sd_formats - 1];
1163                 pix->pixelformat = sd_fmt->fourcc;
1164         }
1165
1166         v4l2_fill_mbus_format(&format.format, pix, sd_fmt->mbus_code);
1167         ret = v4l2_subdev_call(dcmi->entity.source, pad, set_fmt,
1168                                &pad_cfg, &format);
1169         if (ret < 0)
1170                 return ret;
1171
1172         return 0;
1173 }
1174
1175 static int dcmi_get_sensor_bounds(struct stm32_dcmi *dcmi,
1176                                   struct v4l2_rect *r)
1177 {
1178         struct v4l2_subdev_selection bounds = {
1179                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1180                 .target = V4L2_SEL_TGT_CROP_BOUNDS,
1181         };
1182         unsigned int max_width, max_height, max_pixsize;
1183         struct v4l2_pix_format pix;
1184         unsigned int i;
1185         int ret;
1186
1187         /*
1188          * Get sensor bounds first
1189          */
1190         ret = v4l2_subdev_call(dcmi->entity.source, pad, get_selection,
1191                                NULL, &bounds);
1192         if (!ret)
1193                 *r = bounds.r;
1194         if (ret != -ENOIOCTLCMD)
1195                 return ret;
1196
1197         /*
1198          * If selection is not implemented,
1199          * fallback by enumerating sensor frame sizes
1200          * and take the largest one
1201          */
1202         max_width = 0;
1203         max_height = 0;
1204         max_pixsize = 0;
1205         for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
1206                 struct dcmi_framesize *fsize = &dcmi->sd_framesizes[i];
1207                 unsigned int pixsize = fsize->width * fsize->height;
1208
1209                 if (pixsize > max_pixsize) {
1210                         max_pixsize = pixsize;
1211                         max_width = fsize->width;
1212                         max_height = fsize->height;
1213                 }
1214         }
1215         if (max_pixsize > 0) {
1216                 r->top = 0;
1217                 r->left = 0;
1218                 r->width = max_width;
1219                 r->height = max_height;
1220                 return 0;
1221         }
1222
1223         /*
1224          * If frame sizes enumeration is not implemented,
1225          * fallback by getting current sensor frame size
1226          */
1227         ret = dcmi_get_sensor_format(dcmi, &pix);
1228         if (ret)
1229                 return ret;
1230
1231         r->top = 0;
1232         r->left = 0;
1233         r->width = pix.width;
1234         r->height = pix.height;
1235
1236         return 0;
1237 }
1238
1239 static int dcmi_g_selection(struct file *file, void *fh,
1240                             struct v4l2_selection *s)
1241 {
1242         struct stm32_dcmi *dcmi = video_drvdata(file);
1243
1244         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1245                 return -EINVAL;
1246
1247         switch (s->target) {
1248         case V4L2_SEL_TGT_CROP_DEFAULT:
1249         case V4L2_SEL_TGT_CROP_BOUNDS:
1250                 s->r = dcmi->sd_bounds;
1251                 return 0;
1252         case V4L2_SEL_TGT_CROP:
1253                 if (dcmi->do_crop) {
1254                         s->r = dcmi->crop;
1255                 } else {
1256                         s->r.top = 0;
1257                         s->r.left = 0;
1258                         s->r.width = dcmi->fmt.fmt.pix.width;
1259                         s->r.height = dcmi->fmt.fmt.pix.height;
1260                 }
1261                 break;
1262         default:
1263                 return -EINVAL;
1264         }
1265
1266         return 0;
1267 }
1268
1269 static int dcmi_s_selection(struct file *file, void *priv,
1270                             struct v4l2_selection *s)
1271 {
1272         struct stm32_dcmi *dcmi = video_drvdata(file);
1273         struct v4l2_rect r = s->r;
1274         struct v4l2_rect max_rect;
1275         struct v4l2_pix_format pix;
1276
1277         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1278             s->target != V4L2_SEL_TGT_CROP)
1279                 return -EINVAL;
1280
1281         /* Reset sensor resolution to max resolution */
1282         pix.pixelformat = dcmi->fmt.fmt.pix.pixelformat;
1283         pix.width = dcmi->sd_bounds.width;
1284         pix.height = dcmi->sd_bounds.height;
1285         dcmi_set_sensor_format(dcmi, &pix);
1286
1287         /*
1288          * Make the intersection between
1289          * sensor resolution
1290          * and crop request
1291          */
1292         max_rect.top = 0;
1293         max_rect.left = 0;
1294         max_rect.width = pix.width;
1295         max_rect.height = pix.height;
1296         v4l2_rect_map_inside(&r, &max_rect);
1297         r.top  = clamp_t(s32, r.top, 0, pix.height - r.height);
1298         r.left = clamp_t(s32, r.left, 0, pix.width - r.width);
1299
1300         if (!(r.top == dcmi->sd_bounds.top &&
1301               r.left == dcmi->sd_bounds.left &&
1302               r.width == dcmi->sd_bounds.width &&
1303               r.height == dcmi->sd_bounds.height)) {
1304                 /* Crop if request is different than sensor resolution */
1305                 dcmi->do_crop = true;
1306                 dcmi->crop = r;
1307                 dev_dbg(dcmi->dev, "s_selection: crop %ux%u@(%u,%u) from %ux%u\n",
1308                         r.width, r.height, r.left, r.top,
1309                         pix.width, pix.height);
1310         } else {
1311                 /* Disable crop */
1312                 dcmi->do_crop = false;
1313                 dev_dbg(dcmi->dev, "s_selection: crop is disabled\n");
1314         }
1315
1316         s->r = r;
1317         return 0;
1318 }
1319
1320 static int dcmi_querycap(struct file *file, void *priv,
1321                          struct v4l2_capability *cap)
1322 {
1323         strscpy(cap->driver, DRV_NAME, sizeof(cap->driver));
1324         strscpy(cap->card, "STM32 Camera Memory Interface",
1325                 sizeof(cap->card));
1326         strscpy(cap->bus_info, "platform:dcmi", sizeof(cap->bus_info));
1327         return 0;
1328 }
1329
1330 static int dcmi_enum_input(struct file *file, void *priv,
1331                            struct v4l2_input *i)
1332 {
1333         if (i->index != 0)
1334                 return -EINVAL;
1335
1336         i->type = V4L2_INPUT_TYPE_CAMERA;
1337         strscpy(i->name, "Camera", sizeof(i->name));
1338         return 0;
1339 }
1340
1341 static int dcmi_g_input(struct file *file, void *priv, unsigned int *i)
1342 {
1343         *i = 0;
1344         return 0;
1345 }
1346
1347 static int dcmi_s_input(struct file *file, void *priv, unsigned int i)
1348 {
1349         if (i > 0)
1350                 return -EINVAL;
1351         return 0;
1352 }
1353
1354 static int dcmi_enum_framesizes(struct file *file, void *fh,
1355                                 struct v4l2_frmsizeenum *fsize)
1356 {
1357         struct stm32_dcmi *dcmi = video_drvdata(file);
1358         const struct dcmi_format *sd_fmt;
1359         struct v4l2_subdev_frame_size_enum fse = {
1360                 .index = fsize->index,
1361                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1362         };
1363         int ret;
1364
1365         sd_fmt = find_format_by_fourcc(dcmi, fsize->pixel_format);
1366         if (!sd_fmt)
1367                 return -EINVAL;
1368
1369         fse.code = sd_fmt->mbus_code;
1370
1371         ret = v4l2_subdev_call(dcmi->entity.source, pad, enum_frame_size,
1372                                NULL, &fse);
1373         if (ret)
1374                 return ret;
1375
1376         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1377         fsize->discrete.width = fse.max_width;
1378         fsize->discrete.height = fse.max_height;
1379
1380         return 0;
1381 }
1382
1383 static int dcmi_g_parm(struct file *file, void *priv,
1384                        struct v4l2_streamparm *p)
1385 {
1386         struct stm32_dcmi *dcmi = video_drvdata(file);
1387
1388         return v4l2_g_parm_cap(video_devdata(file), dcmi->entity.source, p);
1389 }
1390
1391 static int dcmi_s_parm(struct file *file, void *priv,
1392                        struct v4l2_streamparm *p)
1393 {
1394         struct stm32_dcmi *dcmi = video_drvdata(file);
1395
1396         return v4l2_s_parm_cap(video_devdata(file), dcmi->entity.source, p);
1397 }
1398
1399 static int dcmi_enum_frameintervals(struct file *file, void *fh,
1400                                     struct v4l2_frmivalenum *fival)
1401 {
1402         struct stm32_dcmi *dcmi = video_drvdata(file);
1403         const struct dcmi_format *sd_fmt;
1404         struct v4l2_subdev_frame_interval_enum fie = {
1405                 .index = fival->index,
1406                 .width = fival->width,
1407                 .height = fival->height,
1408                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1409         };
1410         int ret;
1411
1412         sd_fmt = find_format_by_fourcc(dcmi, fival->pixel_format);
1413         if (!sd_fmt)
1414                 return -EINVAL;
1415
1416         fie.code = sd_fmt->mbus_code;
1417
1418         ret = v4l2_subdev_call(dcmi->entity.source, pad,
1419                                enum_frame_interval, NULL, &fie);
1420         if (ret)
1421                 return ret;
1422
1423         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1424         fival->discrete = fie.interval;
1425
1426         return 0;
1427 }
1428
1429 static const struct of_device_id stm32_dcmi_of_match[] = {
1430         { .compatible = "st,stm32-dcmi"},
1431         { /* end node */ },
1432 };
1433 MODULE_DEVICE_TABLE(of, stm32_dcmi_of_match);
1434
1435 static int dcmi_open(struct file *file)
1436 {
1437         struct stm32_dcmi *dcmi = video_drvdata(file);
1438         struct v4l2_subdev *sd = dcmi->entity.source;
1439         int ret;
1440
1441         if (mutex_lock_interruptible(&dcmi->lock))
1442                 return -ERESTARTSYS;
1443
1444         ret = v4l2_fh_open(file);
1445         if (ret < 0)
1446                 goto unlock;
1447
1448         if (!v4l2_fh_is_singular_file(file))
1449                 goto fh_rel;
1450
1451         ret = v4l2_subdev_call(sd, core, s_power, 1);
1452         if (ret < 0 && ret != -ENOIOCTLCMD)
1453                 goto fh_rel;
1454
1455         ret = dcmi_set_fmt(dcmi, &dcmi->fmt);
1456         if (ret)
1457                 v4l2_subdev_call(sd, core, s_power, 0);
1458 fh_rel:
1459         if (ret)
1460                 v4l2_fh_release(file);
1461 unlock:
1462         mutex_unlock(&dcmi->lock);
1463         return ret;
1464 }
1465
1466 static int dcmi_release(struct file *file)
1467 {
1468         struct stm32_dcmi *dcmi = video_drvdata(file);
1469         struct v4l2_subdev *sd = dcmi->entity.source;
1470         bool fh_singular;
1471         int ret;
1472
1473         mutex_lock(&dcmi->lock);
1474
1475         fh_singular = v4l2_fh_is_singular_file(file);
1476
1477         ret = _vb2_fop_release(file, NULL);
1478
1479         if (fh_singular)
1480                 v4l2_subdev_call(sd, core, s_power, 0);
1481
1482         mutex_unlock(&dcmi->lock);
1483
1484         return ret;
1485 }
1486
1487 static const struct v4l2_ioctl_ops dcmi_ioctl_ops = {
1488         .vidioc_querycap                = dcmi_querycap,
1489
1490         .vidioc_try_fmt_vid_cap         = dcmi_try_fmt_vid_cap,
1491         .vidioc_g_fmt_vid_cap           = dcmi_g_fmt_vid_cap,
1492         .vidioc_s_fmt_vid_cap           = dcmi_s_fmt_vid_cap,
1493         .vidioc_enum_fmt_vid_cap        = dcmi_enum_fmt_vid_cap,
1494         .vidioc_g_selection             = dcmi_g_selection,
1495         .vidioc_s_selection             = dcmi_s_selection,
1496
1497         .vidioc_enum_input              = dcmi_enum_input,
1498         .vidioc_g_input                 = dcmi_g_input,
1499         .vidioc_s_input                 = dcmi_s_input,
1500
1501         .vidioc_g_parm                  = dcmi_g_parm,
1502         .vidioc_s_parm                  = dcmi_s_parm,
1503
1504         .vidioc_enum_framesizes         = dcmi_enum_framesizes,
1505         .vidioc_enum_frameintervals     = dcmi_enum_frameintervals,
1506
1507         .vidioc_reqbufs                 = vb2_ioctl_reqbufs,
1508         .vidioc_create_bufs             = vb2_ioctl_create_bufs,
1509         .vidioc_querybuf                = vb2_ioctl_querybuf,
1510         .vidioc_qbuf                    = vb2_ioctl_qbuf,
1511         .vidioc_dqbuf                   = vb2_ioctl_dqbuf,
1512         .vidioc_expbuf                  = vb2_ioctl_expbuf,
1513         .vidioc_prepare_buf             = vb2_ioctl_prepare_buf,
1514         .vidioc_streamon                = vb2_ioctl_streamon,
1515         .vidioc_streamoff               = vb2_ioctl_streamoff,
1516
1517         .vidioc_log_status              = v4l2_ctrl_log_status,
1518         .vidioc_subscribe_event         = v4l2_ctrl_subscribe_event,
1519         .vidioc_unsubscribe_event       = v4l2_event_unsubscribe,
1520 };
1521
1522 static const struct v4l2_file_operations dcmi_fops = {
1523         .owner          = THIS_MODULE,
1524         .unlocked_ioctl = video_ioctl2,
1525         .open           = dcmi_open,
1526         .release        = dcmi_release,
1527         .poll           = vb2_fop_poll,
1528         .mmap           = vb2_fop_mmap,
1529 #ifndef CONFIG_MMU
1530         .get_unmapped_area = vb2_fop_get_unmapped_area,
1531 #endif
1532         .read           = vb2_fop_read,
1533 };
1534
1535 static int dcmi_set_default_fmt(struct stm32_dcmi *dcmi)
1536 {
1537         struct v4l2_format f = {
1538                 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1539                 .fmt.pix = {
1540                         .width          = CIF_WIDTH,
1541                         .height         = CIF_HEIGHT,
1542                         .field          = V4L2_FIELD_NONE,
1543                         .pixelformat    = dcmi->sd_formats[0]->fourcc,
1544                 },
1545         };
1546         int ret;
1547
1548         ret = dcmi_try_fmt(dcmi, &f, NULL, NULL);
1549         if (ret)
1550                 return ret;
1551         dcmi->sd_format = dcmi->sd_formats[0];
1552         dcmi->fmt = f;
1553         return 0;
1554 }
1555
1556 /*
1557  * FIXME: For the time being we only support subdevices
1558  * which expose RGB & YUV "parallel form" mbus code (_2X8).
1559  * Nevertheless, this allows to support serial source subdevices
1560  * and serial to parallel bridges which conform to this.
1561  */
1562 static const struct dcmi_format dcmi_formats[] = {
1563         {
1564                 .fourcc = V4L2_PIX_FMT_RGB565,
1565                 .mbus_code = MEDIA_BUS_FMT_RGB565_2X8_LE,
1566                 .bpp = 2,
1567         }, {
1568                 .fourcc = V4L2_PIX_FMT_YUYV,
1569                 .mbus_code = MEDIA_BUS_FMT_YUYV8_2X8,
1570                 .bpp = 2,
1571         }, {
1572                 .fourcc = V4L2_PIX_FMT_UYVY,
1573                 .mbus_code = MEDIA_BUS_FMT_UYVY8_2X8,
1574                 .bpp = 2,
1575         }, {
1576                 .fourcc = V4L2_PIX_FMT_JPEG,
1577                 .mbus_code = MEDIA_BUS_FMT_JPEG_1X8,
1578                 .bpp = 1,
1579         },
1580 };
1581
1582 static int dcmi_formats_init(struct stm32_dcmi *dcmi)
1583 {
1584         const struct dcmi_format *sd_fmts[ARRAY_SIZE(dcmi_formats)];
1585         unsigned int num_fmts = 0, i, j;
1586         struct v4l2_subdev *subdev = dcmi->entity.source;
1587         struct v4l2_subdev_mbus_code_enum mbus_code = {
1588                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1589         };
1590
1591         while (!v4l2_subdev_call(subdev, pad, enum_mbus_code,
1592                                  NULL, &mbus_code)) {
1593                 for (i = 0; i < ARRAY_SIZE(dcmi_formats); i++) {
1594                         if (dcmi_formats[i].mbus_code != mbus_code.code)
1595                                 continue;
1596
1597                         /* Code supported, have we got this fourcc yet? */
1598                         for (j = 0; j < num_fmts; j++)
1599                                 if (sd_fmts[j]->fourcc ==
1600                                                 dcmi_formats[i].fourcc) {
1601                                         /* Already available */
1602                                         dev_dbg(dcmi->dev, "Skipping fourcc/code: %4.4s/0x%x\n",
1603                                                 (char *)&sd_fmts[j]->fourcc,
1604                                                 mbus_code.code);
1605                                         break;
1606                                 }
1607                         if (j == num_fmts) {
1608                                 /* New */
1609                                 sd_fmts[num_fmts++] = dcmi_formats + i;
1610                                 dev_dbg(dcmi->dev, "Supported fourcc/code: %4.4s/0x%x\n",
1611                                         (char *)&sd_fmts[num_fmts - 1]->fourcc,
1612                                         sd_fmts[num_fmts - 1]->mbus_code);
1613                         }
1614                 }
1615                 mbus_code.index++;
1616         }
1617
1618         if (!num_fmts)
1619                 return -ENXIO;
1620
1621         dcmi->num_of_sd_formats = num_fmts;
1622         dcmi->sd_formats = devm_kcalloc(dcmi->dev,
1623                                         num_fmts, sizeof(struct dcmi_format *),
1624                                         GFP_KERNEL);
1625         if (!dcmi->sd_formats) {
1626                 dev_err(dcmi->dev, "Could not allocate memory\n");
1627                 return -ENOMEM;
1628         }
1629
1630         memcpy(dcmi->sd_formats, sd_fmts,
1631                num_fmts * sizeof(struct dcmi_format *));
1632         dcmi->sd_format = dcmi->sd_formats[0];
1633
1634         return 0;
1635 }
1636
1637 static int dcmi_framesizes_init(struct stm32_dcmi *dcmi)
1638 {
1639         unsigned int num_fsize = 0;
1640         struct v4l2_subdev *subdev = dcmi->entity.source;
1641         struct v4l2_subdev_frame_size_enum fse = {
1642                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1643                 .code = dcmi->sd_format->mbus_code,
1644         };
1645         unsigned int ret;
1646         unsigned int i;
1647
1648         /* Allocate discrete framesizes array */
1649         while (!v4l2_subdev_call(subdev, pad, enum_frame_size,
1650                                  NULL, &fse))
1651                 fse.index++;
1652
1653         num_fsize = fse.index;
1654         if (!num_fsize)
1655                 return 0;
1656
1657         dcmi->num_of_sd_framesizes = num_fsize;
1658         dcmi->sd_framesizes = devm_kcalloc(dcmi->dev, num_fsize,
1659                                            sizeof(struct dcmi_framesize),
1660                                            GFP_KERNEL);
1661         if (!dcmi->sd_framesizes) {
1662                 dev_err(dcmi->dev, "Could not allocate memory\n");
1663                 return -ENOMEM;
1664         }
1665
1666         /* Fill array with sensor supported framesizes */
1667         dev_dbg(dcmi->dev, "Sensor supports %u frame sizes:\n", num_fsize);
1668         for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
1669                 fse.index = i;
1670                 ret = v4l2_subdev_call(subdev, pad, enum_frame_size,
1671                                        NULL, &fse);
1672                 if (ret)
1673                         return ret;
1674                 dcmi->sd_framesizes[fse.index].width = fse.max_width;
1675                 dcmi->sd_framesizes[fse.index].height = fse.max_height;
1676                 dev_dbg(dcmi->dev, "%ux%u\n", fse.max_width, fse.max_height);
1677         }
1678
1679         return 0;
1680 }
1681
1682 static int dcmi_graph_notify_complete(struct v4l2_async_notifier *notifier)
1683 {
1684         struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1685         int ret;
1686
1687         /*
1688          * Now that the graph is complete,
1689          * we search for the source subdevice
1690          * in order to expose it through V4L2 interface
1691          */
1692         dcmi->entity.source =
1693                 media_entity_to_v4l2_subdev(dcmi_find_source(dcmi));
1694         if (!dcmi->entity.source) {
1695                 dev_err(dcmi->dev, "Source subdevice not found\n");
1696                 return -ENODEV;
1697         }
1698
1699         dcmi->vdev->ctrl_handler = dcmi->entity.source->ctrl_handler;
1700
1701         ret = dcmi_formats_init(dcmi);
1702         if (ret) {
1703                 dev_err(dcmi->dev, "No supported mediabus format found\n");
1704                 return ret;
1705         }
1706
1707         ret = dcmi_framesizes_init(dcmi);
1708         if (ret) {
1709                 dev_err(dcmi->dev, "Could not initialize framesizes\n");
1710                 return ret;
1711         }
1712
1713         ret = dcmi_get_sensor_bounds(dcmi, &dcmi->sd_bounds);
1714         if (ret) {
1715                 dev_err(dcmi->dev, "Could not get sensor bounds\n");
1716                 return ret;
1717         }
1718
1719         ret = dcmi_set_default_fmt(dcmi);
1720         if (ret) {
1721                 dev_err(dcmi->dev, "Could not set default format\n");
1722                 return ret;
1723         }
1724
1725         return 0;
1726 }
1727
1728 static void dcmi_graph_notify_unbind(struct v4l2_async_notifier *notifier,
1729                                      struct v4l2_subdev *sd,
1730                                      struct v4l2_async_subdev *asd)
1731 {
1732         struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1733
1734         dev_dbg(dcmi->dev, "Removing %s\n", video_device_node_name(dcmi->vdev));
1735
1736         /* Checks internally if vdev has been init or not */
1737         video_unregister_device(dcmi->vdev);
1738 }
1739
1740 static int dcmi_graph_notify_bound(struct v4l2_async_notifier *notifier,
1741                                    struct v4l2_subdev *subdev,
1742                                    struct v4l2_async_subdev *asd)
1743 {
1744         struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1745         unsigned int ret;
1746         int src_pad;
1747
1748         dev_dbg(dcmi->dev, "Subdev \"%s\" bound\n", subdev->name);
1749
1750         /*
1751          * Link this sub-device to DCMI, it could be
1752          * a parallel camera sensor or a bridge
1753          */
1754         src_pad = media_entity_get_fwnode_pad(&subdev->entity,
1755                                               subdev->fwnode,
1756                                               MEDIA_PAD_FL_SOURCE);
1757
1758         ret = media_create_pad_link(&subdev->entity, src_pad,
1759                                     &dcmi->vdev->entity, 0,
1760                                     MEDIA_LNK_FL_IMMUTABLE |
1761                                     MEDIA_LNK_FL_ENABLED);
1762         if (ret)
1763                 dev_err(dcmi->dev, "Failed to create media pad link with subdev \"%s\"\n",
1764                         subdev->name);
1765         else
1766                 dev_dbg(dcmi->dev, "DCMI is now linked to \"%s\"\n",
1767                         subdev->name);
1768
1769         return ret;
1770 }
1771
1772 static const struct v4l2_async_notifier_operations dcmi_graph_notify_ops = {
1773         .bound = dcmi_graph_notify_bound,
1774         .unbind = dcmi_graph_notify_unbind,
1775         .complete = dcmi_graph_notify_complete,
1776 };
1777
1778 static int dcmi_graph_parse(struct stm32_dcmi *dcmi, struct device_node *node)
1779 {
1780         struct device_node *ep = NULL;
1781         struct device_node *remote;
1782
1783         ep = of_graph_get_next_endpoint(node, ep);
1784         if (!ep)
1785                 return -EINVAL;
1786
1787         remote = of_graph_get_remote_port_parent(ep);
1788         of_node_put(ep);
1789         if (!remote)
1790                 return -EINVAL;
1791
1792         /* Remote node to connect */
1793         dcmi->entity.remote_node = remote;
1794         dcmi->entity.asd.match_type = V4L2_ASYNC_MATCH_FWNODE;
1795         dcmi->entity.asd.match.fwnode = of_fwnode_handle(remote);
1796         return 0;
1797 }
1798
1799 static int dcmi_graph_init(struct stm32_dcmi *dcmi)
1800 {
1801         int ret;
1802
1803         /* Parse the graph to extract a list of subdevice DT nodes. */
1804         ret = dcmi_graph_parse(dcmi, dcmi->dev->of_node);
1805         if (ret < 0) {
1806                 dev_err(dcmi->dev, "Failed to parse graph\n");
1807                 return ret;
1808         }
1809
1810         v4l2_async_notifier_init(&dcmi->notifier);
1811
1812         ret = v4l2_async_notifier_add_subdev(&dcmi->notifier,
1813                                              &dcmi->entity.asd);
1814         if (ret) {
1815                 dev_err(dcmi->dev, "Failed to add subdev notifier\n");
1816                 of_node_put(dcmi->entity.remote_node);
1817                 return ret;
1818         }
1819
1820         dcmi->notifier.ops = &dcmi_graph_notify_ops;
1821
1822         ret = v4l2_async_notifier_register(&dcmi->v4l2_dev, &dcmi->notifier);
1823         if (ret < 0) {
1824                 dev_err(dcmi->dev, "Failed to register notifier\n");
1825                 v4l2_async_notifier_cleanup(&dcmi->notifier);
1826                 return ret;
1827         }
1828
1829         return 0;
1830 }
1831
1832 static int dcmi_probe(struct platform_device *pdev)
1833 {
1834         struct device_node *np = pdev->dev.of_node;
1835         const struct of_device_id *match = NULL;
1836         struct v4l2_fwnode_endpoint ep = { .bus_type = 0 };
1837         struct stm32_dcmi *dcmi;
1838         struct vb2_queue *q;
1839         struct dma_chan *chan;
1840         struct clk *mclk;
1841         int irq;
1842         int ret = 0;
1843
1844         match = of_match_device(of_match_ptr(stm32_dcmi_of_match), &pdev->dev);
1845         if (!match) {
1846                 dev_err(&pdev->dev, "Could not find a match in devicetree\n");
1847                 return -ENODEV;
1848         }
1849
1850         dcmi = devm_kzalloc(&pdev->dev, sizeof(struct stm32_dcmi), GFP_KERNEL);
1851         if (!dcmi)
1852                 return -ENOMEM;
1853
1854         dcmi->rstc = devm_reset_control_get_exclusive(&pdev->dev, NULL);
1855         if (IS_ERR(dcmi->rstc)) {
1856                 dev_err(&pdev->dev, "Could not get reset control\n");
1857                 return PTR_ERR(dcmi->rstc);
1858         }
1859
1860         /* Get bus characteristics from devicetree */
1861         np = of_graph_get_next_endpoint(np, NULL);
1862         if (!np) {
1863                 dev_err(&pdev->dev, "Could not find the endpoint\n");
1864                 return -ENODEV;
1865         }
1866
1867         ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(np), &ep);
1868         of_node_put(np);
1869         if (ret) {
1870                 dev_err(&pdev->dev, "Could not parse the endpoint\n");
1871                 return ret;
1872         }
1873
1874         if (ep.bus_type == V4L2_MBUS_CSI2_DPHY) {
1875                 dev_err(&pdev->dev, "CSI bus not supported\n");
1876                 return -ENODEV;
1877         }
1878         dcmi->bus.flags = ep.bus.parallel.flags;
1879         dcmi->bus.bus_width = ep.bus.parallel.bus_width;
1880         dcmi->bus.data_shift = ep.bus.parallel.data_shift;
1881
1882         irq = platform_get_irq(pdev, 0);
1883         if (irq <= 0)
1884                 return irq ? irq : -ENXIO;
1885
1886         dcmi->res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1887         if (!dcmi->res) {
1888                 dev_err(&pdev->dev, "Could not get resource\n");
1889                 return -ENODEV;
1890         }
1891
1892         dcmi->regs = devm_ioremap_resource(&pdev->dev, dcmi->res);
1893         if (IS_ERR(dcmi->regs)) {
1894                 dev_err(&pdev->dev, "Could not map registers\n");
1895                 return PTR_ERR(dcmi->regs);
1896         }
1897
1898         ret = devm_request_threaded_irq(&pdev->dev, irq, dcmi_irq_callback,
1899                                         dcmi_irq_thread, IRQF_ONESHOT,
1900                                         dev_name(&pdev->dev), dcmi);
1901         if (ret) {
1902                 dev_err(&pdev->dev, "Unable to request irq %d\n", irq);
1903                 return ret;
1904         }
1905
1906         mclk = devm_clk_get(&pdev->dev, "mclk");
1907         if (IS_ERR(mclk)) {
1908                 if (PTR_ERR(mclk) != -EPROBE_DEFER)
1909                         dev_err(&pdev->dev, "Unable to get mclk\n");
1910                 return PTR_ERR(mclk);
1911         }
1912
1913         chan = dma_request_slave_channel(&pdev->dev, "tx");
1914         if (!chan) {
1915                 dev_info(&pdev->dev, "Unable to request DMA channel, defer probing\n");
1916                 return -EPROBE_DEFER;
1917         }
1918
1919         spin_lock_init(&dcmi->irqlock);
1920         mutex_init(&dcmi->lock);
1921         mutex_init(&dcmi->dma_lock);
1922         init_completion(&dcmi->complete);
1923         INIT_LIST_HEAD(&dcmi->buffers);
1924
1925         dcmi->dev = &pdev->dev;
1926         dcmi->mclk = mclk;
1927         dcmi->state = STOPPED;
1928         dcmi->dma_chan = chan;
1929
1930         q = &dcmi->queue;
1931
1932         dcmi->v4l2_dev.mdev = &dcmi->mdev;
1933
1934         /* Initialize media device */
1935         strscpy(dcmi->mdev.model, DRV_NAME, sizeof(dcmi->mdev.model));
1936         snprintf(dcmi->mdev.bus_info, sizeof(dcmi->mdev.bus_info),
1937                  "platform:%s", DRV_NAME);
1938         dcmi->mdev.dev = &pdev->dev;
1939         media_device_init(&dcmi->mdev);
1940
1941         /* Initialize the top-level structure */
1942         ret = v4l2_device_register(&pdev->dev, &dcmi->v4l2_dev);
1943         if (ret)
1944                 goto err_media_device_cleanup;
1945
1946         dcmi->vdev = video_device_alloc();
1947         if (!dcmi->vdev) {
1948                 ret = -ENOMEM;
1949                 goto err_device_unregister;
1950         }
1951
1952         /* Video node */
1953         dcmi->vdev->fops = &dcmi_fops;
1954         dcmi->vdev->v4l2_dev = &dcmi->v4l2_dev;
1955         dcmi->vdev->queue = &dcmi->queue;
1956         strscpy(dcmi->vdev->name, KBUILD_MODNAME, sizeof(dcmi->vdev->name));
1957         dcmi->vdev->release = video_device_release;
1958         dcmi->vdev->ioctl_ops = &dcmi_ioctl_ops;
1959         dcmi->vdev->lock = &dcmi->lock;
1960         dcmi->vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
1961                                   V4L2_CAP_READWRITE;
1962         video_set_drvdata(dcmi->vdev, dcmi);
1963
1964         /* Media entity pads */
1965         dcmi->vid_cap_pad.flags = MEDIA_PAD_FL_SINK;
1966         ret = media_entity_pads_init(&dcmi->vdev->entity,
1967                                      1, &dcmi->vid_cap_pad);
1968         if (ret) {
1969                 dev_err(dcmi->dev, "Failed to init media entity pad\n");
1970                 goto err_device_release;
1971         }
1972         dcmi->vdev->entity.flags |= MEDIA_ENT_FL_DEFAULT;
1973
1974         ret = video_register_device(dcmi->vdev, VFL_TYPE_GRABBER, -1);
1975         if (ret) {
1976                 dev_err(dcmi->dev, "Failed to register video device\n");
1977                 goto err_media_entity_cleanup;
1978         }
1979
1980         dev_dbg(dcmi->dev, "Device registered as %s\n",
1981                 video_device_node_name(dcmi->vdev));
1982
1983         /* Buffer queue */
1984         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1985         q->io_modes = VB2_MMAP | VB2_READ | VB2_DMABUF;
1986         q->lock = &dcmi->lock;
1987         q->drv_priv = dcmi;
1988         q->buf_struct_size = sizeof(struct dcmi_buf);
1989         q->ops = &dcmi_video_qops;
1990         q->mem_ops = &vb2_dma_contig_memops;
1991         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1992         q->min_buffers_needed = 2;
1993         q->dev = &pdev->dev;
1994
1995         ret = vb2_queue_init(q);
1996         if (ret < 0) {
1997                 dev_err(&pdev->dev, "Failed to initialize vb2 queue\n");
1998                 goto err_media_entity_cleanup;
1999         }
2000
2001         ret = dcmi_graph_init(dcmi);
2002         if (ret < 0)
2003                 goto err_media_entity_cleanup;
2004
2005         /* Reset device */
2006         ret = reset_control_assert(dcmi->rstc);
2007         if (ret) {
2008                 dev_err(&pdev->dev, "Failed to assert the reset line\n");
2009                 goto err_cleanup;
2010         }
2011
2012         usleep_range(3000, 5000);
2013
2014         ret = reset_control_deassert(dcmi->rstc);
2015         if (ret) {
2016                 dev_err(&pdev->dev, "Failed to deassert the reset line\n");
2017                 goto err_cleanup;
2018         }
2019
2020         dev_info(&pdev->dev, "Probe done\n");
2021
2022         platform_set_drvdata(pdev, dcmi);
2023
2024         pm_runtime_enable(&pdev->dev);
2025
2026         return 0;
2027
2028 err_cleanup:
2029         v4l2_async_notifier_cleanup(&dcmi->notifier);
2030 err_media_entity_cleanup:
2031         media_entity_cleanup(&dcmi->vdev->entity);
2032 err_device_release:
2033         video_device_release(dcmi->vdev);
2034 err_device_unregister:
2035         v4l2_device_unregister(&dcmi->v4l2_dev);
2036 err_media_device_cleanup:
2037         media_device_cleanup(&dcmi->mdev);
2038         dma_release_channel(dcmi->dma_chan);
2039
2040         return ret;
2041 }
2042
2043 static int dcmi_remove(struct platform_device *pdev)
2044 {
2045         struct stm32_dcmi *dcmi = platform_get_drvdata(pdev);
2046
2047         pm_runtime_disable(&pdev->dev);
2048
2049         v4l2_async_notifier_unregister(&dcmi->notifier);
2050         v4l2_async_notifier_cleanup(&dcmi->notifier);
2051         media_entity_cleanup(&dcmi->vdev->entity);
2052         v4l2_device_unregister(&dcmi->v4l2_dev);
2053         media_device_cleanup(&dcmi->mdev);
2054
2055         dma_release_channel(dcmi->dma_chan);
2056
2057         return 0;
2058 }
2059
2060 static __maybe_unused int dcmi_runtime_suspend(struct device *dev)
2061 {
2062         struct stm32_dcmi *dcmi = dev_get_drvdata(dev);
2063
2064         clk_disable_unprepare(dcmi->mclk);
2065
2066         return 0;
2067 }
2068
2069 static __maybe_unused int dcmi_runtime_resume(struct device *dev)
2070 {
2071         struct stm32_dcmi *dcmi = dev_get_drvdata(dev);
2072         int ret;
2073
2074         ret = clk_prepare_enable(dcmi->mclk);
2075         if (ret)
2076                 dev_err(dev, "%s: Failed to prepare_enable clock\n", __func__);
2077
2078         return ret;
2079 }
2080
2081 static __maybe_unused int dcmi_suspend(struct device *dev)
2082 {
2083         /* disable clock */
2084         pm_runtime_force_suspend(dev);
2085
2086         /* change pinctrl state */
2087         pinctrl_pm_select_sleep_state(dev);
2088
2089         return 0;
2090 }
2091
2092 static __maybe_unused int dcmi_resume(struct device *dev)
2093 {
2094         /* restore pinctl default state */
2095         pinctrl_pm_select_default_state(dev);
2096
2097         /* clock enable */
2098         pm_runtime_force_resume(dev);
2099
2100         return 0;
2101 }
2102
2103 static const struct dev_pm_ops dcmi_pm_ops = {
2104         SET_SYSTEM_SLEEP_PM_OPS(dcmi_suspend, dcmi_resume)
2105         SET_RUNTIME_PM_OPS(dcmi_runtime_suspend,
2106                            dcmi_runtime_resume, NULL)
2107 };
2108
2109 static struct platform_driver stm32_dcmi_driver = {
2110         .probe          = dcmi_probe,
2111         .remove         = dcmi_remove,
2112         .driver         = {
2113                 .name = DRV_NAME,
2114                 .of_match_table = of_match_ptr(stm32_dcmi_of_match),
2115                 .pm = &dcmi_pm_ops,
2116         },
2117 };
2118
2119 module_platform_driver(stm32_dcmi_driver);
2120
2121 MODULE_AUTHOR("Yannick Fertre <yannick.fertre@st.com>");
2122 MODULE_AUTHOR("Hugues Fruchet <hugues.fruchet@st.com>");
2123 MODULE_DESCRIPTION("STMicroelectronics STM32 Digital Camera Memory Interface driver");
2124 MODULE_LICENSE("GPL");
2125 MODULE_SUPPORTED_DEVICE("video");