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