1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * V4L2 Capture CSI Subdev for Freescale i.MX6UL/L / i.MX7 SOC
4  *
5  * Copyright (c) 2019 Linaro Ltd
6  *
7  */
8 
9 #include <linux/clk.h>
10 #include <linux/delay.h>
11 #include <linux/interrupt.h>
12 #include <linux/mfd/syscon.h>
13 #include <linux/module.h>
14 #include <linux/of_device.h>
15 #include <linux/of_graph.h>
16 #include <linux/pinctrl/consumer.h>
17 #include <linux/platform_device.h>
18 #include <linux/regmap.h>
19 #include <linux/slab.h>
20 #include <linux/spinlock.h>
21 #include <linux/types.h>
22 
23 #include <media/v4l2-device.h>
24 #include <media/v4l2-fwnode.h>
25 #include <media/v4l2-ioctl.h>
26 #include <media/v4l2-mc.h>
27 #include <media/v4l2-subdev.h>
28 #include <media/videobuf2-dma-contig.h>
29 
30 #define IMX7_CSI_PAD_SINK		0
31 #define IMX7_CSI_PAD_SRC		1
32 #define IMX7_CSI_PADS_NUM		2
33 
34 /* csi control reg 1 */
35 #define BIT_SWAP16_EN			BIT(31)
36 #define BIT_EXT_VSYNC			BIT(30)
37 #define BIT_EOF_INT_EN			BIT(29)
38 #define BIT_PRP_IF_EN			BIT(28)
39 #define BIT_CCIR_MODE			BIT(27)
40 #define BIT_COF_INT_EN			BIT(26)
41 #define BIT_SF_OR_INTEN			BIT(25)
42 #define BIT_RF_OR_INTEN			BIT(24)
43 #define BIT_SFF_DMA_DONE_INTEN		BIT(22)
44 #define BIT_STATFF_INTEN		BIT(21)
45 #define BIT_FB2_DMA_DONE_INTEN		BIT(20)
46 #define BIT_FB1_DMA_DONE_INTEN		BIT(19)
47 #define BIT_RXFF_INTEN			BIT(18)
48 #define BIT_SOF_POL			BIT(17)
49 #define BIT_SOF_INTEN			BIT(16)
50 #define BIT_MCLKDIV(n)			((n) << 12)
51 #define BIT_MCLKDIV_MASK		(0xf << 12)
52 #define BIT_HSYNC_POL			BIT(11)
53 #define BIT_CCIR_EN			BIT(10)
54 #define BIT_MCLKEN			BIT(9)
55 #define BIT_FCC				BIT(8)
56 #define BIT_PACK_DIR			BIT(7)
57 #define BIT_CLR_STATFIFO		BIT(6)
58 #define BIT_CLR_RXFIFO			BIT(5)
59 #define BIT_GCLK_MODE			BIT(4)
60 #define BIT_INV_DATA			BIT(3)
61 #define BIT_INV_PCLK			BIT(2)
62 #define BIT_REDGE			BIT(1)
63 #define BIT_PIXEL_BIT			BIT(0)
64 
65 /* control reg 2 */
66 #define BIT_DMA_BURST_TYPE_RFF_INCR4	(1 << 30)
67 #define BIT_DMA_BURST_TYPE_RFF_INCR8	(2 << 30)
68 #define BIT_DMA_BURST_TYPE_RFF_INCR16	(3 << 30)
69 #define BIT_DMA_BURST_TYPE_RFF_MASK	(3 << 30)
70 
71 /* control reg 3 */
72 #define BIT_FRMCNT(n)			((n) << 16)
73 #define BIT_FRMCNT_MASK			(0xffff << 16)
74 #define BIT_FRMCNT_RST			BIT(15)
75 #define BIT_DMA_REFLASH_RFF		BIT(14)
76 #define BIT_DMA_REFLASH_SFF		BIT(13)
77 #define BIT_DMA_REQ_EN_RFF		BIT(12)
78 #define BIT_DMA_REQ_EN_SFF		BIT(11)
79 #define BIT_STATFF_LEVEL(n)		((n) << 8)
80 #define BIT_STATFF_LEVEL_MASK		(0x7 << 8)
81 #define BIT_HRESP_ERR_EN		BIT(7)
82 #define BIT_RXFF_LEVEL(n)		((n) << 4)
83 #define BIT_RXFF_LEVEL_MASK		(0x7 << 4)
84 #define BIT_TWO_8BIT_SENSOR		BIT(3)
85 #define BIT_ZERO_PACK_EN		BIT(2)
86 #define BIT_ECC_INT_EN			BIT(1)
87 #define BIT_ECC_AUTO_EN			BIT(0)
88 
89 /* csi status reg */
90 #define BIT_ADDR_CH_ERR_INT		BIT(28)
91 #define BIT_FIELD0_INT			BIT(27)
92 #define BIT_FIELD1_INT			BIT(26)
93 #define BIT_SFF_OR_INT			BIT(25)
94 #define BIT_RFF_OR_INT			BIT(24)
95 #define BIT_DMA_TSF_DONE_SFF		BIT(22)
96 #define BIT_STATFF_INT			BIT(21)
97 #define BIT_DMA_TSF_DONE_FB2		BIT(20)
98 #define BIT_DMA_TSF_DONE_FB1		BIT(19)
99 #define BIT_RXFF_INT			BIT(18)
100 #define BIT_EOF_INT			BIT(17)
101 #define BIT_SOF_INT			BIT(16)
102 #define BIT_F2_INT			BIT(15)
103 #define BIT_F1_INT			BIT(14)
104 #define BIT_COF_INT			BIT(13)
105 #define BIT_HRESP_ERR_INT		BIT(7)
106 #define BIT_ECC_INT			BIT(1)
107 #define BIT_DRDY			BIT(0)
108 
109 /* csi image parameter reg */
110 #define BIT_IMAGE_WIDTH(n)		((n) << 16)
111 #define BIT_IMAGE_HEIGHT(n)		(n)
112 
113 /* csi control reg 18 */
114 #define BIT_CSI_HW_ENABLE		BIT(31)
115 #define BIT_MIPI_DATA_FORMAT_RAW8	(0x2a << 25)
116 #define BIT_MIPI_DATA_FORMAT_RAW10	(0x2b << 25)
117 #define BIT_MIPI_DATA_FORMAT_RAW12	(0x2c << 25)
118 #define BIT_MIPI_DATA_FORMAT_RAW14	(0x2d << 25)
119 #define BIT_MIPI_DATA_FORMAT_YUV422_8B	(0x1e << 25)
120 #define BIT_MIPI_DATA_FORMAT_MASK	(0x3f << 25)
121 #define BIT_DATA_FROM_MIPI		BIT(22)
122 #define BIT_MIPI_YU_SWAP		BIT(21)
123 #define BIT_MIPI_DOUBLE_CMPNT		BIT(20)
124 #define BIT_MASK_OPTION_FIRST_FRAME	(0 << 18)
125 #define BIT_MASK_OPTION_CSI_EN		(1 << 18)
126 #define BIT_MASK_OPTION_SECOND_FRAME	(2 << 18)
127 #define BIT_MASK_OPTION_ON_DATA		(3 << 18)
128 #define BIT_BASEADDR_CHG_ERR_EN		BIT(9)
129 #define BIT_BASEADDR_SWITCH_SEL		BIT(5)
130 #define BIT_BASEADDR_SWITCH_EN		BIT(4)
131 #define BIT_PARALLEL24_EN		BIT(3)
132 #define BIT_DEINTERLACE_EN		BIT(2)
133 #define BIT_TVDECODER_IN_EN		BIT(1)
134 #define BIT_NTSC_EN			BIT(0)
135 
136 #define CSI_MCLK_VF			1
137 #define CSI_MCLK_ENC			2
138 #define CSI_MCLK_RAW			4
139 #define CSI_MCLK_I2C			8
140 
141 #define CSI_CSICR1			0x00
142 #define CSI_CSICR2			0x04
143 #define CSI_CSICR3			0x08
144 #define CSI_STATFIFO			0x0c
145 #define CSI_CSIRXFIFO			0x10
146 #define CSI_CSIRXCNT			0x14
147 #define CSI_CSISR			0x18
148 
149 #define CSI_CSIDBG			0x1c
150 #define CSI_CSIDMASA_STATFIFO		0x20
151 #define CSI_CSIDMATS_STATFIFO		0x24
152 #define CSI_CSIDMASA_FB1		0x28
153 #define CSI_CSIDMASA_FB2		0x2c
154 #define CSI_CSIFBUF_PARA		0x30
155 #define CSI_CSIIMAG_PARA		0x34
156 
157 #define CSI_CSICR18			0x48
158 #define CSI_CSICR19			0x4c
159 
160 #define IMX7_CSI_VIDEO_NAME		"imx-capture"
161 /* In bytes, per queue */
162 #define IMX7_CSI_VIDEO_MEM_LIMIT	SZ_512M
163 #define IMX7_CSI_VIDEO_EOF_TIMEOUT	2000
164 
165 #define IMX7_CSI_DEF_MBUS_CODE		MEDIA_BUS_FMT_UYVY8_2X8
166 #define IMX7_CSI_DEF_PIX_FORMAT		V4L2_PIX_FMT_UYVY
167 #define IMX7_CSI_DEF_PIX_WIDTH		640
168 #define IMX7_CSI_DEF_PIX_HEIGHT		480
169 
170 enum imx_csi_model {
171 	IMX7_CSI_IMX7 = 0,
172 	IMX7_CSI_IMX8MQ,
173 };
174 
175 struct imx7_csi_pixfmt {
176 	/* the in-memory FourCC pixel format */
177 	u32     fourcc;
178 	/*
179 	 * the set of equivalent media bus codes for the fourcc.
180 	 * NOTE! codes pointer is NULL for in-memory-only formats.
181 	 */
182 	const u32 *codes;
183 	int     bpp;     /* total bpp */
184 	bool	yuv;
185 };
186 
187 struct imx7_csi_vb2_buffer {
188 	struct vb2_v4l2_buffer vbuf;
189 	struct list_head list;
190 };
191 
192 static inline struct imx7_csi_vb2_buffer *
193 to_imx7_csi_vb2_buffer(struct vb2_buffer *vb)
194 {
195 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
196 
197 	return container_of(vbuf, struct imx7_csi_vb2_buffer, vbuf);
198 }
199 
200 struct imx7_csi_dma_buf {
201 	void *virt;
202 	dma_addr_t dma_addr;
203 	unsigned long len;
204 };
205 
206 struct imx7_csi {
207 	struct device *dev;
208 
209 	/* Resources and locks */
210 	void __iomem *regbase;
211 	int irq;
212 	struct clk *mclk;
213 
214 	spinlock_t irqlock; /* Protects last_eof */
215 
216 	/* Media and V4L2 device */
217 	struct media_device mdev;
218 	struct v4l2_device v4l2_dev;
219 	struct v4l2_async_notifier notifier;
220 	struct media_pipeline pipe;
221 
222 	struct v4l2_subdev *src_sd;
223 	bool is_csi2;
224 
225 	/* V4L2 subdev */
226 	struct v4l2_subdev sd;
227 	struct media_pad pad[IMX7_CSI_PADS_NUM];
228 
229 	/* Video device */
230 	struct video_device *vdev;		/* Video device */
231 	struct media_pad vdev_pad;		/* Video device pad */
232 
233 	struct v4l2_pix_format vdev_fmt;	/* The user format */
234 	const struct imx7_csi_pixfmt *vdev_cc;
235 	struct v4l2_rect vdev_compose;		/* The compose rectangle */
236 
237 	struct mutex vdev_mutex;		/* Protect vdev operations */
238 
239 	struct vb2_queue q;			/* The videobuf2 queue */
240 	struct list_head ready_q;		/* List of queued buffers */
241 	spinlock_t q_lock;			/* Protect ready_q */
242 
243 	/* Buffers and streaming state */
244 	struct imx7_csi_vb2_buffer *active_vb2_buf[2];
245 	struct imx7_csi_dma_buf underrun_buf;
246 
247 	bool is_streaming;
248 	int buf_num;
249 	u32 frame_sequence;
250 
251 	bool last_eof;
252 	struct completion last_eof_completion;
253 
254 	enum imx_csi_model model;
255 };
256 
257 static struct imx7_csi *
258 imx7_csi_notifier_to_dev(struct v4l2_async_notifier *n)
259 {
260 	return container_of(n, struct imx7_csi, notifier);
261 }
262 
263 /* -----------------------------------------------------------------------------
264  * Hardware Configuration
265  */
266 
267 static u32 imx7_csi_reg_read(struct imx7_csi *csi, unsigned int offset)
268 {
269 	return readl(csi->regbase + offset);
270 }
271 
272 static void imx7_csi_reg_write(struct imx7_csi *csi, unsigned int value,
273 			       unsigned int offset)
274 {
275 	writel(value, csi->regbase + offset);
276 }
277 
278 static u32 imx7_csi_irq_clear(struct imx7_csi *csi)
279 {
280 	u32 isr;
281 
282 	isr = imx7_csi_reg_read(csi, CSI_CSISR);
283 	imx7_csi_reg_write(csi, isr, CSI_CSISR);
284 
285 	return isr;
286 }
287 
288 static void imx7_csi_init_default(struct imx7_csi *csi)
289 {
290 	imx7_csi_reg_write(csi, BIT_SOF_POL | BIT_REDGE | BIT_GCLK_MODE |
291 			   BIT_HSYNC_POL | BIT_FCC | BIT_MCLKDIV(1) |
292 			   BIT_MCLKEN, CSI_CSICR1);
293 	imx7_csi_reg_write(csi, 0, CSI_CSICR2);
294 	imx7_csi_reg_write(csi, BIT_FRMCNT_RST, CSI_CSICR3);
295 
296 	imx7_csi_reg_write(csi, BIT_IMAGE_WIDTH(IMX7_CSI_DEF_PIX_WIDTH) |
297 			   BIT_IMAGE_HEIGHT(IMX7_CSI_DEF_PIX_HEIGHT),
298 			   CSI_CSIIMAG_PARA);
299 
300 	imx7_csi_reg_write(csi, BIT_DMA_REFLASH_RFF, CSI_CSICR3);
301 }
302 
303 static void imx7_csi_hw_enable_irq(struct imx7_csi *csi)
304 {
305 	u32 cr1 = imx7_csi_reg_read(csi, CSI_CSICR1);
306 
307 	cr1 |= BIT_RFF_OR_INT;
308 	cr1 |= BIT_FB1_DMA_DONE_INTEN;
309 	cr1 |= BIT_FB2_DMA_DONE_INTEN;
310 
311 	imx7_csi_reg_write(csi, cr1, CSI_CSICR1);
312 }
313 
314 static void imx7_csi_hw_disable_irq(struct imx7_csi *csi)
315 {
316 	u32 cr1 = imx7_csi_reg_read(csi, CSI_CSICR1);
317 
318 	cr1 &= ~BIT_RFF_OR_INT;
319 	cr1 &= ~BIT_FB1_DMA_DONE_INTEN;
320 	cr1 &= ~BIT_FB2_DMA_DONE_INTEN;
321 
322 	imx7_csi_reg_write(csi, cr1, CSI_CSICR1);
323 }
324 
325 static void imx7_csi_hw_enable(struct imx7_csi *csi)
326 {
327 	u32 cr = imx7_csi_reg_read(csi, CSI_CSICR18);
328 
329 	cr |= BIT_CSI_HW_ENABLE;
330 
331 	imx7_csi_reg_write(csi, cr, CSI_CSICR18);
332 }
333 
334 static void imx7_csi_hw_disable(struct imx7_csi *csi)
335 {
336 	u32 cr = imx7_csi_reg_read(csi, CSI_CSICR18);
337 
338 	cr &= ~BIT_CSI_HW_ENABLE;
339 
340 	imx7_csi_reg_write(csi, cr, CSI_CSICR18);
341 }
342 
343 static void imx7_csi_dma_reflash(struct imx7_csi *csi)
344 {
345 	u32 cr3;
346 
347 	cr3 = imx7_csi_reg_read(csi, CSI_CSICR3);
348 	cr3 |= BIT_DMA_REFLASH_RFF;
349 	imx7_csi_reg_write(csi, cr3, CSI_CSICR3);
350 }
351 
352 static void imx7_csi_rx_fifo_clear(struct imx7_csi *csi)
353 {
354 	u32 cr1 = imx7_csi_reg_read(csi, CSI_CSICR1) & ~BIT_FCC;
355 
356 	imx7_csi_reg_write(csi, cr1, CSI_CSICR1);
357 	imx7_csi_reg_write(csi, cr1 | BIT_CLR_RXFIFO, CSI_CSICR1);
358 	imx7_csi_reg_write(csi, cr1 | BIT_FCC, CSI_CSICR1);
359 }
360 
361 static void imx7_csi_dmareq_rff_enable(struct imx7_csi *csi)
362 {
363 	u32 cr3 = imx7_csi_reg_read(csi, CSI_CSICR3);
364 
365 	cr3 |= BIT_DMA_REQ_EN_RFF;
366 	cr3 |= BIT_HRESP_ERR_EN;
367 	cr3 &= ~BIT_RXFF_LEVEL_MASK;
368 	cr3 |= BIT_RXFF_LEVEL(2);
369 
370 	imx7_csi_reg_write(csi, cr3, CSI_CSICR3);
371 }
372 
373 static void imx7_csi_dmareq_rff_disable(struct imx7_csi *csi)
374 {
375 	u32 cr3 = imx7_csi_reg_read(csi, CSI_CSICR3);
376 
377 	cr3 &= ~BIT_DMA_REQ_EN_RFF;
378 	cr3 &= ~BIT_HRESP_ERR_EN;
379 	imx7_csi_reg_write(csi, cr3, CSI_CSICR3);
380 }
381 
382 static void imx7_csi_update_buf(struct imx7_csi *csi, dma_addr_t dma_addr,
383 				int buf_num)
384 {
385 	if (buf_num == 1)
386 		imx7_csi_reg_write(csi, dma_addr, CSI_CSIDMASA_FB2);
387 	else
388 		imx7_csi_reg_write(csi, dma_addr, CSI_CSIDMASA_FB1);
389 }
390 
391 static struct imx7_csi_vb2_buffer *imx7_csi_video_next_buf(struct imx7_csi *csi);
392 
393 static void imx7_csi_setup_vb2_buf(struct imx7_csi *csi)
394 {
395 	struct imx7_csi_vb2_buffer *buf;
396 	struct vb2_buffer *vb2_buf;
397 	int i;
398 
399 	for (i = 0; i < 2; i++) {
400 		dma_addr_t dma_addr;
401 
402 		buf = imx7_csi_video_next_buf(csi);
403 		if (buf) {
404 			csi->active_vb2_buf[i] = buf;
405 			vb2_buf = &buf->vbuf.vb2_buf;
406 			dma_addr = vb2_dma_contig_plane_dma_addr(vb2_buf, 0);
407 		} else {
408 			csi->active_vb2_buf[i] = NULL;
409 			dma_addr = csi->underrun_buf.dma_addr;
410 		}
411 
412 		imx7_csi_update_buf(csi, dma_addr, i);
413 	}
414 }
415 
416 static void imx7_csi_dma_unsetup_vb2_buf(struct imx7_csi *csi,
417 					 enum vb2_buffer_state return_status)
418 {
419 	struct imx7_csi_vb2_buffer *buf;
420 	int i;
421 
422 	/* return any remaining active frames with return_status */
423 	for (i = 0; i < 2; i++) {
424 		buf = csi->active_vb2_buf[i];
425 		if (buf) {
426 			struct vb2_buffer *vb = &buf->vbuf.vb2_buf;
427 
428 			vb->timestamp = ktime_get_ns();
429 			vb2_buffer_done(vb, return_status);
430 			csi->active_vb2_buf[i] = NULL;
431 		}
432 	}
433 }
434 
435 static void imx7_csi_free_dma_buf(struct imx7_csi *csi,
436 				  struct imx7_csi_dma_buf *buf)
437 {
438 	if (buf->virt)
439 		dma_free_coherent(csi->dev, buf->len, buf->virt, buf->dma_addr);
440 
441 	buf->virt = NULL;
442 	buf->dma_addr = 0;
443 }
444 
445 static int imx7_csi_alloc_dma_buf(struct imx7_csi *csi,
446 				  struct imx7_csi_dma_buf *buf, int size)
447 {
448 	imx7_csi_free_dma_buf(csi, buf);
449 
450 	buf->len = PAGE_ALIGN(size);
451 	buf->virt = dma_alloc_coherent(csi->dev, buf->len, &buf->dma_addr,
452 				       GFP_DMA | GFP_KERNEL);
453 	if (!buf->virt)
454 		return -ENOMEM;
455 
456 	return 0;
457 }
458 
459 static int imx7_csi_dma_setup(struct imx7_csi *csi)
460 {
461 	int ret;
462 
463 	ret = imx7_csi_alloc_dma_buf(csi, &csi->underrun_buf,
464 				     csi->vdev_fmt.sizeimage);
465 	if (ret < 0) {
466 		v4l2_warn(&csi->sd, "consider increasing the CMA area\n");
467 		return ret;
468 	}
469 
470 	csi->frame_sequence = 0;
471 	csi->last_eof = false;
472 	init_completion(&csi->last_eof_completion);
473 
474 	imx7_csi_setup_vb2_buf(csi);
475 
476 	return 0;
477 }
478 
479 static void imx7_csi_dma_cleanup(struct imx7_csi *csi,
480 				 enum vb2_buffer_state return_status)
481 {
482 	imx7_csi_dma_unsetup_vb2_buf(csi, return_status);
483 	imx7_csi_free_dma_buf(csi, &csi->underrun_buf);
484 }
485 
486 static void imx7_csi_dma_stop(struct imx7_csi *csi)
487 {
488 	unsigned long timeout_jiffies;
489 	unsigned long flags;
490 	int ret;
491 
492 	/* mark next EOF interrupt as the last before stream off */
493 	spin_lock_irqsave(&csi->irqlock, flags);
494 	csi->last_eof = true;
495 	spin_unlock_irqrestore(&csi->irqlock, flags);
496 
497 	/*
498 	 * and then wait for interrupt handler to mark completion.
499 	 */
500 	timeout_jiffies = msecs_to_jiffies(IMX7_CSI_VIDEO_EOF_TIMEOUT);
501 	ret = wait_for_completion_timeout(&csi->last_eof_completion,
502 					  timeout_jiffies);
503 	if (ret == 0)
504 		v4l2_warn(&csi->sd, "wait last EOF timeout\n");
505 
506 	imx7_csi_hw_disable_irq(csi);
507 }
508 
509 static void imx7_csi_configure(struct imx7_csi *csi,
510 			       struct v4l2_subdev_state *sd_state)
511 {
512 	struct v4l2_pix_format *out_pix = &csi->vdev_fmt;
513 	int width = out_pix->width;
514 	u32 stride = 0;
515 	u32 cr3 = BIT_FRMCNT_RST;
516 	u32 cr1, cr18;
517 
518 	cr18 = imx7_csi_reg_read(csi, CSI_CSICR18);
519 
520 	cr18 &= ~(BIT_CSI_HW_ENABLE | BIT_MIPI_DATA_FORMAT_MASK |
521 		  BIT_DATA_FROM_MIPI | BIT_MIPI_DOUBLE_CMPNT |
522 		  BIT_BASEADDR_CHG_ERR_EN | BIT_BASEADDR_SWITCH_SEL |
523 		  BIT_BASEADDR_SWITCH_EN | BIT_DEINTERLACE_EN);
524 
525 	if (out_pix->field == V4L2_FIELD_INTERLACED) {
526 		cr18 |= BIT_DEINTERLACE_EN;
527 		stride = out_pix->width;
528 	}
529 
530 	if (!csi->is_csi2) {
531 		cr1 = BIT_SOF_POL | BIT_REDGE | BIT_GCLK_MODE | BIT_HSYNC_POL
532 		    | BIT_FCC | BIT_MCLKDIV(1) | BIT_MCLKEN;
533 
534 		cr18 |= BIT_BASEADDR_SWITCH_EN | BIT_BASEADDR_SWITCH_SEL |
535 			BIT_BASEADDR_CHG_ERR_EN;
536 
537 		if (out_pix->pixelformat == V4L2_PIX_FMT_UYVY ||
538 		    out_pix->pixelformat == V4L2_PIX_FMT_YUYV)
539 			width *= 2;
540 	} else {
541 		const struct v4l2_mbus_framefmt *sink_fmt;
542 
543 		sink_fmt = v4l2_subdev_get_pad_format(&csi->sd, sd_state,
544 						      IMX7_CSI_PAD_SINK);
545 
546 		cr1 = BIT_SOF_POL | BIT_REDGE | BIT_HSYNC_POL | BIT_FCC
547 		    | BIT_MCLKDIV(1) | BIT_MCLKEN;
548 
549 		cr18 |= BIT_DATA_FROM_MIPI;
550 
551 		switch (sink_fmt->code) {
552 		case MEDIA_BUS_FMT_Y8_1X8:
553 		case MEDIA_BUS_FMT_SBGGR8_1X8:
554 		case MEDIA_BUS_FMT_SGBRG8_1X8:
555 		case MEDIA_BUS_FMT_SGRBG8_1X8:
556 		case MEDIA_BUS_FMT_SRGGB8_1X8:
557 			cr18 |= BIT_MIPI_DATA_FORMAT_RAW8;
558 			break;
559 		case MEDIA_BUS_FMT_Y10_1X10:
560 		case MEDIA_BUS_FMT_SBGGR10_1X10:
561 		case MEDIA_BUS_FMT_SGBRG10_1X10:
562 		case MEDIA_BUS_FMT_SGRBG10_1X10:
563 		case MEDIA_BUS_FMT_SRGGB10_1X10:
564 			cr3 |= BIT_TWO_8BIT_SENSOR;
565 			cr18 |= BIT_MIPI_DATA_FORMAT_RAW10;
566 			break;
567 		case MEDIA_BUS_FMT_Y12_1X12:
568 		case MEDIA_BUS_FMT_SBGGR12_1X12:
569 		case MEDIA_BUS_FMT_SGBRG12_1X12:
570 		case MEDIA_BUS_FMT_SGRBG12_1X12:
571 		case MEDIA_BUS_FMT_SRGGB12_1X12:
572 			cr3 |= BIT_TWO_8BIT_SENSOR;
573 			cr18 |= BIT_MIPI_DATA_FORMAT_RAW12;
574 			break;
575 		case MEDIA_BUS_FMT_Y14_1X14:
576 		case MEDIA_BUS_FMT_SBGGR14_1X14:
577 		case MEDIA_BUS_FMT_SGBRG14_1X14:
578 		case MEDIA_BUS_FMT_SGRBG14_1X14:
579 		case MEDIA_BUS_FMT_SRGGB14_1X14:
580 			cr3 |= BIT_TWO_8BIT_SENSOR;
581 			cr18 |= BIT_MIPI_DATA_FORMAT_RAW14;
582 			break;
583 
584 		/*
585 		 * The CSI bridge has a 16-bit input bus. Depending on the
586 		 * connected source, data may be transmitted with 8 or 10 bits
587 		 * per clock sample (in bits [9:2] or [9:0] respectively) or
588 		 * with 16 bits per clock sample (in bits [15:0]). The data is
589 		 * then packed into a 32-bit FIFO (as shown in figure 13-11 of
590 		 * the i.MX8MM reference manual rev. 3).
591 		 *
592 		 * The data packing in a 32-bit FIFO input word is controlled by
593 		 * the CR3 TWO_8BIT_SENSOR field (also known as SENSOR_16BITS in
594 		 * the i.MX8MM reference manual). When set to 0, data packing
595 		 * groups four 8-bit input samples (bits [9:2]). When set to 1,
596 		 * data packing groups two 16-bit input samples (bits [15:0]).
597 		 *
598 		 * The register field CR18 MIPI_DOUBLE_CMPNT also needs to be
599 		 * configured according to the input format for YUV 4:2:2 data.
600 		 * The field controls the gasket between the CSI-2 receiver and
601 		 * the CSI bridge. On i.MX7 and i.MX8MM, the field must be set
602 		 * to 1 when the CSIS outputs 16-bit samples. On i.MX8MQ, the
603 		 * gasket ignores the MIPI_DOUBLE_CMPNT bit and YUV 4:2:2 always
604 		 * uses 16-bit samples. Setting MIPI_DOUBLE_CMPNT in that case
605 		 * has no effect, but doesn't cause any issue.
606 		 */
607 		case MEDIA_BUS_FMT_UYVY8_2X8:
608 		case MEDIA_BUS_FMT_YUYV8_2X8:
609 			cr18 |= BIT_MIPI_DATA_FORMAT_YUV422_8B;
610 			break;
611 		case MEDIA_BUS_FMT_UYVY8_1X16:
612 		case MEDIA_BUS_FMT_YUYV8_1X16:
613 			cr3 |= BIT_TWO_8BIT_SENSOR;
614 			cr18 |= BIT_MIPI_DATA_FORMAT_YUV422_8B |
615 				BIT_MIPI_DOUBLE_CMPNT;
616 			break;
617 		}
618 	}
619 
620 	imx7_csi_reg_write(csi, cr1, CSI_CSICR1);
621 	imx7_csi_reg_write(csi, BIT_DMA_BURST_TYPE_RFF_INCR16, CSI_CSICR2);
622 	imx7_csi_reg_write(csi, cr3, CSI_CSICR3);
623 	imx7_csi_reg_write(csi, cr18, CSI_CSICR18);
624 
625 	imx7_csi_reg_write(csi, (width * out_pix->height) >> 2, CSI_CSIRXCNT);
626 	imx7_csi_reg_write(csi, BIT_IMAGE_WIDTH(width) |
627 			   BIT_IMAGE_HEIGHT(out_pix->height),
628 			   CSI_CSIIMAG_PARA);
629 	imx7_csi_reg_write(csi, stride, CSI_CSIFBUF_PARA);
630 }
631 
632 static int imx7_csi_init(struct imx7_csi *csi,
633 			 struct v4l2_subdev_state *sd_state)
634 {
635 	int ret;
636 
637 	ret = clk_prepare_enable(csi->mclk);
638 	if (ret < 0)
639 		return ret;
640 
641 	imx7_csi_configure(csi, sd_state);
642 
643 	ret = imx7_csi_dma_setup(csi);
644 	if (ret < 0) {
645 		clk_disable_unprepare(csi->mclk);
646 		return ret;
647 	}
648 
649 	return 0;
650 }
651 
652 static void imx7_csi_deinit(struct imx7_csi *csi,
653 			    enum vb2_buffer_state return_status)
654 {
655 	imx7_csi_dma_cleanup(csi, return_status);
656 	imx7_csi_init_default(csi);
657 	imx7_csi_dmareq_rff_disable(csi);
658 	clk_disable_unprepare(csi->mclk);
659 }
660 
661 static void imx7_csi_baseaddr_switch_on_second_frame(struct imx7_csi *csi)
662 {
663 	u32 cr18 = imx7_csi_reg_read(csi, CSI_CSICR18);
664 
665 	cr18 |= BIT_BASEADDR_SWITCH_EN | BIT_BASEADDR_SWITCH_SEL |
666 		BIT_BASEADDR_CHG_ERR_EN;
667 	cr18 |= BIT_MASK_OPTION_SECOND_FRAME;
668 	imx7_csi_reg_write(csi, cr18, CSI_CSICR18);
669 }
670 
671 static void imx7_csi_enable(struct imx7_csi *csi)
672 {
673 	/* Clear the Rx FIFO and reflash the DMA controller. */
674 	imx7_csi_rx_fifo_clear(csi);
675 	imx7_csi_dma_reflash(csi);
676 
677 	usleep_range(2000, 3000);
678 
679 	/* Clear and enable the interrupts. */
680 	imx7_csi_irq_clear(csi);
681 	imx7_csi_hw_enable_irq(csi);
682 
683 	/* Enable the RxFIFO DMA and the CSI. */
684 	imx7_csi_dmareq_rff_enable(csi);
685 	imx7_csi_hw_enable(csi);
686 
687 	if (csi->model == IMX7_CSI_IMX8MQ)
688 		imx7_csi_baseaddr_switch_on_second_frame(csi);
689 }
690 
691 static void imx7_csi_disable(struct imx7_csi *csi)
692 {
693 	imx7_csi_dma_stop(csi);
694 
695 	imx7_csi_dmareq_rff_disable(csi);
696 
697 	imx7_csi_hw_disable_irq(csi);
698 
699 	imx7_csi_hw_disable(csi);
700 }
701 
702 /* -----------------------------------------------------------------------------
703  * Interrupt Handling
704  */
705 
706 static void imx7_csi_error_recovery(struct imx7_csi *csi)
707 {
708 	imx7_csi_hw_disable(csi);
709 
710 	imx7_csi_rx_fifo_clear(csi);
711 
712 	imx7_csi_dma_reflash(csi);
713 
714 	imx7_csi_hw_enable(csi);
715 }
716 
717 static void imx7_csi_vb2_buf_done(struct imx7_csi *csi)
718 {
719 	struct imx7_csi_vb2_buffer *done, *next;
720 	struct vb2_buffer *vb;
721 	dma_addr_t dma_addr;
722 
723 	done = csi->active_vb2_buf[csi->buf_num];
724 	if (done) {
725 		done->vbuf.field = csi->vdev_fmt.field;
726 		done->vbuf.sequence = csi->frame_sequence;
727 		vb = &done->vbuf.vb2_buf;
728 		vb->timestamp = ktime_get_ns();
729 		vb2_buffer_done(vb, VB2_BUF_STATE_DONE);
730 	}
731 	csi->frame_sequence++;
732 
733 	/* get next queued buffer */
734 	next = imx7_csi_video_next_buf(csi);
735 	if (next) {
736 		dma_addr = vb2_dma_contig_plane_dma_addr(&next->vbuf.vb2_buf, 0);
737 		csi->active_vb2_buf[csi->buf_num] = next;
738 	} else {
739 		dma_addr = csi->underrun_buf.dma_addr;
740 		csi->active_vb2_buf[csi->buf_num] = NULL;
741 	}
742 
743 	imx7_csi_update_buf(csi, dma_addr, csi->buf_num);
744 }
745 
746 static irqreturn_t imx7_csi_irq_handler(int irq, void *data)
747 {
748 	struct imx7_csi *csi =  data;
749 	u32 status;
750 
751 	spin_lock(&csi->irqlock);
752 
753 	status = imx7_csi_irq_clear(csi);
754 
755 	if (status & BIT_RFF_OR_INT) {
756 		dev_warn(csi->dev, "Rx fifo overflow\n");
757 		imx7_csi_error_recovery(csi);
758 	}
759 
760 	if (status & BIT_HRESP_ERR_INT) {
761 		dev_warn(csi->dev, "Hresponse error detected\n");
762 		imx7_csi_error_recovery(csi);
763 	}
764 
765 	if (status & BIT_ADDR_CH_ERR_INT) {
766 		imx7_csi_hw_disable(csi);
767 
768 		imx7_csi_dma_reflash(csi);
769 
770 		imx7_csi_hw_enable(csi);
771 	}
772 
773 	if ((status & BIT_DMA_TSF_DONE_FB1) &&
774 	    (status & BIT_DMA_TSF_DONE_FB2)) {
775 		/*
776 		 * For both FB1 and FB2 interrupter bits set case,
777 		 * CSI DMA is work in one of FB1 and FB2 buffer,
778 		 * but software can not know the state.
779 		 * Skip it to avoid base address updated
780 		 * when csi work in field0 and field1 will write to
781 		 * new base address.
782 		 */
783 	} else if (status & BIT_DMA_TSF_DONE_FB1) {
784 		csi->buf_num = 0;
785 	} else if (status & BIT_DMA_TSF_DONE_FB2) {
786 		csi->buf_num = 1;
787 	}
788 
789 	if ((status & BIT_DMA_TSF_DONE_FB1) ||
790 	    (status & BIT_DMA_TSF_DONE_FB2)) {
791 		imx7_csi_vb2_buf_done(csi);
792 
793 		if (csi->last_eof) {
794 			complete(&csi->last_eof_completion);
795 			csi->last_eof = false;
796 		}
797 	}
798 
799 	spin_unlock(&csi->irqlock);
800 
801 	return IRQ_HANDLED;
802 }
803 
804 /* -----------------------------------------------------------------------------
805  * Format Helpers
806  */
807 
808 #define IMX_BUS_FMTS(fmt...) (const u32[]) {fmt, 0}
809 
810 /*
811  * List of supported pixel formats for the subdevs. Keep V4L2_PIX_FMT_UYVY and
812  * MEDIA_BUS_FMT_UYVY8_2X8 first to match IMX7_CSI_DEF_PIX_FORMAT and
813  * IMX7_CSI_DEF_MBUS_CODE.
814  *
815  * TODO: Restrict the supported formats list based on the SoC integration.
816  *
817  * The CSI bridge can be configured to sample pixel components from the Rx queue
818  * in single (8bpp) or double (16bpp) component modes. Image format variants
819  * with different sample sizes (ie YUYV_2X8 vs YUYV_1X16) determine the pixel
820  * components sampling size per each clock cycle and their packing mode (see
821  * imx7_csi_configure() for details).
822  *
823  * As the CSI bridge can be interfaced with different IP blocks depending on the
824  * SoC model it is integrated on, the Rx queue sampling size should match the
825  * size of the samples transferred by the transmitting IP block. To avoid
826  * misconfigurations of the capture pipeline, the enumeration of the supported
827  * formats should be restricted to match the pixel source transmitting mode.
828  *
829  * Example: i.MX8MM SoC integrates the CSI bridge with the Samsung CSIS CSI-2
830  * receiver which operates in dual pixel sampling mode. The CSI bridge should
831  * only expose the 1X16 formats variant which instructs it to operate in dual
832  * pixel sampling mode. When the CSI bridge is instead integrated on an i.MX7,
833  * which supports both serial and parallel input, it should expose both
834  * variants.
835  *
836  * This currently only applies to YUYV formats, but other formats might need to
837  * be handled in the same way.
838  */
839 static const struct imx7_csi_pixfmt pixel_formats[] = {
840 	/*** YUV formats start here ***/
841 	{
842 		.fourcc	= V4L2_PIX_FMT_UYVY,
843 		.codes  = IMX_BUS_FMTS(
844 			MEDIA_BUS_FMT_UYVY8_2X8,
845 			MEDIA_BUS_FMT_UYVY8_1X16
846 		),
847 		.yuv	= true,
848 		.bpp    = 16,
849 	}, {
850 		.fourcc	= V4L2_PIX_FMT_YUYV,
851 		.codes  = IMX_BUS_FMTS(
852 			MEDIA_BUS_FMT_YUYV8_2X8,
853 			MEDIA_BUS_FMT_YUYV8_1X16
854 		),
855 		.yuv	= true,
856 		.bpp    = 16,
857 	},
858 	/*** raw bayer and grayscale formats start here ***/
859 	{
860 		.fourcc = V4L2_PIX_FMT_SBGGR8,
861 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SBGGR8_1X8),
862 		.bpp    = 8,
863 	}, {
864 		.fourcc = V4L2_PIX_FMT_SGBRG8,
865 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SGBRG8_1X8),
866 		.bpp    = 8,
867 	}, {
868 		.fourcc = V4L2_PIX_FMT_SGRBG8,
869 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SGRBG8_1X8),
870 		.bpp    = 8,
871 	}, {
872 		.fourcc = V4L2_PIX_FMT_SRGGB8,
873 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SRGGB8_1X8),
874 		.bpp    = 8,
875 	}, {
876 		.fourcc = V4L2_PIX_FMT_SBGGR10,
877 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SBGGR10_1X10),
878 		.bpp    = 16,
879 	}, {
880 		.fourcc = V4L2_PIX_FMT_SGBRG10,
881 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SGBRG10_1X10),
882 		.bpp    = 16,
883 	}, {
884 		.fourcc = V4L2_PIX_FMT_SGRBG10,
885 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SGRBG10_1X10),
886 		.bpp    = 16,
887 	}, {
888 		.fourcc = V4L2_PIX_FMT_SRGGB10,
889 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SRGGB10_1X10),
890 		.bpp    = 16,
891 	}, {
892 		.fourcc = V4L2_PIX_FMT_SBGGR12,
893 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SBGGR12_1X12),
894 		.bpp    = 16,
895 	}, {
896 		.fourcc = V4L2_PIX_FMT_SGBRG12,
897 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SGBRG12_1X12),
898 		.bpp    = 16,
899 	}, {
900 		.fourcc = V4L2_PIX_FMT_SGRBG12,
901 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SGRBG12_1X12),
902 		.bpp    = 16,
903 	}, {
904 		.fourcc = V4L2_PIX_FMT_SRGGB12,
905 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SRGGB12_1X12),
906 		.bpp    = 16,
907 	}, {
908 		.fourcc = V4L2_PIX_FMT_SBGGR14,
909 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SBGGR14_1X14),
910 		.bpp    = 16,
911 	}, {
912 		.fourcc = V4L2_PIX_FMT_SGBRG14,
913 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SGBRG14_1X14),
914 		.bpp    = 16,
915 	}, {
916 		.fourcc = V4L2_PIX_FMT_SGRBG14,
917 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SGRBG14_1X14),
918 		.bpp    = 16,
919 	}, {
920 		.fourcc = V4L2_PIX_FMT_SRGGB14,
921 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_SRGGB14_1X14),
922 		.bpp    = 16,
923 	}, {
924 		.fourcc = V4L2_PIX_FMT_GREY,
925 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_Y8_1X8),
926 		.bpp    = 8,
927 	}, {
928 		.fourcc = V4L2_PIX_FMT_Y10,
929 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_Y10_1X10),
930 		.bpp    = 16,
931 	}, {
932 		.fourcc = V4L2_PIX_FMT_Y12,
933 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_Y12_1X12),
934 		.bpp    = 16,
935 	}, {
936 		.fourcc = V4L2_PIX_FMT_Y14,
937 		.codes  = IMX_BUS_FMTS(MEDIA_BUS_FMT_Y14_1X14),
938 		.bpp    = 16,
939 	},
940 };
941 
942 /*
943  * Search in the pixel_formats[] array for an entry with the given fourcc
944  * return it.
945  */
946 static const struct imx7_csi_pixfmt *imx7_csi_find_pixel_format(u32 fourcc)
947 {
948 	unsigned int i;
949 
950 	for (i = 0; i < ARRAY_SIZE(pixel_formats); i++) {
951 		const struct imx7_csi_pixfmt *fmt = &pixel_formats[i];
952 
953 		if (fmt->fourcc == fourcc)
954 			return fmt;
955 	}
956 
957 	return NULL;
958 }
959 
960 /*
961  * Search in the pixel_formats[] array for an entry with the given media
962  * bus code and return it.
963  */
964 static const struct imx7_csi_pixfmt *imx7_csi_find_mbus_format(u32 code)
965 {
966 	unsigned int i;
967 
968 	for (i = 0; i < ARRAY_SIZE(pixel_formats); i++) {
969 		const struct imx7_csi_pixfmt *fmt = &pixel_formats[i];
970 		unsigned int j;
971 
972 		if (!fmt->codes)
973 			continue;
974 
975 		for (j = 0; fmt->codes[j]; j++) {
976 			if (code == fmt->codes[j])
977 				return fmt;
978 		}
979 	}
980 
981 	return NULL;
982 }
983 
984 /*
985  * Enumerate entries in the pixel_formats[] array that match the
986  * requested search criteria. Return the media-bus code that matches
987  * the search criteria at the requested match index.
988  *
989  * @code: The returned media-bus code that matches the search criteria at
990  *        the requested match index.
991  * @index: The requested match index.
992  */
993 static int imx7_csi_enum_mbus_formats(u32 *code, u32 index)
994 {
995 	unsigned int i;
996 
997 	for (i = 0; i < ARRAY_SIZE(pixel_formats); i++) {
998 		const struct imx7_csi_pixfmt *fmt = &pixel_formats[i];
999 		unsigned int j;
1000 
1001 		if (!fmt->codes)
1002 			continue;
1003 
1004 		for (j = 0; fmt->codes[j]; j++) {
1005 			if (index == 0) {
1006 				*code = fmt->codes[j];
1007 				return 0;
1008 			}
1009 
1010 			index--;
1011 		}
1012 	}
1013 
1014 	return -EINVAL;
1015 }
1016 
1017 /* -----------------------------------------------------------------------------
1018  * Video Capture Device - IOCTLs
1019  */
1020 
1021 static int imx7_csi_video_querycap(struct file *file, void *fh,
1022 				   struct v4l2_capability *cap)
1023 {
1024 	struct imx7_csi *csi = video_drvdata(file);
1025 
1026 	strscpy(cap->driver, IMX7_CSI_VIDEO_NAME, sizeof(cap->driver));
1027 	strscpy(cap->card, IMX7_CSI_VIDEO_NAME, sizeof(cap->card));
1028 	snprintf(cap->bus_info, sizeof(cap->bus_info),
1029 		 "platform:%s", dev_name(csi->dev));
1030 
1031 	return 0;
1032 }
1033 
1034 static int imx7_csi_video_enum_fmt_vid_cap(struct file *file, void *fh,
1035 					   struct v4l2_fmtdesc *f)
1036 {
1037 	unsigned int index = f->index;
1038 	unsigned int i;
1039 
1040 	for (i = 0; i < ARRAY_SIZE(pixel_formats); i++) {
1041 		const struct imx7_csi_pixfmt *fmt = &pixel_formats[i];
1042 
1043 		/*
1044 		 * If a media bus code is specified, only consider formats that
1045 		 * match it.
1046 		 */
1047 		if (f->mbus_code) {
1048 			unsigned int j;
1049 
1050 			if (!fmt->codes)
1051 				continue;
1052 
1053 			for (j = 0; fmt->codes[j]; j++) {
1054 				if (f->mbus_code == fmt->codes[j])
1055 					break;
1056 			}
1057 
1058 			if (!fmt->codes[j])
1059 				continue;
1060 		}
1061 
1062 		if (index == 0) {
1063 			f->pixelformat = fmt->fourcc;
1064 			return 0;
1065 		}
1066 
1067 		index--;
1068 	}
1069 
1070 	return -EINVAL;
1071 }
1072 
1073 static int imx7_csi_video_enum_framesizes(struct file *file, void *fh,
1074 					  struct v4l2_frmsizeenum *fsize)
1075 {
1076 	const struct imx7_csi_pixfmt *cc;
1077 
1078 	if (fsize->index > 0)
1079 		return -EINVAL;
1080 
1081 	cc = imx7_csi_find_pixel_format(fsize->pixel_format);
1082 	if (!cc)
1083 		return -EINVAL;
1084 
1085 	/*
1086 	 * TODO: The constraints are hardware-specific and may depend on the
1087 	 * pixel format. This should come from the driver using
1088 	 * imx_media_capture.
1089 	 */
1090 	fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS;
1091 	fsize->stepwise.min_width = 1;
1092 	fsize->stepwise.max_width = 65535;
1093 	fsize->stepwise.min_height = 1;
1094 	fsize->stepwise.max_height = 65535;
1095 	fsize->stepwise.step_width = 1;
1096 	fsize->stepwise.step_height = 1;
1097 
1098 	return 0;
1099 }
1100 
1101 static int imx7_csi_video_g_fmt_vid_cap(struct file *file, void *fh,
1102 					struct v4l2_format *f)
1103 {
1104 	struct imx7_csi *csi = video_drvdata(file);
1105 
1106 	f->fmt.pix = csi->vdev_fmt;
1107 
1108 	return 0;
1109 }
1110 
1111 static const struct imx7_csi_pixfmt *
1112 __imx7_csi_video_try_fmt(struct v4l2_pix_format *pixfmt,
1113 			 struct v4l2_rect *compose)
1114 {
1115 	const struct imx7_csi_pixfmt *cc;
1116 	u32 walign;
1117 
1118 	if (compose) {
1119 		compose->width = pixfmt->width;
1120 		compose->height = pixfmt->height;
1121 	}
1122 
1123 	/*
1124 	 * Find the pixel format, default to the first supported format if not
1125 	 * found.
1126 	 */
1127 	cc = imx7_csi_find_pixel_format(pixfmt->pixelformat);
1128 	if (!cc) {
1129 		pixfmt->pixelformat = IMX7_CSI_DEF_PIX_FORMAT;
1130 		cc = imx7_csi_find_pixel_format(pixfmt->pixelformat);
1131 	}
1132 
1133 	/*
1134 	 * The width alignment is 8 bytes as indicated by the
1135 	 * CSI_IMAG_PARA.IMAGE_WIDTH documentation. Convert it to pixels.
1136 	 *
1137 	 * TODO: Implement configurable stride support.
1138 	 */
1139 	walign = 8 * 8 / cc->bpp;
1140 	v4l_bound_align_image(&pixfmt->width, 1, 0xffff, walign,
1141 			      &pixfmt->height, 1, 0xffff, 1, 0);
1142 
1143 	pixfmt->bytesperline = pixfmt->width * cc->bpp / 8;
1144 	pixfmt->sizeimage = pixfmt->bytesperline * pixfmt->height;
1145 	pixfmt->field = V4L2_FIELD_NONE;
1146 
1147 	return cc;
1148 }
1149 
1150 static int imx7_csi_video_try_fmt_vid_cap(struct file *file, void *fh,
1151 					  struct v4l2_format *f)
1152 {
1153 	__imx7_csi_video_try_fmt(&f->fmt.pix, NULL);
1154 	return 0;
1155 }
1156 
1157 static int imx7_csi_video_s_fmt_vid_cap(struct file *file, void *fh,
1158 					struct v4l2_format *f)
1159 {
1160 	struct imx7_csi *csi = video_drvdata(file);
1161 	const struct imx7_csi_pixfmt *cc;
1162 
1163 	if (vb2_is_busy(&csi->q)) {
1164 		dev_err(csi->dev, "%s queue busy\n", __func__);
1165 		return -EBUSY;
1166 	}
1167 
1168 	cc = __imx7_csi_video_try_fmt(&f->fmt.pix, &csi->vdev_compose);
1169 
1170 	csi->vdev_cc = cc;
1171 	csi->vdev_fmt = f->fmt.pix;
1172 
1173 	return 0;
1174 }
1175 
1176 static int imx7_csi_video_g_selection(struct file *file, void *fh,
1177 				      struct v4l2_selection *s)
1178 {
1179 	struct imx7_csi *csi = video_drvdata(file);
1180 
1181 	if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1182 		return -EINVAL;
1183 
1184 	switch (s->target) {
1185 	case V4L2_SEL_TGT_COMPOSE:
1186 	case V4L2_SEL_TGT_COMPOSE_DEFAULT:
1187 	case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1188 		/* The compose rectangle is fixed to the source format. */
1189 		s->r = csi->vdev_compose;
1190 		break;
1191 	case V4L2_SEL_TGT_COMPOSE_PADDED:
1192 		/*
1193 		 * The hardware writes with a configurable but fixed DMA burst
1194 		 * size. If the source format width is not burst size aligned,
1195 		 * the written frame contains padding to the right.
1196 		 */
1197 		s->r.left = 0;
1198 		s->r.top = 0;
1199 		s->r.width = csi->vdev_fmt.width;
1200 		s->r.height = csi->vdev_fmt.height;
1201 		break;
1202 	default:
1203 		return -EINVAL;
1204 	}
1205 
1206 	return 0;
1207 }
1208 
1209 static const struct v4l2_ioctl_ops imx7_csi_video_ioctl_ops = {
1210 	.vidioc_querycap		= imx7_csi_video_querycap,
1211 
1212 	.vidioc_enum_fmt_vid_cap	= imx7_csi_video_enum_fmt_vid_cap,
1213 	.vidioc_enum_framesizes		= imx7_csi_video_enum_framesizes,
1214 
1215 	.vidioc_g_fmt_vid_cap		= imx7_csi_video_g_fmt_vid_cap,
1216 	.vidioc_try_fmt_vid_cap		= imx7_csi_video_try_fmt_vid_cap,
1217 	.vidioc_s_fmt_vid_cap		= imx7_csi_video_s_fmt_vid_cap,
1218 
1219 	.vidioc_g_selection		= imx7_csi_video_g_selection,
1220 
1221 	.vidioc_reqbufs			= vb2_ioctl_reqbufs,
1222 	.vidioc_create_bufs		= vb2_ioctl_create_bufs,
1223 	.vidioc_prepare_buf		= vb2_ioctl_prepare_buf,
1224 	.vidioc_querybuf		= vb2_ioctl_querybuf,
1225 	.vidioc_qbuf			= vb2_ioctl_qbuf,
1226 	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
1227 	.vidioc_expbuf			= vb2_ioctl_expbuf,
1228 	.vidioc_streamon		= vb2_ioctl_streamon,
1229 	.vidioc_streamoff		= vb2_ioctl_streamoff,
1230 };
1231 
1232 /* -----------------------------------------------------------------------------
1233  * Video Capture Device - Queue Operations
1234  */
1235 
1236 static int imx7_csi_video_queue_setup(struct vb2_queue *vq,
1237 				      unsigned int *nbuffers,
1238 				      unsigned int *nplanes,
1239 				      unsigned int sizes[],
1240 				      struct device *alloc_devs[])
1241 {
1242 	struct imx7_csi *csi = vb2_get_drv_priv(vq);
1243 	struct v4l2_pix_format *pix = &csi->vdev_fmt;
1244 	unsigned int count = *nbuffers;
1245 
1246 	if (vq->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1247 		return -EINVAL;
1248 
1249 	if (*nplanes) {
1250 		if (*nplanes != 1 || sizes[0] < pix->sizeimage)
1251 			return -EINVAL;
1252 		count += vq->num_buffers;
1253 	}
1254 
1255 	count = min_t(__u32, IMX7_CSI_VIDEO_MEM_LIMIT / pix->sizeimage, count);
1256 
1257 	if (*nplanes)
1258 		*nbuffers = (count < vq->num_buffers) ? 0 :
1259 			count - vq->num_buffers;
1260 	else
1261 		*nbuffers = count;
1262 
1263 	*nplanes = 1;
1264 	sizes[0] = pix->sizeimage;
1265 
1266 	return 0;
1267 }
1268 
1269 static int imx7_csi_video_buf_init(struct vb2_buffer *vb)
1270 {
1271 	struct imx7_csi_vb2_buffer *buf = to_imx7_csi_vb2_buffer(vb);
1272 
1273 	INIT_LIST_HEAD(&buf->list);
1274 
1275 	return 0;
1276 }
1277 
1278 static int imx7_csi_video_buf_prepare(struct vb2_buffer *vb)
1279 {
1280 	struct imx7_csi *csi = vb2_get_drv_priv(vb->vb2_queue);
1281 	struct v4l2_pix_format *pix = &csi->vdev_fmt;
1282 
1283 	if (vb2_plane_size(vb, 0) < pix->sizeimage) {
1284 		dev_err(csi->dev,
1285 			"data will not fit into plane (%lu < %lu)\n",
1286 			vb2_plane_size(vb, 0), (long)pix->sizeimage);
1287 		return -EINVAL;
1288 	}
1289 
1290 	vb2_set_plane_payload(vb, 0, pix->sizeimage);
1291 
1292 	return 0;
1293 }
1294 
1295 static bool imx7_csi_fast_track_buffer(struct imx7_csi *csi,
1296 				       struct imx7_csi_vb2_buffer *buf)
1297 {
1298 	unsigned long flags;
1299 	dma_addr_t dma_addr;
1300 	int buf_num;
1301 	u32 isr;
1302 
1303 	if (!csi->is_streaming)
1304 		return false;
1305 
1306 	dma_addr = vb2_dma_contig_plane_dma_addr(&buf->vbuf.vb2_buf, 0);
1307 
1308 	/*
1309 	 * buf_num holds the framebuffer ID of the most recently (*not* the
1310 	 * next anticipated) triggered interrupt. Without loss of generality,
1311 	 * if buf_num is 0, the hardware is capturing to FB2. If FB1 has been
1312 	 * programmed with a dummy buffer (as indicated by active_vb2_buf[0]
1313 	 * being NULL), then we can fast-track the new buffer by programming
1314 	 * its address in FB1 before the hardware completes FB2, instead of
1315 	 * adding it to the buffer queue and incurring a delay of one
1316 	 * additional frame.
1317 	 *
1318 	 * The irqlock prevents races with the interrupt handler that updates
1319 	 * buf_num when it programs the next buffer, but we can still race with
1320 	 * the hardware if we program the buffer in FB1 just after the hardware
1321 	 * completes FB2 and switches to FB1 and before buf_num can be updated
1322 	 * by the interrupt handler for FB2.  The fast-tracked buffer would
1323 	 * then be ignored by the hardware while the driver would think it has
1324 	 * successfully been processed.
1325 	 *
1326 	 * To avoid this problem, if we can't avoid the race, we can detect
1327 	 * that we have lost it by checking, after programming the buffer in
1328 	 * FB1, if the interrupt flag indicating completion of FB2 has been
1329 	 * raised. If that is not the case, fast-tracking succeeded, and we can
1330 	 * update active_vb2_buf[0]. Otherwise, we may or may not have lost the
1331 	 * race (as the interrupt flag may have been raised just after
1332 	 * programming FB1 and before we read the interrupt status register),
1333 	 * and we need to assume the worst case of a race loss and queue the
1334 	 * buffer through the slow path.
1335 	 */
1336 
1337 	spin_lock_irqsave(&csi->irqlock, flags);
1338 
1339 	buf_num = csi->buf_num;
1340 	if (csi->active_vb2_buf[buf_num]) {
1341 		spin_unlock_irqrestore(&csi->irqlock, flags);
1342 		return false;
1343 	}
1344 
1345 	imx7_csi_update_buf(csi, dma_addr, buf_num);
1346 
1347 	isr = imx7_csi_reg_read(csi, CSI_CSISR);
1348 	if (isr & (buf_num ? BIT_DMA_TSF_DONE_FB1 : BIT_DMA_TSF_DONE_FB2)) {
1349 		/*
1350 		 * The interrupt for the /other/ FB just came (the isr hasn't
1351 		 * run yet though, because we have the lock here); we can't be
1352 		 * sure we've programmed buf_num FB in time, so queue the buffer
1353 		 * to the buffer queue normally. No need to undo writing the FB
1354 		 * register, since we won't return it as active_vb2_buf is NULL,
1355 		 * so it's okay to potentially write it to both FB1 and FB2;
1356 		 * only the one where it was queued normally will be returned.
1357 		 */
1358 		spin_unlock_irqrestore(&csi->irqlock, flags);
1359 		return false;
1360 	}
1361 
1362 	csi->active_vb2_buf[buf_num] = buf;
1363 
1364 	spin_unlock_irqrestore(&csi->irqlock, flags);
1365 	return true;
1366 }
1367 
1368 static void imx7_csi_video_buf_queue(struct vb2_buffer *vb)
1369 {
1370 	struct imx7_csi *csi = vb2_get_drv_priv(vb->vb2_queue);
1371 	struct imx7_csi_vb2_buffer *buf = to_imx7_csi_vb2_buffer(vb);
1372 	unsigned long flags;
1373 
1374 	if (imx7_csi_fast_track_buffer(csi, buf))
1375 		return;
1376 
1377 	spin_lock_irqsave(&csi->q_lock, flags);
1378 
1379 	list_add_tail(&buf->list, &csi->ready_q);
1380 
1381 	spin_unlock_irqrestore(&csi->q_lock, flags);
1382 }
1383 
1384 static int imx7_csi_video_validate_fmt(struct imx7_csi *csi)
1385 {
1386 	struct v4l2_subdev_format fmt_src = {
1387 		.pad = IMX7_CSI_PAD_SRC,
1388 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
1389 	};
1390 	const struct imx7_csi_pixfmt *cc;
1391 	int ret;
1392 
1393 	/* Retrieve the media bus format on the source subdev. */
1394 	ret = v4l2_subdev_call_state_active(&csi->sd, pad, get_fmt, &fmt_src);
1395 	if (ret)
1396 		return ret;
1397 
1398 	/*
1399 	 * Verify that the media bus size matches the size set on the video
1400 	 * node. It is sufficient to check the compose rectangle size without
1401 	 * checking the rounded size from pix_fmt, as the rounded size is
1402 	 * derived directly from the compose rectangle size, and will thus
1403 	 * always match if the compose rectangle matches.
1404 	 */
1405 	if (csi->vdev_compose.width != fmt_src.format.width ||
1406 	    csi->vdev_compose.height != fmt_src.format.height)
1407 		return -EPIPE;
1408 
1409 	/*
1410 	 * Verify that the media bus code is compatible with the pixel format
1411 	 * set on the video node.
1412 	 */
1413 	cc = imx7_csi_find_mbus_format(fmt_src.format.code);
1414 	if (!cc || csi->vdev_cc->yuv != cc->yuv)
1415 		return -EPIPE;
1416 
1417 	return 0;
1418 }
1419 
1420 static int imx7_csi_video_start_streaming(struct vb2_queue *vq,
1421 					  unsigned int count)
1422 {
1423 	struct imx7_csi *csi = vb2_get_drv_priv(vq);
1424 	struct imx7_csi_vb2_buffer *buf, *tmp;
1425 	unsigned long flags;
1426 	int ret;
1427 
1428 	ret = imx7_csi_video_validate_fmt(csi);
1429 	if (ret) {
1430 		dev_err(csi->dev, "capture format not valid\n");
1431 		goto err_buffers;
1432 	}
1433 
1434 	mutex_lock(&csi->mdev.graph_mutex);
1435 
1436 	ret = __video_device_pipeline_start(csi->vdev, &csi->pipe);
1437 	if (ret)
1438 		goto err_unlock;
1439 
1440 	ret = v4l2_subdev_call(&csi->sd, video, s_stream, 1);
1441 	if (ret)
1442 		goto err_stop;
1443 
1444 	mutex_unlock(&csi->mdev.graph_mutex);
1445 
1446 	return 0;
1447 
1448 err_stop:
1449 	__video_device_pipeline_stop(csi->vdev);
1450 err_unlock:
1451 	mutex_unlock(&csi->mdev.graph_mutex);
1452 	dev_err(csi->dev, "pipeline start failed with %d\n", ret);
1453 err_buffers:
1454 	spin_lock_irqsave(&csi->q_lock, flags);
1455 	list_for_each_entry_safe(buf, tmp, &csi->ready_q, list) {
1456 		list_del(&buf->list);
1457 		vb2_buffer_done(&buf->vbuf.vb2_buf, VB2_BUF_STATE_QUEUED);
1458 	}
1459 	spin_unlock_irqrestore(&csi->q_lock, flags);
1460 	return ret;
1461 }
1462 
1463 static void imx7_csi_video_stop_streaming(struct vb2_queue *vq)
1464 {
1465 	struct imx7_csi *csi = vb2_get_drv_priv(vq);
1466 	struct imx7_csi_vb2_buffer *frame;
1467 	struct imx7_csi_vb2_buffer *tmp;
1468 	unsigned long flags;
1469 
1470 	mutex_lock(&csi->mdev.graph_mutex);
1471 	v4l2_subdev_call(&csi->sd, video, s_stream, 0);
1472 	__video_device_pipeline_stop(csi->vdev);
1473 	mutex_unlock(&csi->mdev.graph_mutex);
1474 
1475 	/* release all active buffers */
1476 	spin_lock_irqsave(&csi->q_lock, flags);
1477 	list_for_each_entry_safe(frame, tmp, &csi->ready_q, list) {
1478 		list_del(&frame->list);
1479 		vb2_buffer_done(&frame->vbuf.vb2_buf, VB2_BUF_STATE_ERROR);
1480 	}
1481 	spin_unlock_irqrestore(&csi->q_lock, flags);
1482 }
1483 
1484 static const struct vb2_ops imx7_csi_video_qops = {
1485 	.queue_setup	 = imx7_csi_video_queue_setup,
1486 	.buf_init        = imx7_csi_video_buf_init,
1487 	.buf_prepare	 = imx7_csi_video_buf_prepare,
1488 	.buf_queue	 = imx7_csi_video_buf_queue,
1489 	.wait_prepare	 = vb2_ops_wait_prepare,
1490 	.wait_finish	 = vb2_ops_wait_finish,
1491 	.start_streaming = imx7_csi_video_start_streaming,
1492 	.stop_streaming  = imx7_csi_video_stop_streaming,
1493 };
1494 
1495 /* -----------------------------------------------------------------------------
1496  * Video Capture Device - File Operations
1497  */
1498 
1499 static int imx7_csi_video_open(struct file *file)
1500 {
1501 	struct imx7_csi *csi = video_drvdata(file);
1502 	int ret;
1503 
1504 	if (mutex_lock_interruptible(&csi->vdev_mutex))
1505 		return -ERESTARTSYS;
1506 
1507 	ret = v4l2_fh_open(file);
1508 	if (ret) {
1509 		dev_err(csi->dev, "v4l2_fh_open failed\n");
1510 		goto out;
1511 	}
1512 
1513 	ret = v4l2_pipeline_pm_get(&csi->vdev->entity);
1514 	if (ret)
1515 		v4l2_fh_release(file);
1516 
1517 out:
1518 	mutex_unlock(&csi->vdev_mutex);
1519 	return ret;
1520 }
1521 
1522 static int imx7_csi_video_release(struct file *file)
1523 {
1524 	struct imx7_csi *csi = video_drvdata(file);
1525 	struct vb2_queue *vq = &csi->q;
1526 
1527 	mutex_lock(&csi->vdev_mutex);
1528 
1529 	if (file->private_data == vq->owner) {
1530 		vb2_queue_release(vq);
1531 		vq->owner = NULL;
1532 	}
1533 
1534 	v4l2_pipeline_pm_put(&csi->vdev->entity);
1535 
1536 	v4l2_fh_release(file);
1537 	mutex_unlock(&csi->vdev_mutex);
1538 	return 0;
1539 }
1540 
1541 static const struct v4l2_file_operations imx7_csi_video_fops = {
1542 	.owner		= THIS_MODULE,
1543 	.open		= imx7_csi_video_open,
1544 	.release	= imx7_csi_video_release,
1545 	.poll		= vb2_fop_poll,
1546 	.unlocked_ioctl	= video_ioctl2,
1547 	.mmap		= vb2_fop_mmap,
1548 };
1549 
1550 /* -----------------------------------------------------------------------------
1551  * Video Capture Device - Init & Cleanup
1552  */
1553 
1554 static struct imx7_csi_vb2_buffer *imx7_csi_video_next_buf(struct imx7_csi *csi)
1555 {
1556 	struct imx7_csi_vb2_buffer *buf = NULL;
1557 	unsigned long flags;
1558 
1559 	spin_lock_irqsave(&csi->q_lock, flags);
1560 
1561 	/* get next queued buffer */
1562 	if (!list_empty(&csi->ready_q)) {
1563 		buf = list_entry(csi->ready_q.next, struct imx7_csi_vb2_buffer,
1564 				 list);
1565 		list_del(&buf->list);
1566 	}
1567 
1568 	spin_unlock_irqrestore(&csi->q_lock, flags);
1569 
1570 	return buf;
1571 }
1572 
1573 static void imx7_csi_video_init_format(struct imx7_csi *csi)
1574 {
1575 	struct v4l2_pix_format *pixfmt = &csi->vdev_fmt;
1576 
1577 	pixfmt->width = IMX7_CSI_DEF_PIX_WIDTH;
1578 	pixfmt->height = IMX7_CSI_DEF_PIX_HEIGHT;
1579 
1580 	csi->vdev_cc = __imx7_csi_video_try_fmt(pixfmt, &csi->vdev_compose);
1581 }
1582 
1583 static int imx7_csi_video_register(struct imx7_csi *csi)
1584 {
1585 	struct v4l2_subdev *sd = &csi->sd;
1586 	struct v4l2_device *v4l2_dev = sd->v4l2_dev;
1587 	struct video_device *vdev = csi->vdev;
1588 	int ret;
1589 
1590 	vdev->v4l2_dev = v4l2_dev;
1591 
1592 	/* Initialize the default format and compose rectangle. */
1593 	imx7_csi_video_init_format(csi);
1594 
1595 	/* Register the video device. */
1596 	ret = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
1597 	if (ret) {
1598 		dev_err(csi->dev, "Failed to register video device\n");
1599 		return ret;
1600 	}
1601 
1602 	dev_info(csi->dev, "Registered %s as /dev/%s\n", vdev->name,
1603 		 video_device_node_name(vdev));
1604 
1605 	/* Create the link from the CSI subdev to the video device. */
1606 	ret = media_create_pad_link(&sd->entity, IMX7_CSI_PAD_SRC,
1607 				    &vdev->entity, 0, MEDIA_LNK_FL_IMMUTABLE |
1608 				    MEDIA_LNK_FL_ENABLED);
1609 	if (ret) {
1610 		dev_err(csi->dev, "failed to create link to device node\n");
1611 		video_unregister_device(vdev);
1612 		return ret;
1613 	}
1614 
1615 	return 0;
1616 }
1617 
1618 static void imx7_csi_video_unregister(struct imx7_csi *csi)
1619 {
1620 	media_entity_cleanup(&csi->vdev->entity);
1621 	video_unregister_device(csi->vdev);
1622 }
1623 
1624 static int imx7_csi_video_init(struct imx7_csi *csi)
1625 {
1626 	struct video_device *vdev;
1627 	struct vb2_queue *vq;
1628 	int ret;
1629 
1630 	mutex_init(&csi->vdev_mutex);
1631 	INIT_LIST_HEAD(&csi->ready_q);
1632 	spin_lock_init(&csi->q_lock);
1633 
1634 	/* Allocate and initialize the video device. */
1635 	vdev = video_device_alloc();
1636 	if (!vdev)
1637 		return -ENOMEM;
1638 
1639 	vdev->fops = &imx7_csi_video_fops;
1640 	vdev->ioctl_ops = &imx7_csi_video_ioctl_ops;
1641 	vdev->minor = -1;
1642 	vdev->release = video_device_release;
1643 	vdev->vfl_dir = VFL_DIR_RX;
1644 	vdev->tvnorms = V4L2_STD_NTSC | V4L2_STD_PAL | V4L2_STD_SECAM;
1645 	vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING
1646 			 | V4L2_CAP_IO_MC;
1647 	vdev->lock = &csi->vdev_mutex;
1648 	vdev->queue = &csi->q;
1649 
1650 	snprintf(vdev->name, sizeof(vdev->name), "%s capture", csi->sd.name);
1651 
1652 	video_set_drvdata(vdev, csi);
1653 	csi->vdev = vdev;
1654 
1655 	/* Initialize the video device pad. */
1656 	csi->vdev_pad.flags = MEDIA_PAD_FL_SINK;
1657 	ret = media_entity_pads_init(&vdev->entity, 1, &csi->vdev_pad);
1658 	if (ret) {
1659 		video_device_release(vdev);
1660 		return ret;
1661 	}
1662 
1663 	/* Initialize the vb2 queue. */
1664 	vq = &csi->q;
1665 	vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1666 	vq->io_modes = VB2_MMAP | VB2_DMABUF;
1667 	vq->drv_priv = csi;
1668 	vq->buf_struct_size = sizeof(struct imx7_csi_vb2_buffer);
1669 	vq->ops = &imx7_csi_video_qops;
1670 	vq->mem_ops = &vb2_dma_contig_memops;
1671 	vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1672 	vq->lock = &csi->vdev_mutex;
1673 	vq->min_buffers_needed = 2;
1674 	vq->dev = csi->dev;
1675 
1676 	ret = vb2_queue_init(vq);
1677 	if (ret) {
1678 		dev_err(csi->dev, "vb2_queue_init failed\n");
1679 		video_device_release(vdev);
1680 		return ret;
1681 	}
1682 
1683 	return 0;
1684 }
1685 
1686 /* -----------------------------------------------------------------------------
1687  * V4L2 Subdev Operations
1688  */
1689 
1690 static int imx7_csi_s_stream(struct v4l2_subdev *sd, int enable)
1691 {
1692 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1693 	struct v4l2_subdev_state *sd_state;
1694 	int ret = 0;
1695 
1696 	sd_state = v4l2_subdev_lock_and_get_active_state(sd);
1697 
1698 	if (enable) {
1699 		ret = imx7_csi_init(csi, sd_state);
1700 		if (ret < 0)
1701 			goto out_unlock;
1702 
1703 		ret = v4l2_subdev_call(csi->src_sd, video, s_stream, 1);
1704 		if (ret < 0) {
1705 			imx7_csi_deinit(csi, VB2_BUF_STATE_QUEUED);
1706 			goto out_unlock;
1707 		}
1708 
1709 		imx7_csi_enable(csi);
1710 	} else {
1711 		imx7_csi_disable(csi);
1712 
1713 		v4l2_subdev_call(csi->src_sd, video, s_stream, 0);
1714 
1715 		imx7_csi_deinit(csi, VB2_BUF_STATE_ERROR);
1716 	}
1717 
1718 	csi->is_streaming = !!enable;
1719 
1720 out_unlock:
1721 	v4l2_subdev_unlock_state(sd_state);
1722 
1723 	return ret;
1724 }
1725 
1726 static int imx7_csi_init_cfg(struct v4l2_subdev *sd,
1727 			     struct v4l2_subdev_state *sd_state)
1728 {
1729 	const struct imx7_csi_pixfmt *cc;
1730 	int i;
1731 
1732 	cc = imx7_csi_find_mbus_format(IMX7_CSI_DEF_MBUS_CODE);
1733 
1734 	for (i = 0; i < IMX7_CSI_PADS_NUM; i++) {
1735 		struct v4l2_mbus_framefmt *mf =
1736 			v4l2_subdev_get_pad_format(sd, sd_state, i);
1737 
1738 		mf->code = IMX7_CSI_DEF_MBUS_CODE;
1739 		mf->width = IMX7_CSI_DEF_PIX_WIDTH;
1740 		mf->height = IMX7_CSI_DEF_PIX_HEIGHT;
1741 		mf->field = V4L2_FIELD_NONE;
1742 
1743 		mf->colorspace = V4L2_COLORSPACE_SRGB;
1744 		mf->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(mf->colorspace);
1745 		mf->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(mf->colorspace);
1746 		mf->quantization = V4L2_MAP_QUANTIZATION_DEFAULT(!cc->yuv,
1747 					mf->colorspace, mf->ycbcr_enc);
1748 	}
1749 
1750 	return 0;
1751 }
1752 
1753 static int imx7_csi_enum_mbus_code(struct v4l2_subdev *sd,
1754 				   struct v4l2_subdev_state *sd_state,
1755 				   struct v4l2_subdev_mbus_code_enum *code)
1756 {
1757 	struct v4l2_mbus_framefmt *in_fmt;
1758 	int ret = 0;
1759 
1760 	in_fmt = v4l2_subdev_get_pad_format(sd, sd_state, IMX7_CSI_PAD_SINK);
1761 
1762 	switch (code->pad) {
1763 	case IMX7_CSI_PAD_SINK:
1764 		ret = imx7_csi_enum_mbus_formats(&code->code, code->index);
1765 		break;
1766 
1767 	case IMX7_CSI_PAD_SRC:
1768 		if (code->index != 0) {
1769 			ret = -EINVAL;
1770 			break;
1771 		}
1772 
1773 		code->code = in_fmt->code;
1774 		break;
1775 
1776 	default:
1777 		ret = -EINVAL;
1778 		break;
1779 	}
1780 
1781 	return ret;
1782 }
1783 
1784 /*
1785  * Default the colorspace in tryfmt to SRGB if set to an unsupported
1786  * colorspace or not initialized. Then set the remaining colorimetry
1787  * parameters based on the colorspace if they are uninitialized.
1788  *
1789  * tryfmt->code must be set on entry.
1790  */
1791 static void imx7_csi_try_colorimetry(struct v4l2_mbus_framefmt *tryfmt)
1792 {
1793 	const struct imx7_csi_pixfmt *cc;
1794 	bool is_rgb = false;
1795 
1796 	cc = imx7_csi_find_mbus_format(tryfmt->code);
1797 	if (cc && !cc->yuv)
1798 		is_rgb = true;
1799 
1800 	switch (tryfmt->colorspace) {
1801 	case V4L2_COLORSPACE_SMPTE170M:
1802 	case V4L2_COLORSPACE_REC709:
1803 	case V4L2_COLORSPACE_JPEG:
1804 	case V4L2_COLORSPACE_SRGB:
1805 	case V4L2_COLORSPACE_BT2020:
1806 	case V4L2_COLORSPACE_OPRGB:
1807 	case V4L2_COLORSPACE_DCI_P3:
1808 	case V4L2_COLORSPACE_RAW:
1809 		break;
1810 	default:
1811 		tryfmt->colorspace = V4L2_COLORSPACE_SRGB;
1812 		break;
1813 	}
1814 
1815 	if (tryfmt->xfer_func == V4L2_XFER_FUNC_DEFAULT)
1816 		tryfmt->xfer_func =
1817 			V4L2_MAP_XFER_FUNC_DEFAULT(tryfmt->colorspace);
1818 
1819 	if (tryfmt->ycbcr_enc == V4L2_YCBCR_ENC_DEFAULT)
1820 		tryfmt->ycbcr_enc =
1821 			V4L2_MAP_YCBCR_ENC_DEFAULT(tryfmt->colorspace);
1822 
1823 	if (tryfmt->quantization == V4L2_QUANTIZATION_DEFAULT)
1824 		tryfmt->quantization =
1825 			V4L2_MAP_QUANTIZATION_DEFAULT(is_rgb,
1826 						      tryfmt->colorspace,
1827 						      tryfmt->ycbcr_enc);
1828 }
1829 
1830 static void imx7_csi_try_fmt(struct v4l2_subdev *sd,
1831 			     struct v4l2_subdev_state *sd_state,
1832 			     struct v4l2_subdev_format *sdformat,
1833 			     const struct imx7_csi_pixfmt **cc)
1834 {
1835 	const struct imx7_csi_pixfmt *in_cc;
1836 	struct v4l2_mbus_framefmt *in_fmt;
1837 	u32 code;
1838 
1839 	in_fmt = v4l2_subdev_get_pad_format(sd, sd_state, IMX7_CSI_PAD_SINK);
1840 
1841 	switch (sdformat->pad) {
1842 	case IMX7_CSI_PAD_SRC:
1843 		in_cc = imx7_csi_find_mbus_format(in_fmt->code);
1844 
1845 		sdformat->format.width = in_fmt->width;
1846 		sdformat->format.height = in_fmt->height;
1847 		sdformat->format.code = in_fmt->code;
1848 		sdformat->format.field = in_fmt->field;
1849 		*cc = in_cc;
1850 
1851 		sdformat->format.colorspace = in_fmt->colorspace;
1852 		sdformat->format.xfer_func = in_fmt->xfer_func;
1853 		sdformat->format.quantization = in_fmt->quantization;
1854 		sdformat->format.ycbcr_enc = in_fmt->ycbcr_enc;
1855 		break;
1856 
1857 	case IMX7_CSI_PAD_SINK:
1858 		*cc = imx7_csi_find_mbus_format(sdformat->format.code);
1859 		if (!*cc) {
1860 			code = IMX7_CSI_DEF_MBUS_CODE;
1861 			*cc = imx7_csi_find_mbus_format(code);
1862 			sdformat->format.code = code;
1863 		}
1864 
1865 		if (sdformat->format.field != V4L2_FIELD_INTERLACED)
1866 			sdformat->format.field = V4L2_FIELD_NONE;
1867 		break;
1868 	}
1869 
1870 	imx7_csi_try_colorimetry(&sdformat->format);
1871 }
1872 
1873 static int imx7_csi_set_fmt(struct v4l2_subdev *sd,
1874 			    struct v4l2_subdev_state *sd_state,
1875 			    struct v4l2_subdev_format *sdformat)
1876 {
1877 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1878 	const struct imx7_csi_pixfmt *outcc;
1879 	struct v4l2_mbus_framefmt *outfmt;
1880 	const struct imx7_csi_pixfmt *cc;
1881 	struct v4l2_mbus_framefmt *fmt;
1882 	struct v4l2_subdev_format format;
1883 
1884 	if (csi->is_streaming)
1885 		return -EBUSY;
1886 
1887 	imx7_csi_try_fmt(sd, sd_state, sdformat, &cc);
1888 
1889 	fmt = v4l2_subdev_get_pad_format(sd, sd_state, sdformat->pad);
1890 
1891 	*fmt = sdformat->format;
1892 
1893 	if (sdformat->pad == IMX7_CSI_PAD_SINK) {
1894 		/* propagate format to source pads */
1895 		format.pad = IMX7_CSI_PAD_SRC;
1896 		format.which = sdformat->which;
1897 		format.format = sdformat->format;
1898 		imx7_csi_try_fmt(sd, sd_state, &format, &outcc);
1899 
1900 		outfmt = v4l2_subdev_get_pad_format(sd, sd_state,
1901 						    IMX7_CSI_PAD_SRC);
1902 		*outfmt = format.format;
1903 	}
1904 
1905 	return 0;
1906 }
1907 
1908 static int imx7_csi_pad_link_validate(struct v4l2_subdev *sd,
1909 				      struct media_link *link,
1910 				      struct v4l2_subdev_format *source_fmt,
1911 				      struct v4l2_subdev_format *sink_fmt)
1912 {
1913 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1914 	struct media_pad *pad = NULL;
1915 	unsigned int i;
1916 	int ret;
1917 
1918 	/*
1919 	 * Validate the source link, and record whether the source uses the
1920 	 * parallel input or the CSI-2 receiver.
1921 	 */
1922 	ret = v4l2_subdev_link_validate_default(sd, link, source_fmt, sink_fmt);
1923 	if (ret)
1924 		return ret;
1925 
1926 	switch (csi->src_sd->entity.function) {
1927 	case MEDIA_ENT_F_VID_IF_BRIDGE:
1928 		/* The input is the CSI-2 receiver. */
1929 		csi->is_csi2 = true;
1930 		break;
1931 
1932 	case MEDIA_ENT_F_VID_MUX:
1933 		/* The input is the mux, check its input. */
1934 		for (i = 0; i < csi->src_sd->entity.num_pads; i++) {
1935 			struct media_pad *spad = &csi->src_sd->entity.pads[i];
1936 
1937 			if (!(spad->flags & MEDIA_PAD_FL_SINK))
1938 				continue;
1939 
1940 			pad = media_pad_remote_pad_first(spad);
1941 			if (pad)
1942 				break;
1943 		}
1944 
1945 		if (!pad)
1946 			return -ENODEV;
1947 
1948 		csi->is_csi2 = pad->entity->function == MEDIA_ENT_F_VID_IF_BRIDGE;
1949 		break;
1950 
1951 	default:
1952 		/*
1953 		 * The input is an external entity, it must use the parallel
1954 		 * bus.
1955 		 */
1956 		csi->is_csi2 = false;
1957 		break;
1958 	}
1959 
1960 	return 0;
1961 }
1962 
1963 static int imx7_csi_registered(struct v4l2_subdev *sd)
1964 {
1965 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1966 	int ret;
1967 
1968 	ret = imx7_csi_video_init(csi);
1969 	if (ret)
1970 		return ret;
1971 
1972 	ret = imx7_csi_video_register(csi);
1973 	if (ret)
1974 		return ret;
1975 
1976 	ret = v4l2_device_register_subdev_nodes(&csi->v4l2_dev);
1977 	if (ret)
1978 		goto err_unreg;
1979 
1980 	ret = media_device_register(&csi->mdev);
1981 	if (ret)
1982 		goto err_unreg;
1983 
1984 	return 0;
1985 
1986 err_unreg:
1987 	imx7_csi_video_unregister(csi);
1988 	return ret;
1989 }
1990 
1991 static void imx7_csi_unregistered(struct v4l2_subdev *sd)
1992 {
1993 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1994 
1995 	imx7_csi_video_unregister(csi);
1996 }
1997 
1998 static const struct v4l2_subdev_video_ops imx7_csi_video_ops = {
1999 	.s_stream	= imx7_csi_s_stream,
2000 };
2001 
2002 static const struct v4l2_subdev_pad_ops imx7_csi_pad_ops = {
2003 	.init_cfg	= imx7_csi_init_cfg,
2004 	.enum_mbus_code	= imx7_csi_enum_mbus_code,
2005 	.get_fmt	= v4l2_subdev_get_fmt,
2006 	.set_fmt	= imx7_csi_set_fmt,
2007 	.link_validate	= imx7_csi_pad_link_validate,
2008 };
2009 
2010 static const struct v4l2_subdev_ops imx7_csi_subdev_ops = {
2011 	.video		= &imx7_csi_video_ops,
2012 	.pad		= &imx7_csi_pad_ops,
2013 };
2014 
2015 static const struct v4l2_subdev_internal_ops imx7_csi_internal_ops = {
2016 	.registered	= imx7_csi_registered,
2017 	.unregistered	= imx7_csi_unregistered,
2018 };
2019 
2020 /* -----------------------------------------------------------------------------
2021  * Media Entity Operations
2022  */
2023 
2024 static const struct media_entity_operations imx7_csi_entity_ops = {
2025 	.link_validate	= v4l2_subdev_link_validate,
2026 	.get_fwnode_pad = v4l2_subdev_get_fwnode_pad_1_to_1,
2027 };
2028 
2029 /* -----------------------------------------------------------------------------
2030  * Probe & Remove
2031  */
2032 
2033 static int imx7_csi_notify_bound(struct v4l2_async_notifier *notifier,
2034 				 struct v4l2_subdev *sd,
2035 				 struct v4l2_async_subdev *asd)
2036 {
2037 	struct imx7_csi *csi = imx7_csi_notifier_to_dev(notifier);
2038 	struct media_pad *sink = &csi->sd.entity.pads[IMX7_CSI_PAD_SINK];
2039 
2040 	csi->src_sd = sd;
2041 
2042 	return v4l2_create_fwnode_links_to_pad(sd, sink, MEDIA_LNK_FL_ENABLED |
2043 					       MEDIA_LNK_FL_IMMUTABLE);
2044 }
2045 
2046 static int imx7_csi_notify_complete(struct v4l2_async_notifier *notifier)
2047 {
2048 	struct imx7_csi *csi = imx7_csi_notifier_to_dev(notifier);
2049 
2050 	return v4l2_device_register_subdev_nodes(&csi->v4l2_dev);
2051 }
2052 
2053 static const struct v4l2_async_notifier_operations imx7_csi_notify_ops = {
2054 	.bound = imx7_csi_notify_bound,
2055 	.complete = imx7_csi_notify_complete,
2056 };
2057 
2058 static int imx7_csi_async_register(struct imx7_csi *csi)
2059 {
2060 	struct v4l2_async_subdev *asd;
2061 	struct fwnode_handle *ep;
2062 	int ret;
2063 
2064 	v4l2_async_nf_init(&csi->notifier);
2065 
2066 	ep = fwnode_graph_get_endpoint_by_id(dev_fwnode(csi->dev), 0, 0,
2067 					     FWNODE_GRAPH_ENDPOINT_NEXT);
2068 	if (!ep) {
2069 		ret = dev_err_probe(csi->dev, -ENOTCONN,
2070 				    "Failed to get remote endpoint\n");
2071 		goto error;
2072 	}
2073 
2074 	asd = v4l2_async_nf_add_fwnode_remote(&csi->notifier, ep,
2075 					      struct v4l2_async_subdev);
2076 
2077 	fwnode_handle_put(ep);
2078 
2079 	if (IS_ERR(asd)) {
2080 		ret = dev_err_probe(csi->dev, PTR_ERR(asd),
2081 				    "Failed to add remote subdev to notifier\n");
2082 		goto error;
2083 	}
2084 
2085 	csi->notifier.ops = &imx7_csi_notify_ops;
2086 
2087 	ret = v4l2_async_nf_register(&csi->v4l2_dev, &csi->notifier);
2088 	if (ret)
2089 		goto error;
2090 
2091 	return 0;
2092 
2093 error:
2094 	v4l2_async_nf_cleanup(&csi->notifier);
2095 	return ret;
2096 }
2097 
2098 static void imx7_csi_media_cleanup(struct imx7_csi *csi)
2099 {
2100 	v4l2_device_unregister(&csi->v4l2_dev);
2101 	media_device_unregister(&csi->mdev);
2102 	v4l2_subdev_cleanup(&csi->sd);
2103 	media_device_cleanup(&csi->mdev);
2104 }
2105 
2106 static const struct media_device_ops imx7_csi_media_ops = {
2107 	.link_notify = v4l2_pipeline_link_notify,
2108 };
2109 
2110 static int imx7_csi_media_dev_init(struct imx7_csi *csi)
2111 {
2112 	int ret;
2113 
2114 	strscpy(csi->mdev.model, "imx-media", sizeof(csi->mdev.model));
2115 	csi->mdev.ops = &imx7_csi_media_ops;
2116 	csi->mdev.dev = csi->dev;
2117 
2118 	csi->v4l2_dev.mdev = &csi->mdev;
2119 	strscpy(csi->v4l2_dev.name, "imx-media",
2120 		sizeof(csi->v4l2_dev.name));
2121 	snprintf(csi->mdev.bus_info, sizeof(csi->mdev.bus_info),
2122 		 "platform:%s", dev_name(csi->mdev.dev));
2123 
2124 	media_device_init(&csi->mdev);
2125 
2126 	ret = v4l2_device_register(csi->dev, &csi->v4l2_dev);
2127 	if (ret < 0) {
2128 		v4l2_err(&csi->v4l2_dev,
2129 			 "Failed to register v4l2_device: %d\n", ret);
2130 		goto cleanup;
2131 	}
2132 
2133 	return 0;
2134 
2135 cleanup:
2136 	media_device_cleanup(&csi->mdev);
2137 
2138 	return ret;
2139 }
2140 
2141 static int imx7_csi_media_init(struct imx7_csi *csi)
2142 {
2143 	unsigned int i;
2144 	int ret;
2145 
2146 	/* add media device */
2147 	ret = imx7_csi_media_dev_init(csi);
2148 	if (ret)
2149 		return ret;
2150 
2151 	v4l2_subdev_init(&csi->sd, &imx7_csi_subdev_ops);
2152 	v4l2_set_subdevdata(&csi->sd, csi);
2153 	csi->sd.internal_ops = &imx7_csi_internal_ops;
2154 	csi->sd.entity.ops = &imx7_csi_entity_ops;
2155 	csi->sd.entity.function = MEDIA_ENT_F_VID_IF_BRIDGE;
2156 	csi->sd.dev = csi->dev;
2157 	csi->sd.owner = THIS_MODULE;
2158 	csi->sd.flags = V4L2_SUBDEV_FL_HAS_DEVNODE;
2159 	snprintf(csi->sd.name, sizeof(csi->sd.name), "csi");
2160 
2161 	for (i = 0; i < IMX7_CSI_PADS_NUM; i++)
2162 		csi->pad[i].flags = (i == IMX7_CSI_PAD_SINK) ?
2163 			MEDIA_PAD_FL_SINK : MEDIA_PAD_FL_SOURCE;
2164 
2165 	ret = media_entity_pads_init(&csi->sd.entity, IMX7_CSI_PADS_NUM,
2166 				     csi->pad);
2167 	if (ret)
2168 		goto error;
2169 
2170 	ret = v4l2_subdev_init_finalize(&csi->sd);
2171 	if (ret)
2172 		goto error;
2173 
2174 	ret = v4l2_device_register_subdev(&csi->v4l2_dev, &csi->sd);
2175 	if (ret)
2176 		goto error;
2177 
2178 	return 0;
2179 
2180 error:
2181 	imx7_csi_media_cleanup(csi);
2182 	return ret;
2183 }
2184 
2185 static int imx7_csi_probe(struct platform_device *pdev)
2186 {
2187 	struct device *dev = &pdev->dev;
2188 	struct imx7_csi *csi;
2189 	int ret;
2190 
2191 	csi = devm_kzalloc(&pdev->dev, sizeof(*csi), GFP_KERNEL);
2192 	if (!csi)
2193 		return -ENOMEM;
2194 
2195 	csi->dev = dev;
2196 	platform_set_drvdata(pdev, csi);
2197 
2198 	spin_lock_init(&csi->irqlock);
2199 
2200 	/* Acquire resources and install interrupt handler. */
2201 	csi->mclk = devm_clk_get(&pdev->dev, "mclk");
2202 	if (IS_ERR(csi->mclk)) {
2203 		ret = PTR_ERR(csi->mclk);
2204 		dev_err(dev, "Failed to get mclk: %d", ret);
2205 		return ret;
2206 	}
2207 
2208 	csi->irq = platform_get_irq(pdev, 0);
2209 	if (csi->irq < 0)
2210 		return csi->irq;
2211 
2212 	csi->regbase = devm_platform_ioremap_resource(pdev, 0);
2213 	if (IS_ERR(csi->regbase))
2214 		return PTR_ERR(csi->regbase);
2215 
2216 	csi->model = (enum imx_csi_model)(uintptr_t)of_device_get_match_data(&pdev->dev);
2217 
2218 	ret = devm_request_irq(dev, csi->irq, imx7_csi_irq_handler, 0, "csi",
2219 			       (void *)csi);
2220 	if (ret < 0) {
2221 		dev_err(dev, "Request CSI IRQ failed.\n");
2222 		return ret;
2223 	}
2224 
2225 	/* Initialize all the media device infrastructure. */
2226 	ret = imx7_csi_media_init(csi);
2227 	if (ret)
2228 		return ret;
2229 
2230 	ret = imx7_csi_async_register(csi);
2231 	if (ret)
2232 		goto err_media_cleanup;
2233 
2234 	return 0;
2235 
2236 err_media_cleanup:
2237 	imx7_csi_media_cleanup(csi);
2238 
2239 	return ret;
2240 }
2241 
2242 static void imx7_csi_remove(struct platform_device *pdev)
2243 {
2244 	struct imx7_csi *csi = platform_get_drvdata(pdev);
2245 
2246 	imx7_csi_media_cleanup(csi);
2247 
2248 	v4l2_async_nf_unregister(&csi->notifier);
2249 	v4l2_async_nf_cleanup(&csi->notifier);
2250 	v4l2_async_unregister_subdev(&csi->sd);
2251 }
2252 
2253 static const struct of_device_id imx7_csi_of_match[] = {
2254 	{ .compatible = "fsl,imx8mq-csi", .data = (void *)IMX7_CSI_IMX8MQ },
2255 	{ .compatible = "fsl,imx7-csi", .data = (void *)IMX7_CSI_IMX7 },
2256 	{ .compatible = "fsl,imx6ul-csi", .data = (void *)IMX7_CSI_IMX7 },
2257 	{ },
2258 };
2259 MODULE_DEVICE_TABLE(of, imx7_csi_of_match);
2260 
2261 static struct platform_driver imx7_csi_driver = {
2262 	.probe = imx7_csi_probe,
2263 	.remove_new = imx7_csi_remove,
2264 	.driver = {
2265 		.of_match_table = imx7_csi_of_match,
2266 		.name = "imx7-csi",
2267 	},
2268 };
2269 module_platform_driver(imx7_csi_driver);
2270 
2271 MODULE_DESCRIPTION("i.MX7 CSI subdev driver");
2272 MODULE_AUTHOR("Rui Miguel Silva <rui.silva@linaro.org>");
2273 MODULE_LICENSE("GPL v2");
2274 MODULE_ALIAS("platform:imx7-csi");
2275