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