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