Merge tag 'for_linus' of git://git.kernel.org/pub/scm/linux/kernel/git/mst/vhost
[cris-mirror.git] / drivers / media / platform / stm32 / stm32-dcmi.c
blob9460b3080dca1c0cbca254f05550e265ee9f726d
1 /*
2 * Driver for STM32 Digital Camera Memory Interface
4 * Copyright (C) STMicroelectronics SA 2017
5 * Authors: Yannick Fertre <yannick.fertre@st.com>
6 * Hugues Fruchet <hugues.fruchet@st.com>
7 * for STMicroelectronics.
8 * License terms: GNU General Public License (GPL), version 2
10 * This driver is based on atmel_isi.c
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>
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>
39 #define DRV_NAME "stm32-dcmi"
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 */
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)
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)
76 * Bits definition for interrupt registers
77 * (DCMI_RIS, DCMI_IER, DCMI_MIS, DCMI_ICR)
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)
85 enum state {
86 STOPPED = 0,
87 RUNNING,
88 STOPPING,
91 #define MIN_WIDTH 16U
92 #define MAX_WIDTH 2048U
93 #define MIN_HEIGHT 16U
94 #define MAX_HEIGHT 2048U
96 #define TIMEOUT_MS 1000
98 struct dcmi_graph_entity {
99 struct device_node *node;
101 struct v4l2_async_subdev asd;
102 struct v4l2_subdev *subdev;
105 struct dcmi_format {
106 u32 fourcc;
107 u32 mbus_code;
108 u8 bpp;
111 struct dcmi_framesize {
112 u32 width;
113 u32 height;
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;
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;
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;
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;
151 /* Protect this data structure */
152 struct mutex lock;
153 struct vb2_queue queue;
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 buffers_count;
166 static inline struct stm32_dcmi *notifier_to_dcmi(struct v4l2_async_notifier *n)
168 return container_of(n, struct stm32_dcmi, notifier);
171 static inline u32 reg_read(void __iomem *base, u32 reg)
173 return readl_relaxed(base + reg);
176 static inline void reg_write(void __iomem *base, u32 reg, u32 val)
178 writel_relaxed(val, base + reg);
181 static inline void reg_set(void __iomem *base, u32 reg, u32 mask)
183 reg_write(base, reg, reg_read(base, reg) | mask);
186 static inline void reg_clear(void __iomem *base, u32 reg, u32 mask)
188 reg_write(base, reg, reg_read(base, reg) & ~mask);
191 static int dcmi_start_capture(struct stm32_dcmi *dcmi);
193 static void dcmi_dma_callback(void *param)
195 struct stm32_dcmi *dcmi = (struct stm32_dcmi *)param;
196 struct dma_chan *chan = dcmi->dma_chan;
197 struct dma_tx_state state;
198 enum dma_status status;
200 spin_lock(&dcmi->irqlock);
202 /* Check DMA status */
203 status = dmaengine_tx_status(chan, dcmi->dma_cookie, &state);
205 switch (status) {
206 case DMA_IN_PROGRESS:
207 dev_dbg(dcmi->dev, "%s: Received DMA_IN_PROGRESS\n", __func__);
208 break;
209 case DMA_PAUSED:
210 dev_err(dcmi->dev, "%s: Received DMA_PAUSED\n", __func__);
211 break;
212 case DMA_ERROR:
213 dev_err(dcmi->dev, "%s: Received DMA_ERROR\n", __func__);
214 break;
215 case DMA_COMPLETE:
216 dev_dbg(dcmi->dev, "%s: Received DMA_COMPLETE\n", __func__);
218 if (dcmi->active) {
219 struct dcmi_buf *buf = dcmi->active;
220 struct vb2_v4l2_buffer *vbuf = &dcmi->active->vb;
222 vbuf->sequence = dcmi->sequence++;
223 vbuf->field = V4L2_FIELD_NONE;
224 vbuf->vb2_buf.timestamp = ktime_get_ns();
225 vb2_set_plane_payload(&vbuf->vb2_buf, 0, buf->size);
226 vb2_buffer_done(&vbuf->vb2_buf, VB2_BUF_STATE_DONE);
227 dev_dbg(dcmi->dev, "buffer[%d] done seq=%d\n",
228 vbuf->vb2_buf.index, vbuf->sequence);
230 dcmi->buffers_count++;
231 dcmi->active = NULL;
234 /* Restart a new DMA transfer with next buffer */
235 if (dcmi->state == RUNNING) {
236 if (list_empty(&dcmi->buffers)) {
237 dev_err(dcmi->dev, "%s: No more buffer queued, cannot capture buffer",
238 __func__);
239 dcmi->errors_count++;
240 dcmi->active = NULL;
242 spin_unlock(&dcmi->irqlock);
243 return;
246 dcmi->active = list_entry(dcmi->buffers.next,
247 struct dcmi_buf, list);
249 list_del_init(&dcmi->active->list);
251 if (dcmi_start_capture(dcmi)) {
252 dev_err(dcmi->dev, "%s: Cannot restart capture on DMA complete",
253 __func__);
255 spin_unlock(&dcmi->irqlock);
256 return;
259 /* Enable capture */
260 reg_set(dcmi->regs, DCMI_CR, CR_CAPTURE);
263 break;
264 default:
265 dev_err(dcmi->dev, "%s: Received unknown status\n", __func__);
266 break;
269 spin_unlock(&dcmi->irqlock);
272 static int dcmi_start_dma(struct stm32_dcmi *dcmi,
273 struct dcmi_buf *buf)
275 struct dma_async_tx_descriptor *desc = NULL;
276 struct dma_slave_config config;
277 int ret;
279 memset(&config, 0, sizeof(config));
281 config.src_addr = (dma_addr_t)dcmi->res->start + DCMI_DR;
282 config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
283 config.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
284 config.dst_maxburst = 4;
286 /* Configure DMA channel */
287 ret = dmaengine_slave_config(dcmi->dma_chan, &config);
288 if (ret < 0) {
289 dev_err(dcmi->dev, "%s: DMA channel config failed (%d)\n",
290 __func__, ret);
291 return ret;
294 /* Prepare a DMA transaction */
295 desc = dmaengine_prep_slave_single(dcmi->dma_chan, buf->paddr,
296 buf->size,
297 DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT);
298 if (!desc) {
299 dev_err(dcmi->dev, "%s: DMA dmaengine_prep_slave_single failed for buffer size %zu\n",
300 __func__, buf->size);
301 return -EINVAL;
304 /* Set completion callback routine for notification */
305 desc->callback = dcmi_dma_callback;
306 desc->callback_param = dcmi;
308 /* Push current DMA transaction in the pending queue */
309 dcmi->dma_cookie = dmaengine_submit(desc);
310 if (dma_submit_error(dcmi->dma_cookie)) {
311 dev_err(dcmi->dev, "%s: DMA submission failed\n", __func__);
312 return -ENXIO;
315 dma_async_issue_pending(dcmi->dma_chan);
317 return 0;
320 static int dcmi_start_capture(struct stm32_dcmi *dcmi)
322 int ret;
323 struct dcmi_buf *buf = dcmi->active;
325 if (!buf)
326 return -EINVAL;
328 ret = dcmi_start_dma(dcmi, buf);
329 if (ret) {
330 dcmi->errors_count++;
331 return ret;
334 /* Enable capture */
335 reg_set(dcmi->regs, DCMI_CR, CR_CAPTURE);
337 return 0;
340 static void dcmi_set_crop(struct stm32_dcmi *dcmi)
342 u32 size, start;
344 /* Crop resolution */
345 size = ((dcmi->crop.height - 1) << 16) |
346 ((dcmi->crop.width << 1) - 1);
347 reg_write(dcmi->regs, DCMI_CWSIZE, size);
349 /* Crop start point */
350 start = ((dcmi->crop.top) << 16) |
351 ((dcmi->crop.left << 1));
352 reg_write(dcmi->regs, DCMI_CWSTRT, start);
354 dev_dbg(dcmi->dev, "Cropping to %ux%u@%u:%u\n",
355 dcmi->crop.width, dcmi->crop.height,
356 dcmi->crop.left, dcmi->crop.top);
358 /* Enable crop */
359 reg_set(dcmi->regs, DCMI_CR, CR_CROP);
362 static irqreturn_t dcmi_irq_thread(int irq, void *arg)
364 struct stm32_dcmi *dcmi = arg;
366 spin_lock(&dcmi->irqlock);
368 /* Stop capture is required */
369 if (dcmi->state == STOPPING) {
370 reg_clear(dcmi->regs, DCMI_IER, IT_FRAME | IT_OVR | IT_ERR);
372 dcmi->state = STOPPED;
374 complete(&dcmi->complete);
376 spin_unlock(&dcmi->irqlock);
377 return IRQ_HANDLED;
380 if ((dcmi->misr & IT_OVR) || (dcmi->misr & IT_ERR)) {
382 * An overflow or an error has been detected,
383 * stop current DMA transfert & restart it
385 dev_warn(dcmi->dev, "%s: Overflow or error detected\n",
386 __func__);
388 dcmi->errors_count++;
389 dmaengine_terminate_all(dcmi->dma_chan);
391 reg_set(dcmi->regs, DCMI_ICR, IT_FRAME | IT_OVR | IT_ERR);
393 dev_dbg(dcmi->dev, "Restarting capture after DCMI error\n");
395 if (dcmi_start_capture(dcmi)) {
396 dev_err(dcmi->dev, "%s: Cannot restart capture on overflow or error\n",
397 __func__);
399 spin_unlock(&dcmi->irqlock);
400 return IRQ_HANDLED;
404 spin_unlock(&dcmi->irqlock);
405 return IRQ_HANDLED;
408 static irqreturn_t dcmi_irq_callback(int irq, void *arg)
410 struct stm32_dcmi *dcmi = arg;
412 spin_lock(&dcmi->irqlock);
414 dcmi->misr = reg_read(dcmi->regs, DCMI_MIS);
416 /* Clear interrupt */
417 reg_set(dcmi->regs, DCMI_ICR, IT_FRAME | IT_OVR | IT_ERR);
419 spin_unlock(&dcmi->irqlock);
421 return IRQ_WAKE_THREAD;
424 static int dcmi_queue_setup(struct vb2_queue *vq,
425 unsigned int *nbuffers,
426 unsigned int *nplanes,
427 unsigned int sizes[],
428 struct device *alloc_devs[])
430 struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
431 unsigned int size;
433 size = dcmi->fmt.fmt.pix.sizeimage;
435 /* Make sure the image size is large enough */
436 if (*nplanes)
437 return sizes[0] < size ? -EINVAL : 0;
439 *nplanes = 1;
440 sizes[0] = size;
442 dcmi->active = NULL;
444 dev_dbg(dcmi->dev, "Setup queue, count=%d, size=%d\n",
445 *nbuffers, size);
447 return 0;
450 static int dcmi_buf_init(struct vb2_buffer *vb)
452 struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
453 struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
455 INIT_LIST_HEAD(&buf->list);
457 return 0;
460 static int dcmi_buf_prepare(struct vb2_buffer *vb)
462 struct stm32_dcmi *dcmi = vb2_get_drv_priv(vb->vb2_queue);
463 struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
464 struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
465 unsigned long size;
467 size = dcmi->fmt.fmt.pix.sizeimage;
469 if (vb2_plane_size(vb, 0) < size) {
470 dev_err(dcmi->dev, "%s data will not fit into plane (%lu < %lu)\n",
471 __func__, vb2_plane_size(vb, 0), size);
472 return -EINVAL;
475 vb2_set_plane_payload(vb, 0, size);
477 if (!buf->prepared) {
478 /* Get memory addresses */
479 buf->paddr =
480 vb2_dma_contig_plane_dma_addr(&buf->vb.vb2_buf, 0);
481 buf->size = vb2_plane_size(&buf->vb.vb2_buf, 0);
482 buf->prepared = true;
484 vb2_set_plane_payload(&buf->vb.vb2_buf, 0, buf->size);
486 dev_dbg(dcmi->dev, "buffer[%d] phy=0x%pad size=%zu\n",
487 vb->index, &buf->paddr, buf->size);
490 return 0;
493 static void dcmi_buf_queue(struct vb2_buffer *vb)
495 struct stm32_dcmi *dcmi = vb2_get_drv_priv(vb->vb2_queue);
496 struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
497 struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
498 unsigned long flags = 0;
500 spin_lock_irqsave(&dcmi->irqlock, flags);
502 if ((dcmi->state == RUNNING) && (!dcmi->active)) {
503 dcmi->active = buf;
505 dev_dbg(dcmi->dev, "Starting capture on buffer[%d] queued\n",
506 buf->vb.vb2_buf.index);
508 if (dcmi_start_capture(dcmi)) {
509 dev_err(dcmi->dev, "%s: Cannot restart capture on overflow or error\n",
510 __func__);
512 spin_unlock_irqrestore(&dcmi->irqlock, flags);
513 return;
515 } else {
516 /* Enqueue to video buffers list */
517 list_add_tail(&buf->list, &dcmi->buffers);
520 spin_unlock_irqrestore(&dcmi->irqlock, flags);
523 static int dcmi_start_streaming(struct vb2_queue *vq, unsigned int count)
525 struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
526 struct dcmi_buf *buf, *node;
527 u32 val = 0;
528 int ret;
530 ret = clk_enable(dcmi->mclk);
531 if (ret) {
532 dev_err(dcmi->dev, "%s: Failed to start streaming, cannot enable clock",
533 __func__);
534 goto err_release_buffers;
537 /* Enable stream on the sub device */
538 ret = v4l2_subdev_call(dcmi->entity.subdev, video, s_stream, 1);
539 if (ret && ret != -ENOIOCTLCMD) {
540 dev_err(dcmi->dev, "%s: Failed to start streaming, subdev streamon error",
541 __func__);
542 goto err_disable_clock;
545 spin_lock_irq(&dcmi->irqlock);
547 /* Set bus width */
548 switch (dcmi->bus.bus_width) {
549 case 14:
550 val |= CR_EDM_0 | CR_EDM_1;
551 break;
552 case 12:
553 val |= CR_EDM_1;
554 break;
555 case 10:
556 val |= CR_EDM_0;
557 break;
558 default:
559 /* Set bus width to 8 bits by default */
560 break;
563 /* Set vertical synchronization polarity */
564 if (dcmi->bus.flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH)
565 val |= CR_VSPOL;
567 /* Set horizontal synchronization polarity */
568 if (dcmi->bus.flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH)
569 val |= CR_HSPOL;
571 /* Set pixel clock polarity */
572 if (dcmi->bus.flags & V4L2_MBUS_PCLK_SAMPLE_RISING)
573 val |= CR_PCKPOL;
575 reg_write(dcmi->regs, DCMI_CR, val);
577 /* Set crop */
578 if (dcmi->do_crop)
579 dcmi_set_crop(dcmi);
581 /* Enable dcmi */
582 reg_set(dcmi->regs, DCMI_CR, CR_ENABLE);
584 dcmi->state = RUNNING;
586 dcmi->sequence = 0;
587 dcmi->errors_count = 0;
588 dcmi->buffers_count = 0;
589 dcmi->active = NULL;
592 * Start transfer if at least one buffer has been queued,
593 * otherwise transfer is deferred at buffer queueing
595 if (list_empty(&dcmi->buffers)) {
596 dev_dbg(dcmi->dev, "Start streaming is deferred to next buffer queueing\n");
597 spin_unlock_irq(&dcmi->irqlock);
598 return 0;
601 dcmi->active = list_entry(dcmi->buffers.next, struct dcmi_buf, list);
602 list_del_init(&dcmi->active->list);
604 dev_dbg(dcmi->dev, "Start streaming, starting capture\n");
606 ret = dcmi_start_capture(dcmi);
607 if (ret) {
608 dev_err(dcmi->dev, "%s: Start streaming failed, cannot start capture",
609 __func__);
611 spin_unlock_irq(&dcmi->irqlock);
612 goto err_subdev_streamoff;
615 /* Enable interruptions */
616 reg_set(dcmi->regs, DCMI_IER, IT_FRAME | IT_OVR | IT_ERR);
618 spin_unlock_irq(&dcmi->irqlock);
620 return 0;
622 err_subdev_streamoff:
623 v4l2_subdev_call(dcmi->entity.subdev, video, s_stream, 0);
625 err_disable_clock:
626 clk_disable(dcmi->mclk);
628 err_release_buffers:
629 spin_lock_irq(&dcmi->irqlock);
631 * Return all buffers to vb2 in QUEUED state.
632 * This will give ownership back to userspace
634 if (dcmi->active) {
635 buf = dcmi->active;
636 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED);
637 dcmi->active = NULL;
639 list_for_each_entry_safe(buf, node, &dcmi->buffers, list) {
640 list_del_init(&buf->list);
641 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED);
643 spin_unlock_irq(&dcmi->irqlock);
645 return ret;
648 static void dcmi_stop_streaming(struct vb2_queue *vq)
650 struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
651 struct dcmi_buf *buf, *node;
652 unsigned long time_ms = msecs_to_jiffies(TIMEOUT_MS);
653 long timeout;
654 int ret;
656 /* Disable stream on the sub device */
657 ret = v4l2_subdev_call(dcmi->entity.subdev, video, s_stream, 0);
658 if (ret && ret != -ENOIOCTLCMD)
659 dev_err(dcmi->dev, "stream off failed in subdev\n");
661 dcmi->state = STOPPING;
663 timeout = wait_for_completion_interruptible_timeout(&dcmi->complete,
664 time_ms);
666 spin_lock_irq(&dcmi->irqlock);
668 /* Disable interruptions */
669 reg_clear(dcmi->regs, DCMI_IER, IT_FRAME | IT_OVR | IT_ERR);
671 /* Disable DCMI */
672 reg_clear(dcmi->regs, DCMI_CR, CR_ENABLE);
674 if (!timeout) {
675 dev_err(dcmi->dev, "Timeout during stop streaming\n");
676 dcmi->state = STOPPED;
679 /* Return all queued buffers to vb2 in ERROR state */
680 if (dcmi->active) {
681 buf = dcmi->active;
682 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
683 dcmi->active = NULL;
685 list_for_each_entry_safe(buf, node, &dcmi->buffers, list) {
686 list_del_init(&buf->list);
687 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
690 spin_unlock_irq(&dcmi->irqlock);
692 /* Stop all pending DMA operations */
693 dmaengine_terminate_all(dcmi->dma_chan);
695 clk_disable(dcmi->mclk);
697 dev_dbg(dcmi->dev, "Stop streaming, errors=%d buffers=%d\n",
698 dcmi->errors_count, dcmi->buffers_count);
701 static const struct vb2_ops dcmi_video_qops = {
702 .queue_setup = dcmi_queue_setup,
703 .buf_init = dcmi_buf_init,
704 .buf_prepare = dcmi_buf_prepare,
705 .buf_queue = dcmi_buf_queue,
706 .start_streaming = dcmi_start_streaming,
707 .stop_streaming = dcmi_stop_streaming,
708 .wait_prepare = vb2_ops_wait_prepare,
709 .wait_finish = vb2_ops_wait_finish,
712 static int dcmi_g_fmt_vid_cap(struct file *file, void *priv,
713 struct v4l2_format *fmt)
715 struct stm32_dcmi *dcmi = video_drvdata(file);
717 *fmt = dcmi->fmt;
719 return 0;
722 static const struct dcmi_format *find_format_by_fourcc(struct stm32_dcmi *dcmi,
723 unsigned int fourcc)
725 unsigned int num_formats = dcmi->num_of_sd_formats;
726 const struct dcmi_format *fmt;
727 unsigned int i;
729 for (i = 0; i < num_formats; i++) {
730 fmt = dcmi->sd_formats[i];
731 if (fmt->fourcc == fourcc)
732 return fmt;
735 return NULL;
738 static void __find_outer_frame_size(struct stm32_dcmi *dcmi,
739 struct v4l2_pix_format *pix,
740 struct dcmi_framesize *framesize)
742 struct dcmi_framesize *match = NULL;
743 unsigned int i;
744 unsigned int min_err = UINT_MAX;
746 for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
747 struct dcmi_framesize *fsize = &dcmi->sd_framesizes[i];
748 int w_err = (fsize->width - pix->width);
749 int h_err = (fsize->height - pix->height);
750 int err = w_err + h_err;
752 if ((w_err >= 0) && (h_err >= 0) && (err < min_err)) {
753 min_err = err;
754 match = fsize;
757 if (!match)
758 match = &dcmi->sd_framesizes[0];
760 *framesize = *match;
763 static int dcmi_try_fmt(struct stm32_dcmi *dcmi, struct v4l2_format *f,
764 const struct dcmi_format **sd_format,
765 struct dcmi_framesize *sd_framesize)
767 const struct dcmi_format *sd_fmt;
768 struct dcmi_framesize sd_fsize;
769 struct v4l2_pix_format *pix = &f->fmt.pix;
770 struct v4l2_subdev_pad_config pad_cfg;
771 struct v4l2_subdev_format format = {
772 .which = V4L2_SUBDEV_FORMAT_TRY,
774 int ret;
776 sd_fmt = find_format_by_fourcc(dcmi, pix->pixelformat);
777 if (!sd_fmt) {
778 sd_fmt = dcmi->sd_formats[dcmi->num_of_sd_formats - 1];
779 pix->pixelformat = sd_fmt->fourcc;
782 /* Limit to hardware capabilities */
783 pix->width = clamp(pix->width, MIN_WIDTH, MAX_WIDTH);
784 pix->height = clamp(pix->height, MIN_HEIGHT, MAX_HEIGHT);
786 if (dcmi->do_crop && dcmi->num_of_sd_framesizes) {
787 struct dcmi_framesize outer_sd_fsize;
789 * If crop is requested and sensor have discrete frame sizes,
790 * select the frame size that is just larger than request
792 __find_outer_frame_size(dcmi, pix, &outer_sd_fsize);
793 pix->width = outer_sd_fsize.width;
794 pix->height = outer_sd_fsize.height;
797 v4l2_fill_mbus_format(&format.format, pix, sd_fmt->mbus_code);
798 ret = v4l2_subdev_call(dcmi->entity.subdev, pad, set_fmt,
799 &pad_cfg, &format);
800 if (ret < 0)
801 return ret;
803 /* Update pix regarding to what sensor can do */
804 v4l2_fill_pix_format(pix, &format.format);
806 /* Save resolution that sensor can actually do */
807 sd_fsize.width = pix->width;
808 sd_fsize.height = pix->height;
810 if (dcmi->do_crop) {
811 struct v4l2_rect c = dcmi->crop;
812 struct v4l2_rect max_rect;
815 * Adjust crop by making the intersection between
816 * format resolution request and crop request
818 max_rect.top = 0;
819 max_rect.left = 0;
820 max_rect.width = pix->width;
821 max_rect.height = pix->height;
822 v4l2_rect_map_inside(&c, &max_rect);
823 c.top = clamp_t(s32, c.top, 0, pix->height - c.height);
824 c.left = clamp_t(s32, c.left, 0, pix->width - c.width);
825 dcmi->crop = c;
827 /* Adjust format resolution request to crop */
828 pix->width = dcmi->crop.width;
829 pix->height = dcmi->crop.height;
832 pix->field = V4L2_FIELD_NONE;
833 pix->bytesperline = pix->width * sd_fmt->bpp;
834 pix->sizeimage = pix->bytesperline * pix->height;
836 if (sd_format)
837 *sd_format = sd_fmt;
838 if (sd_framesize)
839 *sd_framesize = sd_fsize;
841 return 0;
844 static int dcmi_set_fmt(struct stm32_dcmi *dcmi, struct v4l2_format *f)
846 struct v4l2_subdev_format format = {
847 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
849 const struct dcmi_format *sd_format;
850 struct dcmi_framesize sd_framesize;
851 struct v4l2_mbus_framefmt *mf = &format.format;
852 struct v4l2_pix_format *pix = &f->fmt.pix;
853 int ret;
856 * Try format, fmt.width/height could have been changed
857 * to match sensor capability or crop request
858 * sd_format & sd_framesize will contain what subdev
859 * can do for this request.
861 ret = dcmi_try_fmt(dcmi, f, &sd_format, &sd_framesize);
862 if (ret)
863 return ret;
865 /* pix to mbus format */
866 v4l2_fill_mbus_format(mf, pix,
867 sd_format->mbus_code);
868 mf->width = sd_framesize.width;
869 mf->height = sd_framesize.height;
871 ret = v4l2_subdev_call(dcmi->entity.subdev, pad,
872 set_fmt, NULL, &format);
873 if (ret < 0)
874 return ret;
876 dev_dbg(dcmi->dev, "Sensor format set to 0x%x %ux%u\n",
877 mf->code, mf->width, mf->height);
878 dev_dbg(dcmi->dev, "Buffer format set to %4.4s %ux%u\n",
879 (char *)&pix->pixelformat,
880 pix->width, pix->height);
882 dcmi->fmt = *f;
883 dcmi->sd_format = sd_format;
884 dcmi->sd_framesize = sd_framesize;
886 return 0;
889 static int dcmi_s_fmt_vid_cap(struct file *file, void *priv,
890 struct v4l2_format *f)
892 struct stm32_dcmi *dcmi = video_drvdata(file);
894 if (vb2_is_streaming(&dcmi->queue))
895 return -EBUSY;
897 return dcmi_set_fmt(dcmi, f);
900 static int dcmi_try_fmt_vid_cap(struct file *file, void *priv,
901 struct v4l2_format *f)
903 struct stm32_dcmi *dcmi = video_drvdata(file);
905 return dcmi_try_fmt(dcmi, f, NULL, NULL);
908 static int dcmi_enum_fmt_vid_cap(struct file *file, void *priv,
909 struct v4l2_fmtdesc *f)
911 struct stm32_dcmi *dcmi = video_drvdata(file);
913 if (f->index >= dcmi->num_of_sd_formats)
914 return -EINVAL;
916 f->pixelformat = dcmi->sd_formats[f->index]->fourcc;
917 return 0;
920 static int dcmi_get_sensor_format(struct stm32_dcmi *dcmi,
921 struct v4l2_pix_format *pix)
923 struct v4l2_subdev_format fmt = {
924 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
926 int ret;
928 ret = v4l2_subdev_call(dcmi->entity.subdev, pad, get_fmt, NULL, &fmt);
929 if (ret)
930 return ret;
932 v4l2_fill_pix_format(pix, &fmt.format);
934 return 0;
937 static int dcmi_set_sensor_format(struct stm32_dcmi *dcmi,
938 struct v4l2_pix_format *pix)
940 const struct dcmi_format *sd_fmt;
941 struct v4l2_subdev_format format = {
942 .which = V4L2_SUBDEV_FORMAT_TRY,
944 struct v4l2_subdev_pad_config pad_cfg;
945 int ret;
947 sd_fmt = find_format_by_fourcc(dcmi, pix->pixelformat);
948 if (!sd_fmt) {
949 sd_fmt = dcmi->sd_formats[dcmi->num_of_sd_formats - 1];
950 pix->pixelformat = sd_fmt->fourcc;
953 v4l2_fill_mbus_format(&format.format, pix, sd_fmt->mbus_code);
954 ret = v4l2_subdev_call(dcmi->entity.subdev, pad, set_fmt,
955 &pad_cfg, &format);
956 if (ret < 0)
957 return ret;
959 return 0;
962 static int dcmi_get_sensor_bounds(struct stm32_dcmi *dcmi,
963 struct v4l2_rect *r)
965 struct v4l2_subdev_selection bounds = {
966 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
967 .target = V4L2_SEL_TGT_CROP_BOUNDS,
969 unsigned int max_width, max_height, max_pixsize;
970 struct v4l2_pix_format pix;
971 unsigned int i;
972 int ret;
975 * Get sensor bounds first
977 ret = v4l2_subdev_call(dcmi->entity.subdev, pad, get_selection,
978 NULL, &bounds);
979 if (!ret)
980 *r = bounds.r;
981 if (ret != -ENOIOCTLCMD)
982 return ret;
985 * If selection is not implemented,
986 * fallback by enumerating sensor frame sizes
987 * and take the largest one
989 max_width = 0;
990 max_height = 0;
991 max_pixsize = 0;
992 for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
993 struct dcmi_framesize *fsize = &dcmi->sd_framesizes[i];
994 unsigned int pixsize = fsize->width * fsize->height;
996 if (pixsize > max_pixsize) {
997 max_pixsize = pixsize;
998 max_width = fsize->width;
999 max_height = fsize->height;
1002 if (max_pixsize > 0) {
1003 r->top = 0;
1004 r->left = 0;
1005 r->width = max_width;
1006 r->height = max_height;
1007 return 0;
1011 * If frame sizes enumeration is not implemented,
1012 * fallback by getting current sensor frame size
1014 ret = dcmi_get_sensor_format(dcmi, &pix);
1015 if (ret)
1016 return ret;
1018 r->top = 0;
1019 r->left = 0;
1020 r->width = pix.width;
1021 r->height = pix.height;
1023 return 0;
1026 static int dcmi_g_selection(struct file *file, void *fh,
1027 struct v4l2_selection *s)
1029 struct stm32_dcmi *dcmi = video_drvdata(file);
1031 if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1032 return -EINVAL;
1034 switch (s->target) {
1035 case V4L2_SEL_TGT_CROP_DEFAULT:
1036 case V4L2_SEL_TGT_CROP_BOUNDS:
1037 s->r = dcmi->sd_bounds;
1038 return 0;
1039 case V4L2_SEL_TGT_CROP:
1040 if (dcmi->do_crop) {
1041 s->r = dcmi->crop;
1042 } else {
1043 s->r.top = 0;
1044 s->r.left = 0;
1045 s->r.width = dcmi->fmt.fmt.pix.width;
1046 s->r.height = dcmi->fmt.fmt.pix.height;
1048 break;
1049 default:
1050 return -EINVAL;
1053 return 0;
1056 static int dcmi_s_selection(struct file *file, void *priv,
1057 struct v4l2_selection *s)
1059 struct stm32_dcmi *dcmi = video_drvdata(file);
1060 struct v4l2_rect r = s->r;
1061 struct v4l2_rect max_rect;
1062 struct v4l2_pix_format pix;
1064 if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1065 s->target != V4L2_SEL_TGT_CROP)
1066 return -EINVAL;
1068 /* Reset sensor resolution to max resolution */
1069 pix.pixelformat = dcmi->fmt.fmt.pix.pixelformat;
1070 pix.width = dcmi->sd_bounds.width;
1071 pix.height = dcmi->sd_bounds.height;
1072 dcmi_set_sensor_format(dcmi, &pix);
1075 * Make the intersection between
1076 * sensor resolution
1077 * and crop request
1079 max_rect.top = 0;
1080 max_rect.left = 0;
1081 max_rect.width = pix.width;
1082 max_rect.height = pix.height;
1083 v4l2_rect_map_inside(&r, &max_rect);
1084 r.top = clamp_t(s32, r.top, 0, pix.height - r.height);
1085 r.left = clamp_t(s32, r.left, 0, pix.width - r.width);
1087 if (!((r.top == dcmi->sd_bounds.top) &&
1088 (r.left == dcmi->sd_bounds.left) &&
1089 (r.width == dcmi->sd_bounds.width) &&
1090 (r.height == dcmi->sd_bounds.height))) {
1091 /* Crop if request is different than sensor resolution */
1092 dcmi->do_crop = true;
1093 dcmi->crop = r;
1094 dev_dbg(dcmi->dev, "s_selection: crop %ux%u@(%u,%u) from %ux%u\n",
1095 r.width, r.height, r.left, r.top,
1096 pix.width, pix.height);
1097 } else {
1098 /* Disable crop */
1099 dcmi->do_crop = false;
1100 dev_dbg(dcmi->dev, "s_selection: crop is disabled\n");
1103 s->r = r;
1104 return 0;
1107 static int dcmi_querycap(struct file *file, void *priv,
1108 struct v4l2_capability *cap)
1110 strlcpy(cap->driver, DRV_NAME, sizeof(cap->driver));
1111 strlcpy(cap->card, "STM32 Camera Memory Interface",
1112 sizeof(cap->card));
1113 strlcpy(cap->bus_info, "platform:dcmi", sizeof(cap->bus_info));
1114 return 0;
1117 static int dcmi_enum_input(struct file *file, void *priv,
1118 struct v4l2_input *i)
1120 if (i->index != 0)
1121 return -EINVAL;
1123 i->type = V4L2_INPUT_TYPE_CAMERA;
1124 strlcpy(i->name, "Camera", sizeof(i->name));
1125 return 0;
1128 static int dcmi_g_input(struct file *file, void *priv, unsigned int *i)
1130 *i = 0;
1131 return 0;
1134 static int dcmi_s_input(struct file *file, void *priv, unsigned int i)
1136 if (i > 0)
1137 return -EINVAL;
1138 return 0;
1141 static int dcmi_enum_framesizes(struct file *file, void *fh,
1142 struct v4l2_frmsizeenum *fsize)
1144 struct stm32_dcmi *dcmi = video_drvdata(file);
1145 const struct dcmi_format *sd_fmt;
1146 struct v4l2_subdev_frame_size_enum fse = {
1147 .index = fsize->index,
1148 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1150 int ret;
1152 sd_fmt = find_format_by_fourcc(dcmi, fsize->pixel_format);
1153 if (!sd_fmt)
1154 return -EINVAL;
1156 fse.code = sd_fmt->mbus_code;
1158 ret = v4l2_subdev_call(dcmi->entity.subdev, pad, enum_frame_size,
1159 NULL, &fse);
1160 if (ret)
1161 return ret;
1163 fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1164 fsize->discrete.width = fse.max_width;
1165 fsize->discrete.height = fse.max_height;
1167 return 0;
1170 static int dcmi_enum_frameintervals(struct file *file, void *fh,
1171 struct v4l2_frmivalenum *fival)
1173 struct stm32_dcmi *dcmi = video_drvdata(file);
1174 const struct dcmi_format *sd_fmt;
1175 struct v4l2_subdev_frame_interval_enum fie = {
1176 .index = fival->index,
1177 .width = fival->width,
1178 .height = fival->height,
1179 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1181 int ret;
1183 sd_fmt = find_format_by_fourcc(dcmi, fival->pixel_format);
1184 if (!sd_fmt)
1185 return -EINVAL;
1187 fie.code = sd_fmt->mbus_code;
1189 ret = v4l2_subdev_call(dcmi->entity.subdev, pad,
1190 enum_frame_interval, NULL, &fie);
1191 if (ret)
1192 return ret;
1194 fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1195 fival->discrete = fie.interval;
1197 return 0;
1200 static const struct of_device_id stm32_dcmi_of_match[] = {
1201 { .compatible = "st,stm32-dcmi"},
1202 { /* end node */ },
1204 MODULE_DEVICE_TABLE(of, stm32_dcmi_of_match);
1206 static int dcmi_open(struct file *file)
1208 struct stm32_dcmi *dcmi = video_drvdata(file);
1209 struct v4l2_subdev *sd = dcmi->entity.subdev;
1210 int ret;
1212 if (mutex_lock_interruptible(&dcmi->lock))
1213 return -ERESTARTSYS;
1215 ret = v4l2_fh_open(file);
1216 if (ret < 0)
1217 goto unlock;
1219 if (!v4l2_fh_is_singular_file(file))
1220 goto fh_rel;
1222 ret = v4l2_subdev_call(sd, core, s_power, 1);
1223 if (ret < 0 && ret != -ENOIOCTLCMD)
1224 goto fh_rel;
1226 ret = dcmi_set_fmt(dcmi, &dcmi->fmt);
1227 if (ret)
1228 v4l2_subdev_call(sd, core, s_power, 0);
1229 fh_rel:
1230 if (ret)
1231 v4l2_fh_release(file);
1232 unlock:
1233 mutex_unlock(&dcmi->lock);
1234 return ret;
1237 static int dcmi_release(struct file *file)
1239 struct stm32_dcmi *dcmi = video_drvdata(file);
1240 struct v4l2_subdev *sd = dcmi->entity.subdev;
1241 bool fh_singular;
1242 int ret;
1244 mutex_lock(&dcmi->lock);
1246 fh_singular = v4l2_fh_is_singular_file(file);
1248 ret = _vb2_fop_release(file, NULL);
1250 if (fh_singular)
1251 v4l2_subdev_call(sd, core, s_power, 0);
1253 mutex_unlock(&dcmi->lock);
1255 return ret;
1258 static const struct v4l2_ioctl_ops dcmi_ioctl_ops = {
1259 .vidioc_querycap = dcmi_querycap,
1261 .vidioc_try_fmt_vid_cap = dcmi_try_fmt_vid_cap,
1262 .vidioc_g_fmt_vid_cap = dcmi_g_fmt_vid_cap,
1263 .vidioc_s_fmt_vid_cap = dcmi_s_fmt_vid_cap,
1264 .vidioc_enum_fmt_vid_cap = dcmi_enum_fmt_vid_cap,
1265 .vidioc_g_selection = dcmi_g_selection,
1266 .vidioc_s_selection = dcmi_s_selection,
1268 .vidioc_enum_input = dcmi_enum_input,
1269 .vidioc_g_input = dcmi_g_input,
1270 .vidioc_s_input = dcmi_s_input,
1272 .vidioc_enum_framesizes = dcmi_enum_framesizes,
1273 .vidioc_enum_frameintervals = dcmi_enum_frameintervals,
1275 .vidioc_reqbufs = vb2_ioctl_reqbufs,
1276 .vidioc_create_bufs = vb2_ioctl_create_bufs,
1277 .vidioc_querybuf = vb2_ioctl_querybuf,
1278 .vidioc_qbuf = vb2_ioctl_qbuf,
1279 .vidioc_dqbuf = vb2_ioctl_dqbuf,
1280 .vidioc_expbuf = vb2_ioctl_expbuf,
1281 .vidioc_prepare_buf = vb2_ioctl_prepare_buf,
1282 .vidioc_streamon = vb2_ioctl_streamon,
1283 .vidioc_streamoff = vb2_ioctl_streamoff,
1285 .vidioc_log_status = v4l2_ctrl_log_status,
1286 .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1287 .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1290 static const struct v4l2_file_operations dcmi_fops = {
1291 .owner = THIS_MODULE,
1292 .unlocked_ioctl = video_ioctl2,
1293 .open = dcmi_open,
1294 .release = dcmi_release,
1295 .poll = vb2_fop_poll,
1296 .mmap = vb2_fop_mmap,
1297 #ifndef CONFIG_MMU
1298 .get_unmapped_area = vb2_fop_get_unmapped_area,
1299 #endif
1300 .read = vb2_fop_read,
1303 static int dcmi_set_default_fmt(struct stm32_dcmi *dcmi)
1305 struct v4l2_format f = {
1306 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1307 .fmt.pix = {
1308 .width = CIF_WIDTH,
1309 .height = CIF_HEIGHT,
1310 .field = V4L2_FIELD_NONE,
1311 .pixelformat = dcmi->sd_formats[0]->fourcc,
1314 int ret;
1316 ret = dcmi_try_fmt(dcmi, &f, NULL, NULL);
1317 if (ret)
1318 return ret;
1319 dcmi->sd_format = dcmi->sd_formats[0];
1320 dcmi->fmt = f;
1321 return 0;
1324 static const struct dcmi_format dcmi_formats[] = {
1326 .fourcc = V4L2_PIX_FMT_RGB565,
1327 .mbus_code = MEDIA_BUS_FMT_RGB565_2X8_LE,
1328 .bpp = 2,
1329 }, {
1330 .fourcc = V4L2_PIX_FMT_YUYV,
1331 .mbus_code = MEDIA_BUS_FMT_YUYV8_2X8,
1332 .bpp = 2,
1333 }, {
1334 .fourcc = V4L2_PIX_FMT_UYVY,
1335 .mbus_code = MEDIA_BUS_FMT_UYVY8_2X8,
1336 .bpp = 2,
1340 static int dcmi_formats_init(struct stm32_dcmi *dcmi)
1342 const struct dcmi_format *sd_fmts[ARRAY_SIZE(dcmi_formats)];
1343 unsigned int num_fmts = 0, i, j;
1344 struct v4l2_subdev *subdev = dcmi->entity.subdev;
1345 struct v4l2_subdev_mbus_code_enum mbus_code = {
1346 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1349 while (!v4l2_subdev_call(subdev, pad, enum_mbus_code,
1350 NULL, &mbus_code)) {
1351 for (i = 0; i < ARRAY_SIZE(dcmi_formats); i++) {
1352 if (dcmi_formats[i].mbus_code != mbus_code.code)
1353 continue;
1355 /* Code supported, have we got this fourcc yet? */
1356 for (j = 0; j < num_fmts; j++)
1357 if (sd_fmts[j]->fourcc ==
1358 dcmi_formats[i].fourcc)
1359 /* Already available */
1360 break;
1361 if (j == num_fmts)
1362 /* New */
1363 sd_fmts[num_fmts++] = dcmi_formats + i;
1365 mbus_code.index++;
1368 if (!num_fmts)
1369 return -ENXIO;
1371 dcmi->num_of_sd_formats = num_fmts;
1372 dcmi->sd_formats = devm_kcalloc(dcmi->dev,
1373 num_fmts, sizeof(struct dcmi_format *),
1374 GFP_KERNEL);
1375 if (!dcmi->sd_formats) {
1376 dev_err(dcmi->dev, "Could not allocate memory\n");
1377 return -ENOMEM;
1380 memcpy(dcmi->sd_formats, sd_fmts,
1381 num_fmts * sizeof(struct dcmi_format *));
1382 dcmi->sd_format = dcmi->sd_formats[0];
1384 return 0;
1387 static int dcmi_framesizes_init(struct stm32_dcmi *dcmi)
1389 unsigned int num_fsize = 0;
1390 struct v4l2_subdev *subdev = dcmi->entity.subdev;
1391 struct v4l2_subdev_frame_size_enum fse = {
1392 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1393 .code = dcmi->sd_format->mbus_code,
1395 unsigned int ret;
1396 unsigned int i;
1398 /* Allocate discrete framesizes array */
1399 while (!v4l2_subdev_call(subdev, pad, enum_frame_size,
1400 NULL, &fse))
1401 fse.index++;
1403 num_fsize = fse.index;
1404 if (!num_fsize)
1405 return 0;
1407 dcmi->num_of_sd_framesizes = num_fsize;
1408 dcmi->sd_framesizes = devm_kcalloc(dcmi->dev, num_fsize,
1409 sizeof(struct dcmi_framesize),
1410 GFP_KERNEL);
1411 if (!dcmi->sd_framesizes) {
1412 dev_err(dcmi->dev, "Could not allocate memory\n");
1413 return -ENOMEM;
1416 /* Fill array with sensor supported framesizes */
1417 dev_dbg(dcmi->dev, "Sensor supports %u frame sizes:\n", num_fsize);
1418 for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
1419 fse.index = i;
1420 ret = v4l2_subdev_call(subdev, pad, enum_frame_size,
1421 NULL, &fse);
1422 if (ret)
1423 return ret;
1424 dcmi->sd_framesizes[fse.index].width = fse.max_width;
1425 dcmi->sd_framesizes[fse.index].height = fse.max_height;
1426 dev_dbg(dcmi->dev, "%ux%u\n", fse.max_width, fse.max_height);
1429 return 0;
1432 static int dcmi_graph_notify_complete(struct v4l2_async_notifier *notifier)
1434 struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1435 int ret;
1437 dcmi->vdev->ctrl_handler = dcmi->entity.subdev->ctrl_handler;
1438 ret = dcmi_formats_init(dcmi);
1439 if (ret) {
1440 dev_err(dcmi->dev, "No supported mediabus format found\n");
1441 return ret;
1444 ret = dcmi_framesizes_init(dcmi);
1445 if (ret) {
1446 dev_err(dcmi->dev, "Could not initialize framesizes\n");
1447 return ret;
1450 ret = dcmi_get_sensor_bounds(dcmi, &dcmi->sd_bounds);
1451 if (ret) {
1452 dev_err(dcmi->dev, "Could not get sensor bounds\n");
1453 return ret;
1456 ret = dcmi_set_default_fmt(dcmi);
1457 if (ret) {
1458 dev_err(dcmi->dev, "Could not set default format\n");
1459 return ret;
1462 ret = video_register_device(dcmi->vdev, VFL_TYPE_GRABBER, -1);
1463 if (ret) {
1464 dev_err(dcmi->dev, "Failed to register video device\n");
1465 return ret;
1468 dev_dbg(dcmi->dev, "Device registered as %s\n",
1469 video_device_node_name(dcmi->vdev));
1470 return 0;
1473 static void dcmi_graph_notify_unbind(struct v4l2_async_notifier *notifier,
1474 struct v4l2_subdev *sd,
1475 struct v4l2_async_subdev *asd)
1477 struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1479 dev_dbg(dcmi->dev, "Removing %s\n", video_device_node_name(dcmi->vdev));
1481 /* Checks internaly if vdev has been init or not */
1482 video_unregister_device(dcmi->vdev);
1485 static int dcmi_graph_notify_bound(struct v4l2_async_notifier *notifier,
1486 struct v4l2_subdev *subdev,
1487 struct v4l2_async_subdev *asd)
1489 struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1491 dev_dbg(dcmi->dev, "Subdev %s bound\n", subdev->name);
1493 dcmi->entity.subdev = subdev;
1495 return 0;
1498 static const struct v4l2_async_notifier_operations dcmi_graph_notify_ops = {
1499 .bound = dcmi_graph_notify_bound,
1500 .unbind = dcmi_graph_notify_unbind,
1501 .complete = dcmi_graph_notify_complete,
1504 static int dcmi_graph_parse(struct stm32_dcmi *dcmi, struct device_node *node)
1506 struct device_node *ep = NULL;
1507 struct device_node *remote;
1509 while (1) {
1510 ep = of_graph_get_next_endpoint(node, ep);
1511 if (!ep)
1512 return -EINVAL;
1514 remote = of_graph_get_remote_port_parent(ep);
1515 if (!remote) {
1516 of_node_put(ep);
1517 return -EINVAL;
1520 /* Remote node to connect */
1521 dcmi->entity.node = remote;
1522 dcmi->entity.asd.match_type = V4L2_ASYNC_MATCH_FWNODE;
1523 dcmi->entity.asd.match.fwnode = of_fwnode_handle(remote);
1524 return 0;
1528 static int dcmi_graph_init(struct stm32_dcmi *dcmi)
1530 struct v4l2_async_subdev **subdevs = NULL;
1531 int ret;
1533 /* Parse the graph to extract a list of subdevice DT nodes. */
1534 ret = dcmi_graph_parse(dcmi, dcmi->dev->of_node);
1535 if (ret < 0) {
1536 dev_err(dcmi->dev, "Graph parsing failed\n");
1537 return ret;
1540 /* Register the subdevices notifier. */
1541 subdevs = devm_kzalloc(dcmi->dev, sizeof(*subdevs), GFP_KERNEL);
1542 if (!subdevs) {
1543 of_node_put(dcmi->entity.node);
1544 return -ENOMEM;
1547 subdevs[0] = &dcmi->entity.asd;
1549 dcmi->notifier.subdevs = subdevs;
1550 dcmi->notifier.num_subdevs = 1;
1551 dcmi->notifier.ops = &dcmi_graph_notify_ops;
1553 ret = v4l2_async_notifier_register(&dcmi->v4l2_dev, &dcmi->notifier);
1554 if (ret < 0) {
1555 dev_err(dcmi->dev, "Notifier registration failed\n");
1556 of_node_put(dcmi->entity.node);
1557 return ret;
1560 return 0;
1563 static int dcmi_probe(struct platform_device *pdev)
1565 struct device_node *np = pdev->dev.of_node;
1566 const struct of_device_id *match = NULL;
1567 struct v4l2_fwnode_endpoint ep;
1568 struct stm32_dcmi *dcmi;
1569 struct vb2_queue *q;
1570 struct dma_chan *chan;
1571 struct clk *mclk;
1572 int irq;
1573 int ret = 0;
1575 match = of_match_device(of_match_ptr(stm32_dcmi_of_match), &pdev->dev);
1576 if (!match) {
1577 dev_err(&pdev->dev, "Could not find a match in devicetree\n");
1578 return -ENODEV;
1581 dcmi = devm_kzalloc(&pdev->dev, sizeof(struct stm32_dcmi), GFP_KERNEL);
1582 if (!dcmi)
1583 return -ENOMEM;
1585 dcmi->rstc = devm_reset_control_get_exclusive(&pdev->dev, NULL);
1586 if (IS_ERR(dcmi->rstc)) {
1587 dev_err(&pdev->dev, "Could not get reset control\n");
1588 return -ENODEV;
1591 /* Get bus characteristics from devicetree */
1592 np = of_graph_get_next_endpoint(np, NULL);
1593 if (!np) {
1594 dev_err(&pdev->dev, "Could not find the endpoint\n");
1595 of_node_put(np);
1596 return -ENODEV;
1599 ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(np), &ep);
1600 if (ret) {
1601 dev_err(&pdev->dev, "Could not parse the endpoint\n");
1602 of_node_put(np);
1603 return -ENODEV;
1606 if (ep.bus_type == V4L2_MBUS_CSI2) {
1607 dev_err(&pdev->dev, "CSI bus not supported\n");
1608 of_node_put(np);
1609 return -ENODEV;
1611 dcmi->bus.flags = ep.bus.parallel.flags;
1612 dcmi->bus.bus_width = ep.bus.parallel.bus_width;
1613 dcmi->bus.data_shift = ep.bus.parallel.data_shift;
1615 of_node_put(np);
1617 irq = platform_get_irq(pdev, 0);
1618 if (irq <= 0) {
1619 dev_err(&pdev->dev, "Could not get irq\n");
1620 return -ENODEV;
1623 dcmi->res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1624 if (!dcmi->res) {
1625 dev_err(&pdev->dev, "Could not get resource\n");
1626 return -ENODEV;
1629 dcmi->regs = devm_ioremap_resource(&pdev->dev, dcmi->res);
1630 if (IS_ERR(dcmi->regs)) {
1631 dev_err(&pdev->dev, "Could not map registers\n");
1632 return PTR_ERR(dcmi->regs);
1635 ret = devm_request_threaded_irq(&pdev->dev, irq, dcmi_irq_callback,
1636 dcmi_irq_thread, IRQF_ONESHOT,
1637 dev_name(&pdev->dev), dcmi);
1638 if (ret) {
1639 dev_err(&pdev->dev, "Unable to request irq %d\n", irq);
1640 return -ENODEV;
1643 mclk = devm_clk_get(&pdev->dev, "mclk");
1644 if (IS_ERR(mclk)) {
1645 dev_err(&pdev->dev, "Unable to get mclk\n");
1646 return PTR_ERR(mclk);
1649 chan = dma_request_slave_channel(&pdev->dev, "tx");
1650 if (!chan) {
1651 dev_info(&pdev->dev, "Unable to request DMA channel, defer probing\n");
1652 return -EPROBE_DEFER;
1655 ret = clk_prepare(mclk);
1656 if (ret) {
1657 dev_err(&pdev->dev, "Unable to prepare mclk %p\n", mclk);
1658 goto err_dma_release;
1661 spin_lock_init(&dcmi->irqlock);
1662 mutex_init(&dcmi->lock);
1663 init_completion(&dcmi->complete);
1664 INIT_LIST_HEAD(&dcmi->buffers);
1666 dcmi->dev = &pdev->dev;
1667 dcmi->mclk = mclk;
1668 dcmi->state = STOPPED;
1669 dcmi->dma_chan = chan;
1671 q = &dcmi->queue;
1673 /* Initialize the top-level structure */
1674 ret = v4l2_device_register(&pdev->dev, &dcmi->v4l2_dev);
1675 if (ret)
1676 goto err_clk_unprepare;
1678 dcmi->vdev = video_device_alloc();
1679 if (!dcmi->vdev) {
1680 ret = -ENOMEM;
1681 goto err_device_unregister;
1684 /* Video node */
1685 dcmi->vdev->fops = &dcmi_fops;
1686 dcmi->vdev->v4l2_dev = &dcmi->v4l2_dev;
1687 dcmi->vdev->queue = &dcmi->queue;
1688 strlcpy(dcmi->vdev->name, KBUILD_MODNAME, sizeof(dcmi->vdev->name));
1689 dcmi->vdev->release = video_device_release;
1690 dcmi->vdev->ioctl_ops = &dcmi_ioctl_ops;
1691 dcmi->vdev->lock = &dcmi->lock;
1692 dcmi->vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
1693 V4L2_CAP_READWRITE;
1694 video_set_drvdata(dcmi->vdev, dcmi);
1696 /* Buffer queue */
1697 q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1698 q->io_modes = VB2_MMAP | VB2_READ | VB2_DMABUF;
1699 q->lock = &dcmi->lock;
1700 q->drv_priv = dcmi;
1701 q->buf_struct_size = sizeof(struct dcmi_buf);
1702 q->ops = &dcmi_video_qops;
1703 q->mem_ops = &vb2_dma_contig_memops;
1704 q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1705 q->min_buffers_needed = 2;
1706 q->dev = &pdev->dev;
1708 ret = vb2_queue_init(q);
1709 if (ret < 0) {
1710 dev_err(&pdev->dev, "Failed to initialize vb2 queue\n");
1711 goto err_device_release;
1714 ret = dcmi_graph_init(dcmi);
1715 if (ret < 0)
1716 goto err_device_release;
1718 /* Reset device */
1719 ret = reset_control_assert(dcmi->rstc);
1720 if (ret) {
1721 dev_err(&pdev->dev, "Failed to assert the reset line\n");
1722 goto err_device_release;
1725 usleep_range(3000, 5000);
1727 ret = reset_control_deassert(dcmi->rstc);
1728 if (ret) {
1729 dev_err(&pdev->dev, "Failed to deassert the reset line\n");
1730 goto err_device_release;
1733 dev_info(&pdev->dev, "Probe done\n");
1735 platform_set_drvdata(pdev, dcmi);
1736 return 0;
1738 err_device_release:
1739 video_device_release(dcmi->vdev);
1740 err_device_unregister:
1741 v4l2_device_unregister(&dcmi->v4l2_dev);
1742 err_clk_unprepare:
1743 clk_unprepare(dcmi->mclk);
1744 err_dma_release:
1745 dma_release_channel(dcmi->dma_chan);
1747 return ret;
1750 static int dcmi_remove(struct platform_device *pdev)
1752 struct stm32_dcmi *dcmi = platform_get_drvdata(pdev);
1754 v4l2_async_notifier_unregister(&dcmi->notifier);
1755 v4l2_device_unregister(&dcmi->v4l2_dev);
1756 clk_unprepare(dcmi->mclk);
1757 dma_release_channel(dcmi->dma_chan);
1759 return 0;
1762 static struct platform_driver stm32_dcmi_driver = {
1763 .probe = dcmi_probe,
1764 .remove = dcmi_remove,
1765 .driver = {
1766 .name = DRV_NAME,
1767 .of_match_table = of_match_ptr(stm32_dcmi_of_match),
1771 module_platform_driver(stm32_dcmi_driver);
1773 MODULE_AUTHOR("Yannick Fertre <yannick.fertre@st.com>");
1774 MODULE_AUTHOR("Hugues Fruchet <hugues.fruchet@st.com>");
1775 MODULE_DESCRIPTION("STMicroelectronics STM32 Digital Camera Memory Interface driver");
1776 MODULE_LICENSE("GPL");
1777 MODULE_SUPPORTED_DEVICE("video");