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