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.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 	u32 walign;
1078 
1079 	if (fsize->index > 0)
1080 		return -EINVAL;
1081 
1082 	cc = imx7_csi_find_pixel_format(fsize->pixel_format);
1083 	if (!cc)
1084 		return -EINVAL;
1085 
1086 	/*
1087 	 * The width alignment is 8 bytes as indicated by the
1088 	 * CSI_IMAG_PARA.IMAGE_WIDTH documentation. Convert it to pixels.
1089 	 */
1090 	walign = 8 * 8 / cc->bpp;
1091 
1092 	fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS;
1093 	fsize->stepwise.min_width = walign;
1094 	fsize->stepwise.max_width = round_down(65535U, walign);
1095 	fsize->stepwise.min_height = 1;
1096 	fsize->stepwise.max_height = 65535;
1097 	fsize->stepwise.step_width = walign;
1098 	fsize->stepwise.step_height = 1;
1099 
1100 	return 0;
1101 }
1102 
1103 static int imx7_csi_video_g_fmt_vid_cap(struct file *file, void *fh,
1104 					struct v4l2_format *f)
1105 {
1106 	struct imx7_csi *csi = video_drvdata(file);
1107 
1108 	f->fmt.pix = csi->vdev_fmt;
1109 
1110 	return 0;
1111 }
1112 
1113 static const struct imx7_csi_pixfmt *
1114 __imx7_csi_video_try_fmt(struct v4l2_pix_format *pixfmt,
1115 			 struct v4l2_rect *compose)
1116 {
1117 	const struct imx7_csi_pixfmt *cc;
1118 	u32 walign;
1119 
1120 	if (compose) {
1121 		compose->width = pixfmt->width;
1122 		compose->height = pixfmt->height;
1123 	}
1124 
1125 	/*
1126 	 * Find the pixel format, default to the first supported format if not
1127 	 * found.
1128 	 */
1129 	cc = imx7_csi_find_pixel_format(pixfmt->pixelformat);
1130 	if (!cc) {
1131 		pixfmt->pixelformat = IMX7_CSI_DEF_PIX_FORMAT;
1132 		cc = imx7_csi_find_pixel_format(pixfmt->pixelformat);
1133 	}
1134 
1135 	/*
1136 	 * The width alignment is 8 bytes as indicated by the
1137 	 * CSI_IMAG_PARA.IMAGE_WIDTH documentation. Convert it to pixels.
1138 	 *
1139 	 * TODO: Implement configurable stride support.
1140 	 */
1141 	walign = 8 * 8 / cc->bpp;
1142 	v4l_bound_align_image(&pixfmt->width, 1, 0xffff, walign,
1143 			      &pixfmt->height, 1, 0xffff, 1, 0);
1144 
1145 	pixfmt->bytesperline = pixfmt->width * cc->bpp / 8;
1146 	pixfmt->sizeimage = pixfmt->bytesperline * pixfmt->height;
1147 	pixfmt->field = V4L2_FIELD_NONE;
1148 
1149 	return cc;
1150 }
1151 
1152 static int imx7_csi_video_try_fmt_vid_cap(struct file *file, void *fh,
1153 					  struct v4l2_format *f)
1154 {
1155 	__imx7_csi_video_try_fmt(&f->fmt.pix, NULL);
1156 	return 0;
1157 }
1158 
1159 static int imx7_csi_video_s_fmt_vid_cap(struct file *file, void *fh,
1160 					struct v4l2_format *f)
1161 {
1162 	struct imx7_csi *csi = video_drvdata(file);
1163 	const struct imx7_csi_pixfmt *cc;
1164 
1165 	if (vb2_is_busy(&csi->q)) {
1166 		dev_err(csi->dev, "%s queue busy\n", __func__);
1167 		return -EBUSY;
1168 	}
1169 
1170 	cc = __imx7_csi_video_try_fmt(&f->fmt.pix, &csi->vdev_compose);
1171 
1172 	csi->vdev_cc = cc;
1173 	csi->vdev_fmt = f->fmt.pix;
1174 
1175 	return 0;
1176 }
1177 
1178 static int imx7_csi_video_g_selection(struct file *file, void *fh,
1179 				      struct v4l2_selection *s)
1180 {
1181 	struct imx7_csi *csi = video_drvdata(file);
1182 
1183 	if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1184 		return -EINVAL;
1185 
1186 	switch (s->target) {
1187 	case V4L2_SEL_TGT_COMPOSE:
1188 	case V4L2_SEL_TGT_COMPOSE_DEFAULT:
1189 	case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1190 		/* The compose rectangle is fixed to the source format. */
1191 		s->r = csi->vdev_compose;
1192 		break;
1193 	case V4L2_SEL_TGT_COMPOSE_PADDED:
1194 		/*
1195 		 * The hardware writes with a configurable but fixed DMA burst
1196 		 * size. If the source format width is not burst size aligned,
1197 		 * the written frame contains padding to the right.
1198 		 */
1199 		s->r.left = 0;
1200 		s->r.top = 0;
1201 		s->r.width = csi->vdev_fmt.width;
1202 		s->r.height = csi->vdev_fmt.height;
1203 		break;
1204 	default:
1205 		return -EINVAL;
1206 	}
1207 
1208 	return 0;
1209 }
1210 
1211 static const struct v4l2_ioctl_ops imx7_csi_video_ioctl_ops = {
1212 	.vidioc_querycap		= imx7_csi_video_querycap,
1213 
1214 	.vidioc_enum_fmt_vid_cap	= imx7_csi_video_enum_fmt_vid_cap,
1215 	.vidioc_enum_framesizes		= imx7_csi_video_enum_framesizes,
1216 
1217 	.vidioc_g_fmt_vid_cap		= imx7_csi_video_g_fmt_vid_cap,
1218 	.vidioc_try_fmt_vid_cap		= imx7_csi_video_try_fmt_vid_cap,
1219 	.vidioc_s_fmt_vid_cap		= imx7_csi_video_s_fmt_vid_cap,
1220 
1221 	.vidioc_g_selection		= imx7_csi_video_g_selection,
1222 
1223 	.vidioc_reqbufs			= vb2_ioctl_reqbufs,
1224 	.vidioc_create_bufs		= vb2_ioctl_create_bufs,
1225 	.vidioc_prepare_buf		= vb2_ioctl_prepare_buf,
1226 	.vidioc_querybuf		= vb2_ioctl_querybuf,
1227 	.vidioc_qbuf			= vb2_ioctl_qbuf,
1228 	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
1229 	.vidioc_expbuf			= vb2_ioctl_expbuf,
1230 	.vidioc_streamon		= vb2_ioctl_streamon,
1231 	.vidioc_streamoff		= vb2_ioctl_streamoff,
1232 };
1233 
1234 /* -----------------------------------------------------------------------------
1235  * Video Capture Device - Queue Operations
1236  */
1237 
1238 static int imx7_csi_video_queue_setup(struct vb2_queue *vq,
1239 				      unsigned int *nbuffers,
1240 				      unsigned int *nplanes,
1241 				      unsigned int sizes[],
1242 				      struct device *alloc_devs[])
1243 {
1244 	struct imx7_csi *csi = vb2_get_drv_priv(vq);
1245 	struct v4l2_pix_format *pix = &csi->vdev_fmt;
1246 	unsigned int count = *nbuffers;
1247 
1248 	if (vq->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1249 		return -EINVAL;
1250 
1251 	if (*nplanes) {
1252 		if (*nplanes != 1 || sizes[0] < pix->sizeimage)
1253 			return -EINVAL;
1254 		count += vq->num_buffers;
1255 	}
1256 
1257 	count = min_t(__u32, IMX7_CSI_VIDEO_MEM_LIMIT / pix->sizeimage, count);
1258 
1259 	if (*nplanes)
1260 		*nbuffers = (count < vq->num_buffers) ? 0 :
1261 			count - vq->num_buffers;
1262 	else
1263 		*nbuffers = count;
1264 
1265 	*nplanes = 1;
1266 	sizes[0] = pix->sizeimage;
1267 
1268 	return 0;
1269 }
1270 
1271 static int imx7_csi_video_buf_init(struct vb2_buffer *vb)
1272 {
1273 	struct imx7_csi_vb2_buffer *buf = to_imx7_csi_vb2_buffer(vb);
1274 
1275 	INIT_LIST_HEAD(&buf->list);
1276 
1277 	return 0;
1278 }
1279 
1280 static int imx7_csi_video_buf_prepare(struct vb2_buffer *vb)
1281 {
1282 	struct imx7_csi *csi = vb2_get_drv_priv(vb->vb2_queue);
1283 	struct v4l2_pix_format *pix = &csi->vdev_fmt;
1284 
1285 	if (vb2_plane_size(vb, 0) < pix->sizeimage) {
1286 		dev_err(csi->dev,
1287 			"data will not fit into plane (%lu < %lu)\n",
1288 			vb2_plane_size(vb, 0), (long)pix->sizeimage);
1289 		return -EINVAL;
1290 	}
1291 
1292 	vb2_set_plane_payload(vb, 0, pix->sizeimage);
1293 
1294 	return 0;
1295 }
1296 
1297 static bool imx7_csi_fast_track_buffer(struct imx7_csi *csi,
1298 				       struct imx7_csi_vb2_buffer *buf)
1299 {
1300 	unsigned long flags;
1301 	dma_addr_t dma_addr;
1302 	int buf_num;
1303 	u32 isr;
1304 
1305 	if (!csi->is_streaming)
1306 		return false;
1307 
1308 	dma_addr = vb2_dma_contig_plane_dma_addr(&buf->vbuf.vb2_buf, 0);
1309 
1310 	/*
1311 	 * buf_num holds the framebuffer ID of the most recently (*not* the
1312 	 * next anticipated) triggered interrupt. Without loss of generality,
1313 	 * if buf_num is 0, the hardware is capturing to FB2. If FB1 has been
1314 	 * programmed with a dummy buffer (as indicated by active_vb2_buf[0]
1315 	 * being NULL), then we can fast-track the new buffer by programming
1316 	 * its address in FB1 before the hardware completes FB2, instead of
1317 	 * adding it to the buffer queue and incurring a delay of one
1318 	 * additional frame.
1319 	 *
1320 	 * The irqlock prevents races with the interrupt handler that updates
1321 	 * buf_num when it programs the next buffer, but we can still race with
1322 	 * the hardware if we program the buffer in FB1 just after the hardware
1323 	 * completes FB2 and switches to FB1 and before buf_num can be updated
1324 	 * by the interrupt handler for FB2.  The fast-tracked buffer would
1325 	 * then be ignored by the hardware while the driver would think it has
1326 	 * successfully been processed.
1327 	 *
1328 	 * To avoid this problem, if we can't avoid the race, we can detect
1329 	 * that we have lost it by checking, after programming the buffer in
1330 	 * FB1, if the interrupt flag indicating completion of FB2 has been
1331 	 * raised. If that is not the case, fast-tracking succeeded, and we can
1332 	 * update active_vb2_buf[0]. Otherwise, we may or may not have lost the
1333 	 * race (as the interrupt flag may have been raised just after
1334 	 * programming FB1 and before we read the interrupt status register),
1335 	 * and we need to assume the worst case of a race loss and queue the
1336 	 * buffer through the slow path.
1337 	 */
1338 
1339 	spin_lock_irqsave(&csi->irqlock, flags);
1340 
1341 	buf_num = csi->buf_num;
1342 	if (csi->active_vb2_buf[buf_num]) {
1343 		spin_unlock_irqrestore(&csi->irqlock, flags);
1344 		return false;
1345 	}
1346 
1347 	imx7_csi_update_buf(csi, dma_addr, buf_num);
1348 
1349 	isr = imx7_csi_reg_read(csi, CSI_CSISR);
1350 	if (isr & (buf_num ? BIT_DMA_TSF_DONE_FB1 : BIT_DMA_TSF_DONE_FB2)) {
1351 		/*
1352 		 * The interrupt for the /other/ FB just came (the isr hasn't
1353 		 * run yet though, because we have the lock here); we can't be
1354 		 * sure we've programmed buf_num FB in time, so queue the buffer
1355 		 * to the buffer queue normally. No need to undo writing the FB
1356 		 * register, since we won't return it as active_vb2_buf is NULL,
1357 		 * so it's okay to potentially write it to both FB1 and FB2;
1358 		 * only the one where it was queued normally will be returned.
1359 		 */
1360 		spin_unlock_irqrestore(&csi->irqlock, flags);
1361 		return false;
1362 	}
1363 
1364 	csi->active_vb2_buf[buf_num] = buf;
1365 
1366 	spin_unlock_irqrestore(&csi->irqlock, flags);
1367 	return true;
1368 }
1369 
1370 static void imx7_csi_video_buf_queue(struct vb2_buffer *vb)
1371 {
1372 	struct imx7_csi *csi = vb2_get_drv_priv(vb->vb2_queue);
1373 	struct imx7_csi_vb2_buffer *buf = to_imx7_csi_vb2_buffer(vb);
1374 	unsigned long flags;
1375 
1376 	if (imx7_csi_fast_track_buffer(csi, buf))
1377 		return;
1378 
1379 	spin_lock_irqsave(&csi->q_lock, flags);
1380 
1381 	list_add_tail(&buf->list, &csi->ready_q);
1382 
1383 	spin_unlock_irqrestore(&csi->q_lock, flags);
1384 }
1385 
1386 static int imx7_csi_video_validate_fmt(struct imx7_csi *csi)
1387 {
1388 	struct v4l2_subdev_format fmt_src = {
1389 		.pad = IMX7_CSI_PAD_SRC,
1390 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
1391 	};
1392 	const struct imx7_csi_pixfmt *cc;
1393 	int ret;
1394 
1395 	/* Retrieve the media bus format on the source subdev. */
1396 	ret = v4l2_subdev_call_state_active(&csi->sd, pad, get_fmt, &fmt_src);
1397 	if (ret)
1398 		return ret;
1399 
1400 	/*
1401 	 * Verify that the media bus size matches the size set on the video
1402 	 * node. It is sufficient to check the compose rectangle size without
1403 	 * checking the rounded size from pix_fmt, as the rounded size is
1404 	 * derived directly from the compose rectangle size, and will thus
1405 	 * always match if the compose rectangle matches.
1406 	 */
1407 	if (csi->vdev_compose.width != fmt_src.format.width ||
1408 	    csi->vdev_compose.height != fmt_src.format.height)
1409 		return -EPIPE;
1410 
1411 	/*
1412 	 * Verify that the media bus code is compatible with the pixel format
1413 	 * set on the video node.
1414 	 */
1415 	cc = imx7_csi_find_mbus_format(fmt_src.format.code);
1416 	if (!cc || csi->vdev_cc->yuv != cc->yuv)
1417 		return -EPIPE;
1418 
1419 	return 0;
1420 }
1421 
1422 static int imx7_csi_video_start_streaming(struct vb2_queue *vq,
1423 					  unsigned int count)
1424 {
1425 	struct imx7_csi *csi = vb2_get_drv_priv(vq);
1426 	struct imx7_csi_vb2_buffer *buf, *tmp;
1427 	unsigned long flags;
1428 	int ret;
1429 
1430 	ret = imx7_csi_video_validate_fmt(csi);
1431 	if (ret) {
1432 		dev_err(csi->dev, "capture format not valid\n");
1433 		goto err_buffers;
1434 	}
1435 
1436 	mutex_lock(&csi->mdev.graph_mutex);
1437 
1438 	ret = __video_device_pipeline_start(csi->vdev, &csi->pipe);
1439 	if (ret)
1440 		goto err_unlock;
1441 
1442 	ret = v4l2_subdev_call(&csi->sd, video, s_stream, 1);
1443 	if (ret)
1444 		goto err_stop;
1445 
1446 	mutex_unlock(&csi->mdev.graph_mutex);
1447 
1448 	return 0;
1449 
1450 err_stop:
1451 	__video_device_pipeline_stop(csi->vdev);
1452 err_unlock:
1453 	mutex_unlock(&csi->mdev.graph_mutex);
1454 	dev_err(csi->dev, "pipeline start failed with %d\n", ret);
1455 err_buffers:
1456 	spin_lock_irqsave(&csi->q_lock, flags);
1457 	list_for_each_entry_safe(buf, tmp, &csi->ready_q, list) {
1458 		list_del(&buf->list);
1459 		vb2_buffer_done(&buf->vbuf.vb2_buf, VB2_BUF_STATE_QUEUED);
1460 	}
1461 	spin_unlock_irqrestore(&csi->q_lock, flags);
1462 	return ret;
1463 }
1464 
1465 static void imx7_csi_video_stop_streaming(struct vb2_queue *vq)
1466 {
1467 	struct imx7_csi *csi = vb2_get_drv_priv(vq);
1468 	struct imx7_csi_vb2_buffer *frame;
1469 	struct imx7_csi_vb2_buffer *tmp;
1470 	unsigned long flags;
1471 
1472 	mutex_lock(&csi->mdev.graph_mutex);
1473 	v4l2_subdev_call(&csi->sd, video, s_stream, 0);
1474 	__video_device_pipeline_stop(csi->vdev);
1475 	mutex_unlock(&csi->mdev.graph_mutex);
1476 
1477 	/* release all active buffers */
1478 	spin_lock_irqsave(&csi->q_lock, flags);
1479 	list_for_each_entry_safe(frame, tmp, &csi->ready_q, list) {
1480 		list_del(&frame->list);
1481 		vb2_buffer_done(&frame->vbuf.vb2_buf, VB2_BUF_STATE_ERROR);
1482 	}
1483 	spin_unlock_irqrestore(&csi->q_lock, flags);
1484 }
1485 
1486 static const struct vb2_ops imx7_csi_video_qops = {
1487 	.queue_setup	 = imx7_csi_video_queue_setup,
1488 	.buf_init        = imx7_csi_video_buf_init,
1489 	.buf_prepare	 = imx7_csi_video_buf_prepare,
1490 	.buf_queue	 = imx7_csi_video_buf_queue,
1491 	.wait_prepare	 = vb2_ops_wait_prepare,
1492 	.wait_finish	 = vb2_ops_wait_finish,
1493 	.start_streaming = imx7_csi_video_start_streaming,
1494 	.stop_streaming  = imx7_csi_video_stop_streaming,
1495 };
1496 
1497 /* -----------------------------------------------------------------------------
1498  * Video Capture Device - File Operations
1499  */
1500 
1501 static int imx7_csi_video_open(struct file *file)
1502 {
1503 	struct imx7_csi *csi = video_drvdata(file);
1504 	int ret;
1505 
1506 	if (mutex_lock_interruptible(&csi->vdev_mutex))
1507 		return -ERESTARTSYS;
1508 
1509 	ret = v4l2_fh_open(file);
1510 	if (ret) {
1511 		dev_err(csi->dev, "v4l2_fh_open failed\n");
1512 		goto out;
1513 	}
1514 
1515 	ret = v4l2_pipeline_pm_get(&csi->vdev->entity);
1516 	if (ret)
1517 		v4l2_fh_release(file);
1518 
1519 out:
1520 	mutex_unlock(&csi->vdev_mutex);
1521 	return ret;
1522 }
1523 
1524 static int imx7_csi_video_release(struct file *file)
1525 {
1526 	struct imx7_csi *csi = video_drvdata(file);
1527 	struct vb2_queue *vq = &csi->q;
1528 
1529 	mutex_lock(&csi->vdev_mutex);
1530 
1531 	if (file->private_data == vq->owner) {
1532 		vb2_queue_release(vq);
1533 		vq->owner = NULL;
1534 	}
1535 
1536 	v4l2_pipeline_pm_put(&csi->vdev->entity);
1537 
1538 	v4l2_fh_release(file);
1539 	mutex_unlock(&csi->vdev_mutex);
1540 	return 0;
1541 }
1542 
1543 static const struct v4l2_file_operations imx7_csi_video_fops = {
1544 	.owner		= THIS_MODULE,
1545 	.open		= imx7_csi_video_open,
1546 	.release	= imx7_csi_video_release,
1547 	.poll		= vb2_fop_poll,
1548 	.unlocked_ioctl	= video_ioctl2,
1549 	.mmap		= vb2_fop_mmap,
1550 };
1551 
1552 /* -----------------------------------------------------------------------------
1553  * Video Capture Device - Init & Cleanup
1554  */
1555 
1556 static struct imx7_csi_vb2_buffer *imx7_csi_video_next_buf(struct imx7_csi *csi)
1557 {
1558 	struct imx7_csi_vb2_buffer *buf = NULL;
1559 	unsigned long flags;
1560 
1561 	spin_lock_irqsave(&csi->q_lock, flags);
1562 
1563 	/* get next queued buffer */
1564 	if (!list_empty(&csi->ready_q)) {
1565 		buf = list_entry(csi->ready_q.next, struct imx7_csi_vb2_buffer,
1566 				 list);
1567 		list_del(&buf->list);
1568 	}
1569 
1570 	spin_unlock_irqrestore(&csi->q_lock, flags);
1571 
1572 	return buf;
1573 }
1574 
1575 static void imx7_csi_video_init_format(struct imx7_csi *csi)
1576 {
1577 	struct v4l2_pix_format *pixfmt = &csi->vdev_fmt;
1578 
1579 	pixfmt->width = IMX7_CSI_DEF_PIX_WIDTH;
1580 	pixfmt->height = IMX7_CSI_DEF_PIX_HEIGHT;
1581 
1582 	csi->vdev_cc = __imx7_csi_video_try_fmt(pixfmt, &csi->vdev_compose);
1583 }
1584 
1585 static int imx7_csi_video_register(struct imx7_csi *csi)
1586 {
1587 	struct v4l2_subdev *sd = &csi->sd;
1588 	struct v4l2_device *v4l2_dev = sd->v4l2_dev;
1589 	struct video_device *vdev = csi->vdev;
1590 	int ret;
1591 
1592 	vdev->v4l2_dev = v4l2_dev;
1593 
1594 	/* Initialize the default format and compose rectangle. */
1595 	imx7_csi_video_init_format(csi);
1596 
1597 	/* Register the video device. */
1598 	ret = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
1599 	if (ret) {
1600 		dev_err(csi->dev, "Failed to register video device\n");
1601 		return ret;
1602 	}
1603 
1604 	dev_info(csi->dev, "Registered %s as /dev/%s\n", vdev->name,
1605 		 video_device_node_name(vdev));
1606 
1607 	/* Create the link from the CSI subdev to the video device. */
1608 	ret = media_create_pad_link(&sd->entity, IMX7_CSI_PAD_SRC,
1609 				    &vdev->entity, 0, MEDIA_LNK_FL_IMMUTABLE |
1610 				    MEDIA_LNK_FL_ENABLED);
1611 	if (ret) {
1612 		dev_err(csi->dev, "failed to create link to device node\n");
1613 		video_unregister_device(vdev);
1614 		return ret;
1615 	}
1616 
1617 	return 0;
1618 }
1619 
1620 static void imx7_csi_video_unregister(struct imx7_csi *csi)
1621 {
1622 	media_entity_cleanup(&csi->vdev->entity);
1623 	video_unregister_device(csi->vdev);
1624 }
1625 
1626 static int imx7_csi_video_init(struct imx7_csi *csi)
1627 {
1628 	struct video_device *vdev;
1629 	struct vb2_queue *vq;
1630 	int ret;
1631 
1632 	mutex_init(&csi->vdev_mutex);
1633 	INIT_LIST_HEAD(&csi->ready_q);
1634 	spin_lock_init(&csi->q_lock);
1635 
1636 	/* Allocate and initialize the video device. */
1637 	vdev = video_device_alloc();
1638 	if (!vdev)
1639 		return -ENOMEM;
1640 
1641 	vdev->fops = &imx7_csi_video_fops;
1642 	vdev->ioctl_ops = &imx7_csi_video_ioctl_ops;
1643 	vdev->minor = -1;
1644 	vdev->release = video_device_release;
1645 	vdev->vfl_dir = VFL_DIR_RX;
1646 	vdev->tvnorms = V4L2_STD_NTSC | V4L2_STD_PAL | V4L2_STD_SECAM;
1647 	vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING
1648 			 | V4L2_CAP_IO_MC;
1649 	vdev->lock = &csi->vdev_mutex;
1650 	vdev->queue = &csi->q;
1651 
1652 	snprintf(vdev->name, sizeof(vdev->name), "%s capture", csi->sd.name);
1653 
1654 	video_set_drvdata(vdev, csi);
1655 	csi->vdev = vdev;
1656 
1657 	/* Initialize the video device pad. */
1658 	csi->vdev_pad.flags = MEDIA_PAD_FL_SINK;
1659 	ret = media_entity_pads_init(&vdev->entity, 1, &csi->vdev_pad);
1660 	if (ret) {
1661 		video_device_release(vdev);
1662 		return ret;
1663 	}
1664 
1665 	/* Initialize the vb2 queue. */
1666 	vq = &csi->q;
1667 	vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1668 	vq->io_modes = VB2_MMAP | VB2_DMABUF;
1669 	vq->drv_priv = csi;
1670 	vq->buf_struct_size = sizeof(struct imx7_csi_vb2_buffer);
1671 	vq->ops = &imx7_csi_video_qops;
1672 	vq->mem_ops = &vb2_dma_contig_memops;
1673 	vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1674 	vq->lock = &csi->vdev_mutex;
1675 	vq->min_buffers_needed = 2;
1676 	vq->dev = csi->dev;
1677 
1678 	ret = vb2_queue_init(vq);
1679 	if (ret) {
1680 		dev_err(csi->dev, "vb2_queue_init failed\n");
1681 		video_device_release(vdev);
1682 		return ret;
1683 	}
1684 
1685 	return 0;
1686 }
1687 
1688 /* -----------------------------------------------------------------------------
1689  * V4L2 Subdev Operations
1690  */
1691 
1692 static int imx7_csi_s_stream(struct v4l2_subdev *sd, int enable)
1693 {
1694 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1695 	struct v4l2_subdev_state *sd_state;
1696 	int ret = 0;
1697 
1698 	sd_state = v4l2_subdev_lock_and_get_active_state(sd);
1699 
1700 	if (enable) {
1701 		ret = imx7_csi_init(csi, sd_state);
1702 		if (ret < 0)
1703 			goto out_unlock;
1704 
1705 		ret = v4l2_subdev_call(csi->src_sd, video, s_stream, 1);
1706 		if (ret < 0) {
1707 			imx7_csi_deinit(csi, VB2_BUF_STATE_QUEUED);
1708 			goto out_unlock;
1709 		}
1710 
1711 		imx7_csi_enable(csi);
1712 	} else {
1713 		imx7_csi_disable(csi);
1714 
1715 		v4l2_subdev_call(csi->src_sd, video, s_stream, 0);
1716 
1717 		imx7_csi_deinit(csi, VB2_BUF_STATE_ERROR);
1718 	}
1719 
1720 	csi->is_streaming = !!enable;
1721 
1722 out_unlock:
1723 	v4l2_subdev_unlock_state(sd_state);
1724 
1725 	return ret;
1726 }
1727 
1728 static int imx7_csi_init_cfg(struct v4l2_subdev *sd,
1729 			     struct v4l2_subdev_state *sd_state)
1730 {
1731 	const struct imx7_csi_pixfmt *cc;
1732 	int i;
1733 
1734 	cc = imx7_csi_find_mbus_format(IMX7_CSI_DEF_MBUS_CODE);
1735 
1736 	for (i = 0; i < IMX7_CSI_PADS_NUM; i++) {
1737 		struct v4l2_mbus_framefmt *mf =
1738 			v4l2_subdev_get_pad_format(sd, sd_state, i);
1739 
1740 		mf->code = IMX7_CSI_DEF_MBUS_CODE;
1741 		mf->width = IMX7_CSI_DEF_PIX_WIDTH;
1742 		mf->height = IMX7_CSI_DEF_PIX_HEIGHT;
1743 		mf->field = V4L2_FIELD_NONE;
1744 
1745 		mf->colorspace = V4L2_COLORSPACE_SRGB;
1746 		mf->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(mf->colorspace);
1747 		mf->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(mf->colorspace);
1748 		mf->quantization = V4L2_MAP_QUANTIZATION_DEFAULT(!cc->yuv,
1749 					mf->colorspace, mf->ycbcr_enc);
1750 	}
1751 
1752 	return 0;
1753 }
1754 
1755 static int imx7_csi_enum_mbus_code(struct v4l2_subdev *sd,
1756 				   struct v4l2_subdev_state *sd_state,
1757 				   struct v4l2_subdev_mbus_code_enum *code)
1758 {
1759 	struct v4l2_mbus_framefmt *in_fmt;
1760 	int ret = 0;
1761 
1762 	in_fmt = v4l2_subdev_get_pad_format(sd, sd_state, IMX7_CSI_PAD_SINK);
1763 
1764 	switch (code->pad) {
1765 	case IMX7_CSI_PAD_SINK:
1766 		ret = imx7_csi_enum_mbus_formats(&code->code, code->index);
1767 		break;
1768 
1769 	case IMX7_CSI_PAD_SRC:
1770 		if (code->index != 0) {
1771 			ret = -EINVAL;
1772 			break;
1773 		}
1774 
1775 		code->code = in_fmt->code;
1776 		break;
1777 
1778 	default:
1779 		ret = -EINVAL;
1780 		break;
1781 	}
1782 
1783 	return ret;
1784 }
1785 
1786 /*
1787  * Default the colorspace in tryfmt to SRGB if set to an unsupported
1788  * colorspace or not initialized. Then set the remaining colorimetry
1789  * parameters based on the colorspace if they are uninitialized.
1790  *
1791  * tryfmt->code must be set on entry.
1792  */
1793 static void imx7_csi_try_colorimetry(struct v4l2_mbus_framefmt *tryfmt)
1794 {
1795 	const struct imx7_csi_pixfmt *cc;
1796 	bool is_rgb = false;
1797 
1798 	cc = imx7_csi_find_mbus_format(tryfmt->code);
1799 	if (cc && !cc->yuv)
1800 		is_rgb = true;
1801 
1802 	switch (tryfmt->colorspace) {
1803 	case V4L2_COLORSPACE_SMPTE170M:
1804 	case V4L2_COLORSPACE_REC709:
1805 	case V4L2_COLORSPACE_JPEG:
1806 	case V4L2_COLORSPACE_SRGB:
1807 	case V4L2_COLORSPACE_BT2020:
1808 	case V4L2_COLORSPACE_OPRGB:
1809 	case V4L2_COLORSPACE_DCI_P3:
1810 	case V4L2_COLORSPACE_RAW:
1811 		break;
1812 	default:
1813 		tryfmt->colorspace = V4L2_COLORSPACE_SRGB;
1814 		break;
1815 	}
1816 
1817 	if (tryfmt->xfer_func == V4L2_XFER_FUNC_DEFAULT)
1818 		tryfmt->xfer_func =
1819 			V4L2_MAP_XFER_FUNC_DEFAULT(tryfmt->colorspace);
1820 
1821 	if (tryfmt->ycbcr_enc == V4L2_YCBCR_ENC_DEFAULT)
1822 		tryfmt->ycbcr_enc =
1823 			V4L2_MAP_YCBCR_ENC_DEFAULT(tryfmt->colorspace);
1824 
1825 	if (tryfmt->quantization == V4L2_QUANTIZATION_DEFAULT)
1826 		tryfmt->quantization =
1827 			V4L2_MAP_QUANTIZATION_DEFAULT(is_rgb,
1828 						      tryfmt->colorspace,
1829 						      tryfmt->ycbcr_enc);
1830 }
1831 
1832 static void imx7_csi_try_fmt(struct v4l2_subdev *sd,
1833 			     struct v4l2_subdev_state *sd_state,
1834 			     struct v4l2_subdev_format *sdformat,
1835 			     const struct imx7_csi_pixfmt **cc)
1836 {
1837 	const struct imx7_csi_pixfmt *in_cc;
1838 	struct v4l2_mbus_framefmt *in_fmt;
1839 	u32 code;
1840 
1841 	in_fmt = v4l2_subdev_get_pad_format(sd, sd_state, IMX7_CSI_PAD_SINK);
1842 
1843 	switch (sdformat->pad) {
1844 	case IMX7_CSI_PAD_SRC:
1845 		in_cc = imx7_csi_find_mbus_format(in_fmt->code);
1846 
1847 		sdformat->format.width = in_fmt->width;
1848 		sdformat->format.height = in_fmt->height;
1849 		sdformat->format.code = in_fmt->code;
1850 		sdformat->format.field = in_fmt->field;
1851 		*cc = in_cc;
1852 
1853 		sdformat->format.colorspace = in_fmt->colorspace;
1854 		sdformat->format.xfer_func = in_fmt->xfer_func;
1855 		sdformat->format.quantization = in_fmt->quantization;
1856 		sdformat->format.ycbcr_enc = in_fmt->ycbcr_enc;
1857 		break;
1858 
1859 	case IMX7_CSI_PAD_SINK:
1860 		*cc = imx7_csi_find_mbus_format(sdformat->format.code);
1861 		if (!*cc) {
1862 			code = IMX7_CSI_DEF_MBUS_CODE;
1863 			*cc = imx7_csi_find_mbus_format(code);
1864 			sdformat->format.code = code;
1865 		}
1866 
1867 		if (sdformat->format.field != V4L2_FIELD_INTERLACED)
1868 			sdformat->format.field = V4L2_FIELD_NONE;
1869 		break;
1870 	}
1871 
1872 	imx7_csi_try_colorimetry(&sdformat->format);
1873 }
1874 
1875 static int imx7_csi_set_fmt(struct v4l2_subdev *sd,
1876 			    struct v4l2_subdev_state *sd_state,
1877 			    struct v4l2_subdev_format *sdformat)
1878 {
1879 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1880 	const struct imx7_csi_pixfmt *outcc;
1881 	struct v4l2_mbus_framefmt *outfmt;
1882 	const struct imx7_csi_pixfmt *cc;
1883 	struct v4l2_mbus_framefmt *fmt;
1884 	struct v4l2_subdev_format format;
1885 
1886 	if (csi->is_streaming)
1887 		return -EBUSY;
1888 
1889 	imx7_csi_try_fmt(sd, sd_state, sdformat, &cc);
1890 
1891 	fmt = v4l2_subdev_get_pad_format(sd, sd_state, sdformat->pad);
1892 
1893 	*fmt = sdformat->format;
1894 
1895 	if (sdformat->pad == IMX7_CSI_PAD_SINK) {
1896 		/* propagate format to source pads */
1897 		format.pad = IMX7_CSI_PAD_SRC;
1898 		format.which = sdformat->which;
1899 		format.format = sdformat->format;
1900 		imx7_csi_try_fmt(sd, sd_state, &format, &outcc);
1901 
1902 		outfmt = v4l2_subdev_get_pad_format(sd, sd_state,
1903 						    IMX7_CSI_PAD_SRC);
1904 		*outfmt = format.format;
1905 	}
1906 
1907 	return 0;
1908 }
1909 
1910 static int imx7_csi_pad_link_validate(struct v4l2_subdev *sd,
1911 				      struct media_link *link,
1912 				      struct v4l2_subdev_format *source_fmt,
1913 				      struct v4l2_subdev_format *sink_fmt)
1914 {
1915 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1916 	struct media_pad *pad = NULL;
1917 	unsigned int i;
1918 	int ret;
1919 
1920 	/*
1921 	 * Validate the source link, and record whether the source uses the
1922 	 * parallel input or the CSI-2 receiver.
1923 	 */
1924 	ret = v4l2_subdev_link_validate_default(sd, link, source_fmt, sink_fmt);
1925 	if (ret)
1926 		return ret;
1927 
1928 	switch (csi->src_sd->entity.function) {
1929 	case MEDIA_ENT_F_VID_IF_BRIDGE:
1930 		/* The input is the CSI-2 receiver. */
1931 		csi->is_csi2 = true;
1932 		break;
1933 
1934 	case MEDIA_ENT_F_VID_MUX:
1935 		/* The input is the mux, check its input. */
1936 		for (i = 0; i < csi->src_sd->entity.num_pads; i++) {
1937 			struct media_pad *spad = &csi->src_sd->entity.pads[i];
1938 
1939 			if (!(spad->flags & MEDIA_PAD_FL_SINK))
1940 				continue;
1941 
1942 			pad = media_pad_remote_pad_first(spad);
1943 			if (pad)
1944 				break;
1945 		}
1946 
1947 		if (!pad)
1948 			return -ENODEV;
1949 
1950 		csi->is_csi2 = pad->entity->function == MEDIA_ENT_F_VID_IF_BRIDGE;
1951 		break;
1952 
1953 	default:
1954 		/*
1955 		 * The input is an external entity, it must use the parallel
1956 		 * bus.
1957 		 */
1958 		csi->is_csi2 = false;
1959 		break;
1960 	}
1961 
1962 	return 0;
1963 }
1964 
1965 static int imx7_csi_registered(struct v4l2_subdev *sd)
1966 {
1967 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1968 	int ret;
1969 
1970 	ret = imx7_csi_video_init(csi);
1971 	if (ret)
1972 		return ret;
1973 
1974 	ret = imx7_csi_video_register(csi);
1975 	if (ret)
1976 		return ret;
1977 
1978 	ret = v4l2_device_register_subdev_nodes(&csi->v4l2_dev);
1979 	if (ret)
1980 		goto err_unreg;
1981 
1982 	ret = media_device_register(&csi->mdev);
1983 	if (ret)
1984 		goto err_unreg;
1985 
1986 	return 0;
1987 
1988 err_unreg:
1989 	imx7_csi_video_unregister(csi);
1990 	return ret;
1991 }
1992 
1993 static void imx7_csi_unregistered(struct v4l2_subdev *sd)
1994 {
1995 	struct imx7_csi *csi = v4l2_get_subdevdata(sd);
1996 
1997 	imx7_csi_video_unregister(csi);
1998 }
1999 
2000 static const struct v4l2_subdev_video_ops imx7_csi_video_ops = {
2001 	.s_stream	= imx7_csi_s_stream,
2002 };
2003 
2004 static const struct v4l2_subdev_pad_ops imx7_csi_pad_ops = {
2005 	.init_cfg	= imx7_csi_init_cfg,
2006 	.enum_mbus_code	= imx7_csi_enum_mbus_code,
2007 	.get_fmt	= v4l2_subdev_get_fmt,
2008 	.set_fmt	= imx7_csi_set_fmt,
2009 	.link_validate	= imx7_csi_pad_link_validate,
2010 };
2011 
2012 static const struct v4l2_subdev_ops imx7_csi_subdev_ops = {
2013 	.video		= &imx7_csi_video_ops,
2014 	.pad		= &imx7_csi_pad_ops,
2015 };
2016 
2017 static const struct v4l2_subdev_internal_ops imx7_csi_internal_ops = {
2018 	.registered	= imx7_csi_registered,
2019 	.unregistered	= imx7_csi_unregistered,
2020 };
2021 
2022 /* -----------------------------------------------------------------------------
2023  * Media Entity Operations
2024  */
2025 
2026 static const struct media_entity_operations imx7_csi_entity_ops = {
2027 	.link_validate	= v4l2_subdev_link_validate,
2028 	.get_fwnode_pad = v4l2_subdev_get_fwnode_pad_1_to_1,
2029 };
2030 
2031 /* -----------------------------------------------------------------------------
2032  * Probe & Remove
2033  */
2034 
2035 static int imx7_csi_notify_bound(struct v4l2_async_notifier *notifier,
2036 				 struct v4l2_subdev *sd,
2037 				 struct v4l2_async_connection *asd)
2038 {
2039 	struct imx7_csi *csi = imx7_csi_notifier_to_dev(notifier);
2040 	struct media_pad *sink = &csi->sd.entity.pads[IMX7_CSI_PAD_SINK];
2041 
2042 	csi->src_sd = sd;
2043 
2044 	return v4l2_create_fwnode_links_to_pad(sd, sink, MEDIA_LNK_FL_ENABLED |
2045 					       MEDIA_LNK_FL_IMMUTABLE);
2046 }
2047 
2048 static int imx7_csi_notify_complete(struct v4l2_async_notifier *notifier)
2049 {
2050 	struct imx7_csi *csi = imx7_csi_notifier_to_dev(notifier);
2051 
2052 	return v4l2_device_register_subdev_nodes(&csi->v4l2_dev);
2053 }
2054 
2055 static const struct v4l2_async_notifier_operations imx7_csi_notify_ops = {
2056 	.bound = imx7_csi_notify_bound,
2057 	.complete = imx7_csi_notify_complete,
2058 };
2059 
2060 static int imx7_csi_async_register(struct imx7_csi *csi)
2061 {
2062 	struct v4l2_async_connection *asd;
2063 	struct fwnode_handle *ep;
2064 	int ret;
2065 
2066 	v4l2_async_nf_init(&csi->notifier, &csi->v4l2_dev);
2067 
2068 	ep = fwnode_graph_get_endpoint_by_id(dev_fwnode(csi->dev), 0, 0,
2069 					     FWNODE_GRAPH_ENDPOINT_NEXT);
2070 	if (!ep) {
2071 		ret = dev_err_probe(csi->dev, -ENOTCONN,
2072 				    "Failed to get remote endpoint\n");
2073 		goto error;
2074 	}
2075 
2076 	asd = v4l2_async_nf_add_fwnode_remote(&csi->notifier, ep,
2077 					      struct v4l2_async_connection);
2078 
2079 	fwnode_handle_put(ep);
2080 
2081 	if (IS_ERR(asd)) {
2082 		ret = dev_err_probe(csi->dev, PTR_ERR(asd),
2083 				    "Failed to add remote subdev to notifier\n");
2084 		goto error;
2085 	}
2086 
2087 	csi->notifier.ops = &imx7_csi_notify_ops;
2088 
2089 	ret = v4l2_async_nf_register(&csi->notifier);
2090 	if (ret)
2091 		goto error;
2092 
2093 	return 0;
2094 
2095 error:
2096 	v4l2_async_nf_cleanup(&csi->notifier);
2097 	return ret;
2098 }
2099 
2100 static void imx7_csi_media_cleanup(struct imx7_csi *csi)
2101 {
2102 	v4l2_device_unregister(&csi->v4l2_dev);
2103 	media_device_unregister(&csi->mdev);
2104 	v4l2_subdev_cleanup(&csi->sd);
2105 	media_device_cleanup(&csi->mdev);
2106 }
2107 
2108 static const struct media_device_ops imx7_csi_media_ops = {
2109 	.link_notify = v4l2_pipeline_link_notify,
2110 };
2111 
2112 static int imx7_csi_media_dev_init(struct imx7_csi *csi)
2113 {
2114 	int ret;
2115 
2116 	strscpy(csi->mdev.model, "imx-media", sizeof(csi->mdev.model));
2117 	csi->mdev.ops = &imx7_csi_media_ops;
2118 	csi->mdev.dev = csi->dev;
2119 
2120 	csi->v4l2_dev.mdev = &csi->mdev;
2121 	strscpy(csi->v4l2_dev.name, "imx-media",
2122 		sizeof(csi->v4l2_dev.name));
2123 	snprintf(csi->mdev.bus_info, sizeof(csi->mdev.bus_info),
2124 		 "platform:%s", dev_name(csi->mdev.dev));
2125 
2126 	media_device_init(&csi->mdev);
2127 
2128 	ret = v4l2_device_register(csi->dev, &csi->v4l2_dev);
2129 	if (ret < 0) {
2130 		v4l2_err(&csi->v4l2_dev,
2131 			 "Failed to register v4l2_device: %d\n", ret);
2132 		goto cleanup;
2133 	}
2134 
2135 	return 0;
2136 
2137 cleanup:
2138 	media_device_cleanup(&csi->mdev);
2139 
2140 	return ret;
2141 }
2142 
2143 static int imx7_csi_media_init(struct imx7_csi *csi)
2144 {
2145 	unsigned int i;
2146 	int ret;
2147 
2148 	/* add media device */
2149 	ret = imx7_csi_media_dev_init(csi);
2150 	if (ret)
2151 		return ret;
2152 
2153 	v4l2_subdev_init(&csi->sd, &imx7_csi_subdev_ops);
2154 	v4l2_set_subdevdata(&csi->sd, csi);
2155 	csi->sd.internal_ops = &imx7_csi_internal_ops;
2156 	csi->sd.entity.ops = &imx7_csi_entity_ops;
2157 	csi->sd.entity.function = MEDIA_ENT_F_VID_IF_BRIDGE;
2158 	csi->sd.dev = csi->dev;
2159 	csi->sd.owner = THIS_MODULE;
2160 	csi->sd.flags = V4L2_SUBDEV_FL_HAS_DEVNODE;
2161 	snprintf(csi->sd.name, sizeof(csi->sd.name), "csi");
2162 
2163 	for (i = 0; i < IMX7_CSI_PADS_NUM; i++)
2164 		csi->pad[i].flags = (i == IMX7_CSI_PAD_SINK) ?
2165 			MEDIA_PAD_FL_SINK : MEDIA_PAD_FL_SOURCE;
2166 
2167 	ret = media_entity_pads_init(&csi->sd.entity, IMX7_CSI_PADS_NUM,
2168 				     csi->pad);
2169 	if (ret)
2170 		goto error;
2171 
2172 	ret = v4l2_subdev_init_finalize(&csi->sd);
2173 	if (ret)
2174 		goto error;
2175 
2176 	ret = v4l2_device_register_subdev(&csi->v4l2_dev, &csi->sd);
2177 	if (ret)
2178 		goto error;
2179 
2180 	return 0;
2181 
2182 error:
2183 	imx7_csi_media_cleanup(csi);
2184 	return ret;
2185 }
2186 
2187 static int imx7_csi_probe(struct platform_device *pdev)
2188 {
2189 	struct device *dev = &pdev->dev;
2190 	struct imx7_csi *csi;
2191 	int ret;
2192 
2193 	csi = devm_kzalloc(&pdev->dev, sizeof(*csi), GFP_KERNEL);
2194 	if (!csi)
2195 		return -ENOMEM;
2196 
2197 	csi->dev = dev;
2198 	platform_set_drvdata(pdev, csi);
2199 
2200 	spin_lock_init(&csi->irqlock);
2201 
2202 	/* Acquire resources and install interrupt handler. */
2203 	csi->mclk = devm_clk_get(&pdev->dev, "mclk");
2204 	if (IS_ERR(csi->mclk)) {
2205 		ret = PTR_ERR(csi->mclk);
2206 		dev_err(dev, "Failed to get mclk: %d", ret);
2207 		return ret;
2208 	}
2209 
2210 	csi->irq = platform_get_irq(pdev, 0);
2211 	if (csi->irq < 0)
2212 		return csi->irq;
2213 
2214 	csi->regbase = devm_platform_ioremap_resource(pdev, 0);
2215 	if (IS_ERR(csi->regbase))
2216 		return PTR_ERR(csi->regbase);
2217 
2218 	csi->model = (enum imx_csi_model)(uintptr_t)of_device_get_match_data(&pdev->dev);
2219 
2220 	ret = devm_request_irq(dev, csi->irq, imx7_csi_irq_handler, 0, "csi",
2221 			       (void *)csi);
2222 	if (ret < 0) {
2223 		dev_err(dev, "Request CSI IRQ failed.\n");
2224 		return ret;
2225 	}
2226 
2227 	/* Initialize all the media device infrastructure. */
2228 	ret = imx7_csi_media_init(csi);
2229 	if (ret)
2230 		return ret;
2231 
2232 	ret = imx7_csi_async_register(csi);
2233 	if (ret)
2234 		goto err_media_cleanup;
2235 
2236 	return 0;
2237 
2238 err_media_cleanup:
2239 	imx7_csi_media_cleanup(csi);
2240 
2241 	return ret;
2242 }
2243 
2244 static void imx7_csi_remove(struct platform_device *pdev)
2245 {
2246 	struct imx7_csi *csi = platform_get_drvdata(pdev);
2247 
2248 	imx7_csi_media_cleanup(csi);
2249 
2250 	v4l2_async_nf_unregister(&csi->notifier);
2251 	v4l2_async_nf_cleanup(&csi->notifier);
2252 	v4l2_async_unregister_subdev(&csi->sd);
2253 }
2254 
2255 static const struct of_device_id imx7_csi_of_match[] = {
2256 	{ .compatible = "fsl,imx8mq-csi", .data = (void *)IMX7_CSI_IMX8MQ },
2257 	{ .compatible = "fsl,imx7-csi", .data = (void *)IMX7_CSI_IMX7 },
2258 	{ .compatible = "fsl,imx6ul-csi", .data = (void *)IMX7_CSI_IMX7 },
2259 	{ },
2260 };
2261 MODULE_DEVICE_TABLE(of, imx7_csi_of_match);
2262 
2263 static struct platform_driver imx7_csi_driver = {
2264 	.probe = imx7_csi_probe,
2265 	.remove_new = imx7_csi_remove,
2266 	.driver = {
2267 		.of_match_table = imx7_csi_of_match,
2268 		.name = "imx7-csi",
2269 	},
2270 };
2271 module_platform_driver(imx7_csi_driver);
2272 
2273 MODULE_DESCRIPTION("i.MX7 CSI subdev driver");
2274 MODULE_AUTHOR("Rui Miguel Silva <rui.silva@linaro.org>");
2275 MODULE_LICENSE("GPL v2");
2276 MODULE_ALIAS("platform:imx7-csi");
2277