1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * V4L2 Capture CSI Subdev for Freescale i.MX5/6 SOC
4  *
5  * Copyright (c) 2014-2017 Mentor Graphics Inc.
6  * Copyright (C) 2017 Pengutronix, Philipp Zabel <kernel@pengutronix.de>
7  */
8 #include <linux/delay.h>
9 #include <linux/gcd.h>
10 #include <linux/interrupt.h>
11 #include <linux/module.h>
12 #include <linux/of_graph.h>
13 #include <linux/pinctrl/consumer.h>
14 #include <linux/platform_device.h>
15 #include <media/v4l2-ctrls.h>
16 #include <media/v4l2-device.h>
17 #include <media/v4l2-event.h>
18 #include <media/v4l2-fwnode.h>
19 #include <media/v4l2-mc.h>
20 #include <media/v4l2-subdev.h>
21 #include <media/videobuf2-dma-contig.h>
22 #include <video/imx-ipu-v3.h>
23 #include <media/imx.h>
24 #include "imx-media.h"
25 
26 /*
27  * Min/Max supported width and heights.
28  *
29  * We allow planar output, so we have to align width by 16 pixels
30  * to meet IDMAC alignment requirements.
31  *
32  * TODO: move this into pad format negotiation, if capture device
33  * has not requested planar formats, we should allow 8 pixel
34  * alignment.
35  */
36 #define MIN_W       32
37 #define MIN_H       32
38 #define MAX_W      4096
39 #define MAX_H      4096
40 #define W_ALIGN    1 /* multiple of 2 pixels */
41 #define H_ALIGN    1 /* multiple of 2 lines */
42 #define S_ALIGN    1 /* multiple of 2 */
43 
44 /*
45  * struct csi_skip_desc - CSI frame skipping descriptor
46  * @keep - number of frames kept per max_ratio frames
47  * @max_ratio - width of skip_smfc, written to MAX_RATIO bitfield
48  * @skip_smfc - skip pattern written to the SKIP_SMFC bitfield
49  */
50 struct csi_skip_desc {
51 	u8 keep;
52 	u8 max_ratio;
53 	u8 skip_smfc;
54 };
55 
56 struct csi_priv {
57 	struct device *dev;
58 	struct ipu_soc *ipu;
59 	struct v4l2_subdev sd;
60 	struct media_pad pad[CSI_NUM_PADS];
61 	struct v4l2_async_notifier notifier;
62 
63 	/* the video device at IDMAC output pad */
64 	struct imx_media_video_dev *vdev;
65 	struct imx_media_fim *fim;
66 	int csi_id;
67 	int smfc_id;
68 
69 	/* lock to protect all members below */
70 	struct mutex lock;
71 
72 	int active_output_pad;
73 
74 	struct ipuv3_channel *idmac_ch;
75 	struct ipu_smfc *smfc;
76 	struct ipu_csi *csi;
77 
78 	struct v4l2_mbus_framefmt format_mbus[CSI_NUM_PADS];
79 	const struct imx_media_pixfmt *cc[CSI_NUM_PADS];
80 	struct v4l2_fract frame_interval[CSI_NUM_PADS];
81 	struct v4l2_rect crop;
82 	struct v4l2_rect compose;
83 	const struct csi_skip_desc *skip;
84 
85 	/* active vb2 buffers to send to video dev sink */
86 	struct imx_media_buffer *active_vb2_buf[2];
87 	struct imx_media_dma_buf underrun_buf;
88 
89 	int ipu_buf_num;  /* ipu double buffer index: 0-1 */
90 
91 	/* the sink for the captured frames */
92 	struct media_entity *sink;
93 	enum ipu_csi_dest dest;
94 	/* the source subdev */
95 	struct v4l2_subdev *src_sd;
96 
97 	/* the mipi virtual channel number at link validate */
98 	int vc_num;
99 
100 	/* the upstream endpoint CSI is receiving from */
101 	struct v4l2_fwnode_endpoint upstream_ep;
102 
103 	spinlock_t irqlock; /* protect eof_irq handler */
104 	struct timer_list eof_timeout_timer;
105 	int eof_irq;
106 	int nfb4eof_irq;
107 
108 	struct v4l2_ctrl_handler ctrl_hdlr;
109 
110 	int stream_count; /* streaming counter */
111 	u32 frame_sequence; /* frame sequence counter */
112 	bool last_eof;   /* waiting for last EOF at stream off */
113 	bool nfb4eof;    /* NFB4EOF encountered during streaming */
114 	bool interweave_swap; /* swap top/bottom lines when interweaving */
115 	struct completion last_eof_comp;
116 };
117 
118 static inline struct csi_priv *sd_to_dev(struct v4l2_subdev *sdev)
119 {
120 	return container_of(sdev, struct csi_priv, sd);
121 }
122 
123 static inline struct csi_priv *notifier_to_dev(struct v4l2_async_notifier *n)
124 {
125 	return container_of(n, struct csi_priv, notifier);
126 }
127 
128 static inline bool is_parallel_bus(struct v4l2_fwnode_endpoint *ep)
129 {
130 	return ep->bus_type != V4L2_MBUS_CSI2_DPHY;
131 }
132 
133 static inline bool is_parallel_16bit_bus(struct v4l2_fwnode_endpoint *ep)
134 {
135 	return is_parallel_bus(ep) && ep->bus.parallel.bus_width >= 16;
136 }
137 
138 /*
139  * Check for conditions that require the IPU to handle the
140  * data internally as generic data, aka passthrough mode:
141  * - raw bayer media bus formats, or
142  * - BT.656 and BT.1120 (8/10-bit YUV422) data can always be processed
143  *   on-the-fly
144  * - the CSI is receiving from a 16-bit parallel bus, or
145  * - the CSI is receiving from an 8-bit parallel bus and the incoming
146  *   media bus format is other than UYVY8_2X8/YUYV8_2X8.
147  */
148 static inline bool requires_passthrough(struct v4l2_fwnode_endpoint *ep,
149 					struct v4l2_mbus_framefmt *infmt,
150 					const struct imx_media_pixfmt *incc)
151 {
152 	if (ep->bus_type == V4L2_MBUS_BT656) // including BT.1120
153 		return false;
154 
155 	return incc->bayer || is_parallel_16bit_bus(ep) ||
156 		(is_parallel_bus(ep) &&
157 		 infmt->code != MEDIA_BUS_FMT_UYVY8_2X8 &&
158 		 infmt->code != MEDIA_BUS_FMT_YUYV8_2X8);
159 }
160 
161 /*
162  * Parses the fwnode endpoint from the source pad of the entity
163  * connected to this CSI. This will either be the entity directly
164  * upstream from the CSI-2 receiver, directly upstream from the
165  * video mux, or directly upstream from the CSI itself. The endpoint
166  * is needed to determine the bus type and bus config coming into
167  * the CSI.
168  */
169 static int csi_get_upstream_endpoint(struct csi_priv *priv,
170 				     struct v4l2_fwnode_endpoint *ep)
171 {
172 	struct fwnode_handle *endpoint;
173 	struct v4l2_subdev *sd;
174 	struct media_pad *pad;
175 
176 	if (!IS_ENABLED(CONFIG_OF))
177 		return -ENXIO;
178 
179 	if (!priv->src_sd)
180 		return -EPIPE;
181 
182 	sd = priv->src_sd;
183 
184 	switch (sd->grp_id) {
185 	case IMX_MEDIA_GRP_ID_CSI_MUX:
186 		/*
187 		 * CSI is connected directly to CSI mux, skip up to
188 		 * CSI-2 receiver if it is in the path, otherwise stay
189 		 * with the CSI mux.
190 		 */
191 		sd = imx_media_pipeline_subdev(&sd->entity,
192 					       IMX_MEDIA_GRP_ID_CSI2,
193 					       true);
194 		if (IS_ERR(sd))
195 			sd = priv->src_sd;
196 		break;
197 	case IMX_MEDIA_GRP_ID_CSI2:
198 		break;
199 	default:
200 		/*
201 		 * the source is neither the CSI mux nor the CSI-2 receiver,
202 		 * get the source pad directly upstream from CSI itself.
203 		 */
204 		sd = &priv->sd;
205 		break;
206 	}
207 
208 	/* get source pad of entity directly upstream from sd */
209 	pad = imx_media_pipeline_pad(&sd->entity, 0, 0, true);
210 	if (!pad)
211 		return -ENODEV;
212 
213 	endpoint = imx_media_get_pad_fwnode(pad);
214 	if (IS_ERR(endpoint))
215 		return PTR_ERR(endpoint);
216 
217 	v4l2_fwnode_endpoint_parse(endpoint, ep);
218 
219 	fwnode_handle_put(endpoint);
220 
221 	return 0;
222 }
223 
224 static void csi_idmac_put_ipu_resources(struct csi_priv *priv)
225 {
226 	if (priv->idmac_ch)
227 		ipu_idmac_put(priv->idmac_ch);
228 	priv->idmac_ch = NULL;
229 
230 	if (priv->smfc)
231 		ipu_smfc_put(priv->smfc);
232 	priv->smfc = NULL;
233 }
234 
235 static int csi_idmac_get_ipu_resources(struct csi_priv *priv)
236 {
237 	int ch_num, ret;
238 	struct ipu_smfc *smfc;
239 	struct ipuv3_channel *idmac_ch;
240 
241 	ch_num = IPUV3_CHANNEL_CSI0 + priv->smfc_id;
242 
243 	smfc = ipu_smfc_get(priv->ipu, ch_num);
244 	if (IS_ERR(smfc)) {
245 		v4l2_err(&priv->sd, "failed to get SMFC\n");
246 		ret = PTR_ERR(smfc);
247 		goto out;
248 	}
249 	priv->smfc = smfc;
250 
251 	idmac_ch = ipu_idmac_get(priv->ipu, ch_num);
252 	if (IS_ERR(idmac_ch)) {
253 		v4l2_err(&priv->sd, "could not get IDMAC channel %u\n",
254 			 ch_num);
255 		ret = PTR_ERR(idmac_ch);
256 		goto out;
257 	}
258 	priv->idmac_ch = idmac_ch;
259 
260 	return 0;
261 out:
262 	csi_idmac_put_ipu_resources(priv);
263 	return ret;
264 }
265 
266 static void csi_vb2_buf_done(struct csi_priv *priv)
267 {
268 	struct imx_media_video_dev *vdev = priv->vdev;
269 	struct imx_media_buffer *done, *next;
270 	struct vb2_buffer *vb;
271 	dma_addr_t phys;
272 
273 	done = priv->active_vb2_buf[priv->ipu_buf_num];
274 	if (done) {
275 		done->vbuf.field = vdev->fmt.field;
276 		done->vbuf.sequence = priv->frame_sequence;
277 		vb = &done->vbuf.vb2_buf;
278 		vb->timestamp = ktime_get_ns();
279 		vb2_buffer_done(vb, priv->nfb4eof ?
280 				VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
281 	}
282 
283 	priv->frame_sequence++;
284 	priv->nfb4eof = false;
285 
286 	/* get next queued buffer */
287 	next = imx_media_capture_device_next_buf(vdev);
288 	if (next) {
289 		phys = vb2_dma_contig_plane_dma_addr(&next->vbuf.vb2_buf, 0);
290 		priv->active_vb2_buf[priv->ipu_buf_num] = next;
291 	} else {
292 		phys = priv->underrun_buf.phys;
293 		priv->active_vb2_buf[priv->ipu_buf_num] = NULL;
294 	}
295 
296 	if (ipu_idmac_buffer_is_ready(priv->idmac_ch, priv->ipu_buf_num))
297 		ipu_idmac_clear_buffer(priv->idmac_ch, priv->ipu_buf_num);
298 
299 	if (priv->interweave_swap)
300 		phys += vdev->fmt.bytesperline;
301 
302 	ipu_cpmem_set_buffer(priv->idmac_ch, priv->ipu_buf_num, phys);
303 }
304 
305 static irqreturn_t csi_idmac_eof_interrupt(int irq, void *dev_id)
306 {
307 	struct csi_priv *priv = dev_id;
308 
309 	spin_lock(&priv->irqlock);
310 
311 	if (priv->last_eof) {
312 		complete(&priv->last_eof_comp);
313 		priv->last_eof = false;
314 		goto unlock;
315 	}
316 
317 	if (priv->fim)
318 		/* call frame interval monitor */
319 		imx_media_fim_eof_monitor(priv->fim, ktime_get());
320 
321 	csi_vb2_buf_done(priv);
322 
323 	/* select new IPU buf */
324 	ipu_idmac_select_buffer(priv->idmac_ch, priv->ipu_buf_num);
325 	/* toggle IPU double-buffer index */
326 	priv->ipu_buf_num ^= 1;
327 
328 	/* bump the EOF timeout timer */
329 	mod_timer(&priv->eof_timeout_timer,
330 		  jiffies + msecs_to_jiffies(IMX_MEDIA_EOF_TIMEOUT));
331 
332 unlock:
333 	spin_unlock(&priv->irqlock);
334 	return IRQ_HANDLED;
335 }
336 
337 static irqreturn_t csi_idmac_nfb4eof_interrupt(int irq, void *dev_id)
338 {
339 	struct csi_priv *priv = dev_id;
340 
341 	spin_lock(&priv->irqlock);
342 
343 	/*
344 	 * this is not an unrecoverable error, just mark
345 	 * the next captured frame with vb2 error flag.
346 	 */
347 	priv->nfb4eof = true;
348 
349 	v4l2_err(&priv->sd, "NFB4EOF\n");
350 
351 	spin_unlock(&priv->irqlock);
352 
353 	return IRQ_HANDLED;
354 }
355 
356 /*
357  * EOF timeout timer function. This is an unrecoverable condition
358  * without a stream restart.
359  */
360 static void csi_idmac_eof_timeout(struct timer_list *t)
361 {
362 	struct csi_priv *priv = from_timer(priv, t, eof_timeout_timer);
363 	struct imx_media_video_dev *vdev = priv->vdev;
364 
365 	v4l2_err(&priv->sd, "EOF timeout\n");
366 
367 	/* signal a fatal error to capture device */
368 	imx_media_capture_device_error(vdev);
369 }
370 
371 static void csi_idmac_setup_vb2_buf(struct csi_priv *priv, dma_addr_t *phys)
372 {
373 	struct imx_media_video_dev *vdev = priv->vdev;
374 	struct imx_media_buffer *buf;
375 	int i;
376 
377 	for (i = 0; i < 2; i++) {
378 		buf = imx_media_capture_device_next_buf(vdev);
379 		if (buf) {
380 			priv->active_vb2_buf[i] = buf;
381 			phys[i] = vb2_dma_contig_plane_dma_addr(
382 				&buf->vbuf.vb2_buf, 0);
383 		} else {
384 			priv->active_vb2_buf[i] = NULL;
385 			phys[i] = priv->underrun_buf.phys;
386 		}
387 	}
388 }
389 
390 static void csi_idmac_unsetup_vb2_buf(struct csi_priv *priv,
391 				      enum vb2_buffer_state return_status)
392 {
393 	struct imx_media_buffer *buf;
394 	int i;
395 
396 	/* return any remaining active frames with return_status */
397 	for (i = 0; i < 2; i++) {
398 		buf = priv->active_vb2_buf[i];
399 		if (buf) {
400 			struct vb2_buffer *vb = &buf->vbuf.vb2_buf;
401 
402 			vb->timestamp = ktime_get_ns();
403 			vb2_buffer_done(vb, return_status);
404 		}
405 	}
406 }
407 
408 /* init the SMFC IDMAC channel */
409 static int csi_idmac_setup_channel(struct csi_priv *priv)
410 {
411 	struct imx_media_video_dev *vdev = priv->vdev;
412 	const struct imx_media_pixfmt *incc;
413 	struct v4l2_mbus_framefmt *infmt;
414 	struct v4l2_mbus_framefmt *outfmt;
415 	bool passthrough, interweave;
416 	struct ipu_image image;
417 	u32 passthrough_bits;
418 	u32 passthrough_cycles;
419 	dma_addr_t phys[2];
420 	u32 burst_size;
421 	int ret;
422 
423 	infmt = &priv->format_mbus[CSI_SINK_PAD];
424 	incc = priv->cc[CSI_SINK_PAD];
425 	outfmt = &priv->format_mbus[CSI_SRC_PAD_IDMAC];
426 
427 	ipu_cpmem_zero(priv->idmac_ch);
428 
429 	memset(&image, 0, sizeof(image));
430 	image.pix = vdev->fmt;
431 	image.rect = vdev->compose;
432 
433 	csi_idmac_setup_vb2_buf(priv, phys);
434 
435 	image.phys0 = phys[0];
436 	image.phys1 = phys[1];
437 
438 	passthrough = requires_passthrough(&priv->upstream_ep, infmt, incc);
439 	passthrough_cycles = 1;
440 
441 	/*
442 	 * If the field type at capture interface is interlaced, and
443 	 * the output IDMAC pad is sequential, enable interweave at
444 	 * the IDMAC output channel.
445 	 */
446 	interweave = V4L2_FIELD_IS_INTERLACED(image.pix.field) &&
447 		V4L2_FIELD_IS_SEQUENTIAL(outfmt->field);
448 	priv->interweave_swap = interweave &&
449 		image.pix.field == V4L2_FIELD_INTERLACED_BT;
450 
451 	switch (image.pix.pixelformat) {
452 	case V4L2_PIX_FMT_SBGGR8:
453 	case V4L2_PIX_FMT_SGBRG8:
454 	case V4L2_PIX_FMT_SGRBG8:
455 	case V4L2_PIX_FMT_SRGGB8:
456 	case V4L2_PIX_FMT_GREY:
457 		burst_size = 16;
458 		passthrough_bits = 8;
459 		break;
460 	case V4L2_PIX_FMT_SBGGR16:
461 	case V4L2_PIX_FMT_SGBRG16:
462 	case V4L2_PIX_FMT_SGRBG16:
463 	case V4L2_PIX_FMT_SRGGB16:
464 	case V4L2_PIX_FMT_Y10:
465 	case V4L2_PIX_FMT_Y12:
466 		burst_size = 8;
467 		passthrough_bits = 16;
468 		break;
469 	case V4L2_PIX_FMT_YUV420:
470 	case V4L2_PIX_FMT_YVU420:
471 	case V4L2_PIX_FMT_NV12:
472 		burst_size = (image.pix.width & 0x3f) ?
473 			     ((image.pix.width & 0x1f) ?
474 			      ((image.pix.width & 0xf) ? 8 : 16) : 32) : 64;
475 		passthrough_bits = 16;
476 		/*
477 		 * Skip writing U and V components to odd rows (but not
478 		 * when enabling IDMAC interweaving, they are incompatible).
479 		 */
480 		if (!interweave)
481 			ipu_cpmem_skip_odd_chroma_rows(priv->idmac_ch);
482 		break;
483 	case V4L2_PIX_FMT_YUYV:
484 	case V4L2_PIX_FMT_UYVY:
485 		burst_size = (image.pix.width & 0x1f) ?
486 			     ((image.pix.width & 0xf) ? 8 : 16) : 32;
487 		passthrough_bits = 16;
488 		break;
489 	case V4L2_PIX_FMT_RGB565:
490 		if (passthrough) {
491 			burst_size = 16;
492 			passthrough_bits = 8;
493 			passthrough_cycles = incc->cycles;
494 			break;
495 		}
496 		fallthrough;	/* non-passthrough RGB565 (CSI-2 bus) */
497 	default:
498 		burst_size = (image.pix.width & 0xf) ? 8 : 16;
499 		passthrough_bits = 16;
500 		break;
501 	}
502 
503 	if (passthrough) {
504 		if (priv->interweave_swap) {
505 			/* start interweave scan at 1st top line (2nd line) */
506 			image.phys0 += image.pix.bytesperline;
507 			image.phys1 += image.pix.bytesperline;
508 		}
509 
510 		ipu_cpmem_set_resolution(priv->idmac_ch,
511 					 image.rect.width * passthrough_cycles,
512 					 image.rect.height);
513 		ipu_cpmem_set_stride(priv->idmac_ch, image.pix.bytesperline);
514 		ipu_cpmem_set_buffer(priv->idmac_ch, 0, image.phys0);
515 		ipu_cpmem_set_buffer(priv->idmac_ch, 1, image.phys1);
516 		ipu_cpmem_set_format_passthrough(priv->idmac_ch,
517 						 passthrough_bits);
518 	} else {
519 		if (priv->interweave_swap) {
520 			/* start interweave scan at 1st top line (2nd line) */
521 			image.rect.top = 1;
522 		}
523 
524 		ret = ipu_cpmem_set_image(priv->idmac_ch, &image);
525 		if (ret)
526 			goto unsetup_vb2;
527 	}
528 
529 	ipu_cpmem_set_burstsize(priv->idmac_ch, burst_size);
530 
531 	/*
532 	 * Set the channel for the direct CSI-->memory via SMFC
533 	 * use-case to very high priority, by enabling the watermark
534 	 * signal in the SMFC, enabling WM in the channel, and setting
535 	 * the channel priority to high.
536 	 *
537 	 * Refer to the i.mx6 rev. D TRM Table 36-8: Calculated priority
538 	 * value.
539 	 *
540 	 * The WM's are set very low by intention here to ensure that
541 	 * the SMFC FIFOs do not overflow.
542 	 */
543 	ipu_smfc_set_watermark(priv->smfc, 0x02, 0x01);
544 	ipu_cpmem_set_high_priority(priv->idmac_ch);
545 	ipu_idmac_enable_watermark(priv->idmac_ch, true);
546 	ipu_cpmem_set_axi_id(priv->idmac_ch, 0);
547 
548 	burst_size = passthrough ?
549 		(burst_size >> 3) - 1 : (burst_size >> 2) - 1;
550 
551 	ipu_smfc_set_burstsize(priv->smfc, burst_size);
552 
553 	if (interweave)
554 		ipu_cpmem_interlaced_scan(priv->idmac_ch,
555 					  priv->interweave_swap ?
556 					  -image.pix.bytesperline :
557 					  image.pix.bytesperline,
558 					  image.pix.pixelformat);
559 
560 	ipu_idmac_set_double_buffer(priv->idmac_ch, true);
561 
562 	return 0;
563 
564 unsetup_vb2:
565 	csi_idmac_unsetup_vb2_buf(priv, VB2_BUF_STATE_QUEUED);
566 	return ret;
567 }
568 
569 static void csi_idmac_unsetup(struct csi_priv *priv,
570 			      enum vb2_buffer_state state)
571 {
572 	ipu_idmac_disable_channel(priv->idmac_ch);
573 	ipu_smfc_disable(priv->smfc);
574 
575 	csi_idmac_unsetup_vb2_buf(priv, state);
576 }
577 
578 static int csi_idmac_setup(struct csi_priv *priv)
579 {
580 	int ret;
581 
582 	ret = csi_idmac_setup_channel(priv);
583 	if (ret)
584 		return ret;
585 
586 	ipu_cpmem_dump(priv->idmac_ch);
587 	ipu_dump(priv->ipu);
588 
589 	ipu_smfc_enable(priv->smfc);
590 
591 	/* set buffers ready */
592 	ipu_idmac_select_buffer(priv->idmac_ch, 0);
593 	ipu_idmac_select_buffer(priv->idmac_ch, 1);
594 
595 	/* enable the channels */
596 	ipu_idmac_enable_channel(priv->idmac_ch);
597 
598 	return 0;
599 }
600 
601 static int csi_idmac_start(struct csi_priv *priv)
602 {
603 	struct imx_media_video_dev *vdev = priv->vdev;
604 	int ret;
605 
606 	ret = csi_idmac_get_ipu_resources(priv);
607 	if (ret)
608 		return ret;
609 
610 	ipu_smfc_map_channel(priv->smfc, priv->csi_id, priv->vc_num);
611 
612 	ret = imx_media_alloc_dma_buf(priv->dev, &priv->underrun_buf,
613 				      vdev->fmt.sizeimage);
614 	if (ret)
615 		goto out_put_ipu;
616 
617 	priv->ipu_buf_num = 0;
618 
619 	/* init EOF completion waitq */
620 	init_completion(&priv->last_eof_comp);
621 	priv->frame_sequence = 0;
622 	priv->last_eof = false;
623 	priv->nfb4eof = false;
624 
625 	ret = csi_idmac_setup(priv);
626 	if (ret) {
627 		v4l2_err(&priv->sd, "csi_idmac_setup failed: %d\n", ret);
628 		goto out_free_dma_buf;
629 	}
630 
631 	priv->nfb4eof_irq = ipu_idmac_channel_irq(priv->ipu,
632 						  priv->idmac_ch,
633 						  IPU_IRQ_NFB4EOF);
634 	ret = devm_request_irq(priv->dev, priv->nfb4eof_irq,
635 			       csi_idmac_nfb4eof_interrupt, 0,
636 			       "imx-smfc-nfb4eof", priv);
637 	if (ret) {
638 		v4l2_err(&priv->sd,
639 			 "Error registering NFB4EOF irq: %d\n", ret);
640 		goto out_unsetup;
641 	}
642 
643 	priv->eof_irq = ipu_idmac_channel_irq(priv->ipu, priv->idmac_ch,
644 					      IPU_IRQ_EOF);
645 
646 	ret = devm_request_irq(priv->dev, priv->eof_irq,
647 			       csi_idmac_eof_interrupt, 0,
648 			       "imx-smfc-eof", priv);
649 	if (ret) {
650 		v4l2_err(&priv->sd,
651 			 "Error registering eof irq: %d\n", ret);
652 		goto out_free_nfb4eof_irq;
653 	}
654 
655 	/* start the EOF timeout timer */
656 	mod_timer(&priv->eof_timeout_timer,
657 		  jiffies + msecs_to_jiffies(IMX_MEDIA_EOF_TIMEOUT));
658 
659 	return 0;
660 
661 out_free_nfb4eof_irq:
662 	devm_free_irq(priv->dev, priv->nfb4eof_irq, priv);
663 out_unsetup:
664 	csi_idmac_unsetup(priv, VB2_BUF_STATE_QUEUED);
665 out_free_dma_buf:
666 	imx_media_free_dma_buf(priv->dev, &priv->underrun_buf);
667 out_put_ipu:
668 	csi_idmac_put_ipu_resources(priv);
669 	return ret;
670 }
671 
672 static void csi_idmac_wait_last_eof(struct csi_priv *priv)
673 {
674 	unsigned long flags;
675 	int ret;
676 
677 	/* mark next EOF interrupt as the last before stream off */
678 	spin_lock_irqsave(&priv->irqlock, flags);
679 	priv->last_eof = true;
680 	spin_unlock_irqrestore(&priv->irqlock, flags);
681 
682 	/*
683 	 * and then wait for interrupt handler to mark completion.
684 	 */
685 	ret = wait_for_completion_timeout(
686 		&priv->last_eof_comp, msecs_to_jiffies(IMX_MEDIA_EOF_TIMEOUT));
687 	if (ret == 0)
688 		v4l2_warn(&priv->sd, "wait last EOF timeout\n");
689 }
690 
691 static void csi_idmac_stop(struct csi_priv *priv)
692 {
693 	devm_free_irq(priv->dev, priv->eof_irq, priv);
694 	devm_free_irq(priv->dev, priv->nfb4eof_irq, priv);
695 
696 	csi_idmac_unsetup(priv, VB2_BUF_STATE_ERROR);
697 
698 	imx_media_free_dma_buf(priv->dev, &priv->underrun_buf);
699 
700 	/* cancel the EOF timeout timer */
701 	del_timer_sync(&priv->eof_timeout_timer);
702 
703 	csi_idmac_put_ipu_resources(priv);
704 }
705 
706 /* Update the CSI whole sensor and active windows */
707 static int csi_setup(struct csi_priv *priv)
708 {
709 	struct v4l2_mbus_framefmt *infmt, *outfmt;
710 	const struct imx_media_pixfmt *incc;
711 	struct v4l2_mbus_config mbus_cfg;
712 	struct v4l2_mbus_framefmt if_fmt;
713 	struct v4l2_rect crop;
714 
715 	infmt = &priv->format_mbus[CSI_SINK_PAD];
716 	incc = priv->cc[CSI_SINK_PAD];
717 	outfmt = &priv->format_mbus[priv->active_output_pad];
718 
719 	/* compose mbus_config from the upstream endpoint */
720 	mbus_cfg.type = priv->upstream_ep.bus_type;
721 	mbus_cfg.flags = is_parallel_bus(&priv->upstream_ep) ?
722 		priv->upstream_ep.bus.parallel.flags :
723 		priv->upstream_ep.bus.mipi_csi2.flags;
724 
725 	if_fmt = *infmt;
726 	crop = priv->crop;
727 
728 	/*
729 	 * if cycles is set, we need to handle this over multiple cycles as
730 	 * generic/bayer data
731 	 */
732 	if (is_parallel_bus(&priv->upstream_ep) && incc->cycles) {
733 		if_fmt.width *= incc->cycles;
734 		crop.width *= incc->cycles;
735 	}
736 
737 	ipu_csi_set_window(priv->csi, &crop);
738 
739 	ipu_csi_set_downsize(priv->csi,
740 			     priv->crop.width == 2 * priv->compose.width,
741 			     priv->crop.height == 2 * priv->compose.height);
742 
743 	ipu_csi_init_interface(priv->csi, &mbus_cfg, &if_fmt, outfmt);
744 
745 	ipu_csi_set_dest(priv->csi, priv->dest);
746 
747 	if (priv->dest == IPU_CSI_DEST_IDMAC)
748 		ipu_csi_set_skip_smfc(priv->csi, priv->skip->skip_smfc,
749 				      priv->skip->max_ratio - 1, 0);
750 
751 	ipu_csi_dump(priv->csi);
752 
753 	return 0;
754 }
755 
756 static int csi_start(struct csi_priv *priv)
757 {
758 	struct v4l2_fract *input_fi, *output_fi;
759 	int ret;
760 
761 	input_fi = &priv->frame_interval[CSI_SINK_PAD];
762 	output_fi = &priv->frame_interval[priv->active_output_pad];
763 
764 	/* start upstream */
765 	ret = v4l2_subdev_call(priv->src_sd, video, s_stream, 1);
766 	ret = (ret && ret != -ENOIOCTLCMD) ? ret : 0;
767 	if (ret)
768 		return ret;
769 
770 	/* Skip first few frames from a BT.656 source */
771 	if (priv->upstream_ep.bus_type == V4L2_MBUS_BT656) {
772 		u32 delay_usec, bad_frames = 20;
773 
774 		delay_usec = DIV_ROUND_UP_ULL((u64)USEC_PER_SEC *
775 			input_fi->numerator * bad_frames,
776 			input_fi->denominator);
777 
778 		usleep_range(delay_usec, delay_usec + 1000);
779 	}
780 
781 	if (priv->dest == IPU_CSI_DEST_IDMAC) {
782 		ret = csi_idmac_start(priv);
783 		if (ret)
784 			goto stop_upstream;
785 	}
786 
787 	ret = csi_setup(priv);
788 	if (ret)
789 		goto idmac_stop;
790 
791 	/* start the frame interval monitor */
792 	if (priv->fim && priv->dest == IPU_CSI_DEST_IDMAC) {
793 		ret = imx_media_fim_set_stream(priv->fim, output_fi, true);
794 		if (ret)
795 			goto idmac_stop;
796 	}
797 
798 	ret = ipu_csi_enable(priv->csi);
799 	if (ret) {
800 		v4l2_err(&priv->sd, "CSI enable error: %d\n", ret);
801 		goto fim_off;
802 	}
803 
804 	return 0;
805 
806 fim_off:
807 	if (priv->fim && priv->dest == IPU_CSI_DEST_IDMAC)
808 		imx_media_fim_set_stream(priv->fim, NULL, false);
809 idmac_stop:
810 	if (priv->dest == IPU_CSI_DEST_IDMAC)
811 		csi_idmac_stop(priv);
812 stop_upstream:
813 	v4l2_subdev_call(priv->src_sd, video, s_stream, 0);
814 	return ret;
815 }
816 
817 static void csi_stop(struct csi_priv *priv)
818 {
819 	if (priv->dest == IPU_CSI_DEST_IDMAC)
820 		csi_idmac_wait_last_eof(priv);
821 
822 	/*
823 	 * Disable the CSI asap, after syncing with the last EOF.
824 	 * Doing so after the IDMA channel is disabled has shown to
825 	 * create hard system-wide hangs.
826 	 */
827 	ipu_csi_disable(priv->csi);
828 
829 	/* stop upstream */
830 	v4l2_subdev_call(priv->src_sd, video, s_stream, 0);
831 
832 	if (priv->dest == IPU_CSI_DEST_IDMAC) {
833 		csi_idmac_stop(priv);
834 
835 		/* stop the frame interval monitor */
836 		if (priv->fim)
837 			imx_media_fim_set_stream(priv->fim, NULL, false);
838 	}
839 }
840 
841 static const struct csi_skip_desc csi_skip[12] = {
842 	{ 1, 1, 0x00 }, /* Keep all frames */
843 	{ 5, 6, 0x10 }, /* Skip every sixth frame */
844 	{ 4, 5, 0x08 }, /* Skip every fifth frame */
845 	{ 3, 4, 0x04 }, /* Skip every fourth frame */
846 	{ 2, 3, 0x02 }, /* Skip every third frame */
847 	{ 3, 5, 0x0a }, /* Skip frames 1 and 3 of every 5 */
848 	{ 1, 2, 0x01 }, /* Skip every second frame */
849 	{ 2, 5, 0x0b }, /* Keep frames 1 and 4 of every 5 */
850 	{ 1, 3, 0x03 }, /* Keep one in three frames */
851 	{ 1, 4, 0x07 }, /* Keep one in four frames */
852 	{ 1, 5, 0x0f }, /* Keep one in five frames */
853 	{ 1, 6, 0x1f }, /* Keep one in six frames */
854 };
855 
856 static void csi_apply_skip_interval(const struct csi_skip_desc *skip,
857 				    struct v4l2_fract *interval)
858 {
859 	unsigned int div;
860 
861 	interval->numerator *= skip->max_ratio;
862 	interval->denominator *= skip->keep;
863 
864 	/* Reduce fraction to lowest terms */
865 	div = gcd(interval->numerator, interval->denominator);
866 	if (div > 1) {
867 		interval->numerator /= div;
868 		interval->denominator /= div;
869 	}
870 }
871 
872 /*
873  * Find the skip pattern to produce the output frame interval closest to the
874  * requested one, for the given input frame interval. Updates the output frame
875  * interval to the exact value.
876  */
877 static const struct csi_skip_desc *csi_find_best_skip(struct v4l2_fract *in,
878 						      struct v4l2_fract *out)
879 {
880 	const struct csi_skip_desc *skip = &csi_skip[0], *best_skip = skip;
881 	u32 min_err = UINT_MAX;
882 	u64 want_us;
883 	int i;
884 
885 	/* Default to 1:1 ratio */
886 	if (out->numerator == 0 || out->denominator == 0 ||
887 	    in->numerator == 0 || in->denominator == 0) {
888 		*out = *in;
889 		return best_skip;
890 	}
891 
892 	want_us = div_u64((u64)USEC_PER_SEC * out->numerator, out->denominator);
893 
894 	/* Find the reduction closest to the requested time per frame */
895 	for (i = 0; i < ARRAY_SIZE(csi_skip); i++, skip++) {
896 		u64 tmp, err;
897 
898 		tmp = div_u64((u64)USEC_PER_SEC * in->numerator *
899 			      skip->max_ratio, in->denominator * skip->keep);
900 
901 		err = abs((s64)tmp - want_us);
902 		if (err < min_err) {
903 			min_err = err;
904 			best_skip = skip;
905 		}
906 	}
907 
908 	*out = *in;
909 	csi_apply_skip_interval(best_skip, out);
910 
911 	return best_skip;
912 }
913 
914 /*
915  * V4L2 subdev operations.
916  */
917 
918 static int csi_g_frame_interval(struct v4l2_subdev *sd,
919 				struct v4l2_subdev_frame_interval *fi)
920 {
921 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
922 
923 	if (fi->pad >= CSI_NUM_PADS)
924 		return -EINVAL;
925 
926 	mutex_lock(&priv->lock);
927 
928 	fi->interval = priv->frame_interval[fi->pad];
929 
930 	mutex_unlock(&priv->lock);
931 
932 	return 0;
933 }
934 
935 static int csi_s_frame_interval(struct v4l2_subdev *sd,
936 				struct v4l2_subdev_frame_interval *fi)
937 {
938 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
939 	struct v4l2_fract *input_fi;
940 	int ret = 0;
941 
942 	mutex_lock(&priv->lock);
943 
944 	input_fi = &priv->frame_interval[CSI_SINK_PAD];
945 
946 	switch (fi->pad) {
947 	case CSI_SINK_PAD:
948 		/* No limits on valid input frame intervals */
949 		if (fi->interval.numerator == 0 ||
950 		    fi->interval.denominator == 0)
951 			fi->interval = *input_fi;
952 		/* Reset output intervals and frame skipping ratio to 1:1 */
953 		priv->frame_interval[CSI_SRC_PAD_IDMAC] = fi->interval;
954 		priv->frame_interval[CSI_SRC_PAD_DIRECT] = fi->interval;
955 		priv->skip = &csi_skip[0];
956 		break;
957 	case CSI_SRC_PAD_IDMAC:
958 		/*
959 		 * frame interval at IDMAC output pad depends on input
960 		 * interval, modified by frame skipping.
961 		 */
962 		priv->skip = csi_find_best_skip(input_fi, &fi->interval);
963 		break;
964 	case CSI_SRC_PAD_DIRECT:
965 		/*
966 		 * frame interval at DIRECT output pad is same as input
967 		 * interval.
968 		 */
969 		fi->interval = *input_fi;
970 		break;
971 	default:
972 		ret = -EINVAL;
973 		goto out;
974 	}
975 
976 	priv->frame_interval[fi->pad] = fi->interval;
977 out:
978 	mutex_unlock(&priv->lock);
979 	return ret;
980 }
981 
982 static int csi_s_stream(struct v4l2_subdev *sd, int enable)
983 {
984 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
985 	int ret = 0;
986 
987 	mutex_lock(&priv->lock);
988 
989 	if (!priv->src_sd || !priv->sink) {
990 		ret = -EPIPE;
991 		goto out;
992 	}
993 
994 	/*
995 	 * enable/disable streaming only if stream_count is
996 	 * going from 0 to 1 / 1 to 0.
997 	 */
998 	if (priv->stream_count != !enable)
999 		goto update_count;
1000 
1001 	if (enable) {
1002 		dev_dbg(priv->dev, "stream ON\n");
1003 		ret = csi_start(priv);
1004 		if (ret)
1005 			goto out;
1006 	} else {
1007 		dev_dbg(priv->dev, "stream OFF\n");
1008 		csi_stop(priv);
1009 	}
1010 
1011 update_count:
1012 	priv->stream_count += enable ? 1 : -1;
1013 	if (priv->stream_count < 0)
1014 		priv->stream_count = 0;
1015 out:
1016 	mutex_unlock(&priv->lock);
1017 	return ret;
1018 }
1019 
1020 static int csi_link_setup(struct media_entity *entity,
1021 			  const struct media_pad *local,
1022 			  const struct media_pad *remote, u32 flags)
1023 {
1024 	struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
1025 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1026 	struct v4l2_subdev *remote_sd;
1027 	int ret = 0;
1028 
1029 	dev_dbg(priv->dev, "link setup %s -> %s\n", remote->entity->name,
1030 		local->entity->name);
1031 
1032 	mutex_lock(&priv->lock);
1033 
1034 	if (local->flags & MEDIA_PAD_FL_SINK) {
1035 		if (!is_media_entity_v4l2_subdev(remote->entity)) {
1036 			ret = -EINVAL;
1037 			goto out;
1038 		}
1039 
1040 		remote_sd = media_entity_to_v4l2_subdev(remote->entity);
1041 
1042 		if (flags & MEDIA_LNK_FL_ENABLED) {
1043 			if (priv->src_sd) {
1044 				ret = -EBUSY;
1045 				goto out;
1046 			}
1047 			priv->src_sd = remote_sd;
1048 		} else {
1049 			priv->src_sd = NULL;
1050 		}
1051 
1052 		goto out;
1053 	}
1054 
1055 	/* this is a source pad */
1056 
1057 	if (flags & MEDIA_LNK_FL_ENABLED) {
1058 		if (priv->sink) {
1059 			ret = -EBUSY;
1060 			goto out;
1061 		}
1062 	} else {
1063 		v4l2_ctrl_handler_free(&priv->ctrl_hdlr);
1064 		v4l2_ctrl_handler_init(&priv->ctrl_hdlr, 0);
1065 		priv->sink = NULL;
1066 		/* do not apply IC burst alignment in csi_try_crop */
1067 		priv->active_output_pad = CSI_SRC_PAD_IDMAC;
1068 		goto out;
1069 	}
1070 
1071 	/* record which output pad is now active */
1072 	priv->active_output_pad = local->index;
1073 
1074 	/* set CSI destination */
1075 	if (local->index == CSI_SRC_PAD_IDMAC) {
1076 		if (!is_media_entity_v4l2_video_device(remote->entity)) {
1077 			ret = -EINVAL;
1078 			goto out;
1079 		}
1080 
1081 		if (priv->fim) {
1082 			ret = imx_media_fim_add_controls(priv->fim);
1083 			if (ret)
1084 				goto out;
1085 		}
1086 
1087 		priv->dest = IPU_CSI_DEST_IDMAC;
1088 	} else {
1089 		if (!is_media_entity_v4l2_subdev(remote->entity)) {
1090 			ret = -EINVAL;
1091 			goto out;
1092 		}
1093 
1094 		remote_sd = media_entity_to_v4l2_subdev(remote->entity);
1095 		switch (remote_sd->grp_id) {
1096 		case IMX_MEDIA_GRP_ID_IPU_VDIC:
1097 			priv->dest = IPU_CSI_DEST_VDIC;
1098 			break;
1099 		case IMX_MEDIA_GRP_ID_IPU_IC_PRP:
1100 			priv->dest = IPU_CSI_DEST_IC;
1101 			break;
1102 		default:
1103 			ret = -EINVAL;
1104 			goto out;
1105 		}
1106 	}
1107 
1108 	priv->sink = remote->entity;
1109 out:
1110 	mutex_unlock(&priv->lock);
1111 	return ret;
1112 }
1113 
1114 static int csi_link_validate(struct v4l2_subdev *sd,
1115 			     struct media_link *link,
1116 			     struct v4l2_subdev_format *source_fmt,
1117 			     struct v4l2_subdev_format *sink_fmt)
1118 {
1119 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1120 	struct v4l2_fwnode_endpoint upstream_ep = { .bus_type = 0 };
1121 	bool is_csi2;
1122 	int ret;
1123 
1124 	ret = v4l2_subdev_link_validate_default(sd, link,
1125 						source_fmt, sink_fmt);
1126 	if (ret)
1127 		return ret;
1128 
1129 	ret = csi_get_upstream_endpoint(priv, &upstream_ep);
1130 	if (ret) {
1131 		v4l2_err(&priv->sd, "failed to find upstream endpoint\n");
1132 		return ret;
1133 	}
1134 
1135 	mutex_lock(&priv->lock);
1136 
1137 	priv->upstream_ep = upstream_ep;
1138 	is_csi2 = !is_parallel_bus(&upstream_ep);
1139 	if (is_csi2) {
1140 		/*
1141 		 * NOTE! It seems the virtual channels from the mipi csi-2
1142 		 * receiver are used only for routing by the video mux's,
1143 		 * or for hard-wired routing to the CSI's. Once the stream
1144 		 * enters the CSI's however, they are treated internally
1145 		 * in the IPU as virtual channel 0.
1146 		 */
1147 		ipu_csi_set_mipi_datatype(priv->csi, 0,
1148 					  &priv->format_mbus[CSI_SINK_PAD]);
1149 	}
1150 
1151 	/* select either parallel or MIPI-CSI2 as input to CSI */
1152 	ipu_set_csi_src_mux(priv->ipu, priv->csi_id, is_csi2);
1153 
1154 	mutex_unlock(&priv->lock);
1155 	return ret;
1156 }
1157 
1158 static struct v4l2_mbus_framefmt *
1159 __csi_get_fmt(struct csi_priv *priv, struct v4l2_subdev_state *sd_state,
1160 	      unsigned int pad, enum v4l2_subdev_format_whence which)
1161 {
1162 	if (which == V4L2_SUBDEV_FORMAT_TRY)
1163 		return v4l2_subdev_get_try_format(&priv->sd, sd_state, pad);
1164 	else
1165 		return &priv->format_mbus[pad];
1166 }
1167 
1168 static struct v4l2_rect *
1169 __csi_get_crop(struct csi_priv *priv, struct v4l2_subdev_state *sd_state,
1170 	       enum v4l2_subdev_format_whence which)
1171 {
1172 	if (which == V4L2_SUBDEV_FORMAT_TRY)
1173 		return v4l2_subdev_get_try_crop(&priv->sd, sd_state,
1174 						CSI_SINK_PAD);
1175 	else
1176 		return &priv->crop;
1177 }
1178 
1179 static struct v4l2_rect *
1180 __csi_get_compose(struct csi_priv *priv, struct v4l2_subdev_state *sd_state,
1181 		  enum v4l2_subdev_format_whence which)
1182 {
1183 	if (which == V4L2_SUBDEV_FORMAT_TRY)
1184 		return v4l2_subdev_get_try_compose(&priv->sd, sd_state,
1185 						   CSI_SINK_PAD);
1186 	else
1187 		return &priv->compose;
1188 }
1189 
1190 static void csi_try_crop(struct csi_priv *priv,
1191 			 struct v4l2_rect *crop,
1192 			 struct v4l2_subdev_state *sd_state,
1193 			 struct v4l2_mbus_framefmt *infmt,
1194 			 struct v4l2_fwnode_endpoint *upstream_ep)
1195 {
1196 	u32 in_height;
1197 
1198 	crop->width = min_t(__u32, infmt->width, crop->width);
1199 	if (crop->left + crop->width > infmt->width)
1200 		crop->left = infmt->width - crop->width;
1201 	/* adjust crop left/width to h/w alignment restrictions */
1202 	crop->left &= ~0x3;
1203 	if (priv->active_output_pad == CSI_SRC_PAD_DIRECT)
1204 		crop->width &= ~0x7; /* multiple of 8 pixels (IC burst) */
1205 	else
1206 		crop->width &= ~0x1; /* multiple of 2 pixels */
1207 
1208 	in_height = infmt->height;
1209 	if (infmt->field == V4L2_FIELD_ALTERNATE)
1210 		in_height *= 2;
1211 
1212 	/*
1213 	 * FIXME: not sure why yet, but on interlaced bt.656,
1214 	 * changing the vertical cropping causes loss of vertical
1215 	 * sync, so fix it to NTSC/PAL active lines. NTSC contains
1216 	 * 2 extra lines of active video that need to be cropped.
1217 	 */
1218 	if (upstream_ep->bus_type == V4L2_MBUS_BT656 &&
1219 	    (V4L2_FIELD_HAS_BOTH(infmt->field) ||
1220 	     infmt->field == V4L2_FIELD_ALTERNATE)) {
1221 		crop->height = in_height;
1222 		crop->top = (in_height == 480) ? 2 : 0;
1223 	} else {
1224 		crop->height = min_t(__u32, in_height, crop->height);
1225 		if (crop->top + crop->height > in_height)
1226 			crop->top = in_height - crop->height;
1227 	}
1228 }
1229 
1230 static int csi_enum_mbus_code(struct v4l2_subdev *sd,
1231 			      struct v4l2_subdev_state *sd_state,
1232 			      struct v4l2_subdev_mbus_code_enum *code)
1233 {
1234 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1235 	struct v4l2_fwnode_endpoint upstream_ep = { .bus_type = 0 };
1236 	const struct imx_media_pixfmt *incc;
1237 	struct v4l2_mbus_framefmt *infmt;
1238 	int ret = 0;
1239 
1240 	mutex_lock(&priv->lock);
1241 
1242 	infmt = __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, code->which);
1243 	incc = imx_media_find_mbus_format(infmt->code, PIXFMT_SEL_ANY);
1244 
1245 	switch (code->pad) {
1246 	case CSI_SINK_PAD:
1247 		ret = imx_media_enum_mbus_formats(&code->code, code->index,
1248 						  PIXFMT_SEL_ANY);
1249 		break;
1250 	case CSI_SRC_PAD_DIRECT:
1251 	case CSI_SRC_PAD_IDMAC:
1252 		ret = csi_get_upstream_endpoint(priv, &upstream_ep);
1253 		if (ret) {
1254 			v4l2_err(&priv->sd, "failed to find upstream endpoint\n");
1255 			goto out;
1256 		}
1257 
1258 		if (requires_passthrough(&upstream_ep, infmt, incc)) {
1259 			if (code->index != 0) {
1260 				ret = -EINVAL;
1261 				goto out;
1262 			}
1263 			code->code = infmt->code;
1264 		} else {
1265 			enum imx_pixfmt_sel fmt_sel =
1266 				(incc->cs == IPUV3_COLORSPACE_YUV) ?
1267 				PIXFMT_SEL_YUV : PIXFMT_SEL_RGB;
1268 
1269 			ret = imx_media_enum_ipu_formats(&code->code,
1270 							 code->index,
1271 							 fmt_sel);
1272 		}
1273 		break;
1274 	default:
1275 		ret = -EINVAL;
1276 	}
1277 
1278 out:
1279 	mutex_unlock(&priv->lock);
1280 	return ret;
1281 }
1282 
1283 static int csi_enum_frame_size(struct v4l2_subdev *sd,
1284 			       struct v4l2_subdev_state *sd_state,
1285 			       struct v4l2_subdev_frame_size_enum *fse)
1286 {
1287 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1288 	struct v4l2_rect *crop;
1289 	int ret = 0;
1290 
1291 	if (fse->pad >= CSI_NUM_PADS ||
1292 	    fse->index > (fse->pad == CSI_SINK_PAD ? 0 : 3))
1293 		return -EINVAL;
1294 
1295 	mutex_lock(&priv->lock);
1296 
1297 	if (fse->pad == CSI_SINK_PAD) {
1298 		fse->min_width = MIN_W;
1299 		fse->max_width = MAX_W;
1300 		fse->min_height = MIN_H;
1301 		fse->max_height = MAX_H;
1302 	} else {
1303 		crop = __csi_get_crop(priv, sd_state, fse->which);
1304 
1305 		fse->min_width = fse->index & 1 ?
1306 			crop->width / 2 : crop->width;
1307 		fse->max_width = fse->min_width;
1308 		fse->min_height = fse->index & 2 ?
1309 			crop->height / 2 : crop->height;
1310 		fse->max_height = fse->min_height;
1311 	}
1312 
1313 	mutex_unlock(&priv->lock);
1314 	return ret;
1315 }
1316 
1317 static int csi_enum_frame_interval(struct v4l2_subdev *sd,
1318 				   struct v4l2_subdev_state *sd_state,
1319 				   struct v4l2_subdev_frame_interval_enum *fie)
1320 {
1321 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1322 	struct v4l2_fract *input_fi;
1323 	struct v4l2_rect *crop;
1324 	int ret = 0;
1325 
1326 	if (fie->pad >= CSI_NUM_PADS ||
1327 	    fie->index >= (fie->pad != CSI_SRC_PAD_IDMAC ?
1328 			   1 : ARRAY_SIZE(csi_skip)))
1329 		return -EINVAL;
1330 
1331 	mutex_lock(&priv->lock);
1332 
1333 	input_fi = &priv->frame_interval[CSI_SINK_PAD];
1334 	crop = __csi_get_crop(priv, sd_state, fie->which);
1335 
1336 	if ((fie->width != crop->width && fie->width != crop->width / 2) ||
1337 	    (fie->height != crop->height && fie->height != crop->height / 2)) {
1338 		ret = -EINVAL;
1339 		goto out;
1340 	}
1341 
1342 	fie->interval = *input_fi;
1343 
1344 	if (fie->pad == CSI_SRC_PAD_IDMAC)
1345 		csi_apply_skip_interval(&csi_skip[fie->index],
1346 					&fie->interval);
1347 
1348 out:
1349 	mutex_unlock(&priv->lock);
1350 	return ret;
1351 }
1352 
1353 static int csi_get_fmt(struct v4l2_subdev *sd,
1354 		       struct v4l2_subdev_state *sd_state,
1355 		       struct v4l2_subdev_format *sdformat)
1356 {
1357 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1358 	struct v4l2_mbus_framefmt *fmt;
1359 	int ret = 0;
1360 
1361 	if (sdformat->pad >= CSI_NUM_PADS)
1362 		return -EINVAL;
1363 
1364 	mutex_lock(&priv->lock);
1365 
1366 	fmt = __csi_get_fmt(priv, sd_state, sdformat->pad, sdformat->which);
1367 	if (!fmt) {
1368 		ret = -EINVAL;
1369 		goto out;
1370 	}
1371 
1372 	sdformat->format = *fmt;
1373 out:
1374 	mutex_unlock(&priv->lock);
1375 	return ret;
1376 }
1377 
1378 static void csi_try_field(struct csi_priv *priv,
1379 			  struct v4l2_subdev_state *sd_state,
1380 			  struct v4l2_subdev_format *sdformat)
1381 {
1382 	struct v4l2_mbus_framefmt *infmt =
1383 		__csi_get_fmt(priv, sd_state, CSI_SINK_PAD, sdformat->which);
1384 
1385 	/*
1386 	 * no restrictions on sink pad field type except must
1387 	 * be initialized.
1388 	 */
1389 	if (sdformat->pad == CSI_SINK_PAD) {
1390 		if (sdformat->format.field == V4L2_FIELD_ANY)
1391 			sdformat->format.field = V4L2_FIELD_NONE;
1392 		return;
1393 	}
1394 
1395 	switch (infmt->field) {
1396 	case V4L2_FIELD_SEQ_TB:
1397 	case V4L2_FIELD_SEQ_BT:
1398 		/*
1399 		 * If the user requests sequential at the source pad,
1400 		 * allow it (along with possibly inverting field order).
1401 		 * Otherwise passthrough the field type.
1402 		 */
1403 		if (!V4L2_FIELD_IS_SEQUENTIAL(sdformat->format.field))
1404 			sdformat->format.field = infmt->field;
1405 		break;
1406 	case V4L2_FIELD_ALTERNATE:
1407 		/*
1408 		 * This driver does not support alternate field mode, and
1409 		 * the CSI captures a whole frame, so the CSI never presents
1410 		 * alternate mode at its source pads. If user has not
1411 		 * already requested sequential, translate ALTERNATE at
1412 		 * sink pad to SEQ_TB or SEQ_BT at the source pad depending
1413 		 * on input height (assume NTSC BT order if 480 total active
1414 		 * frame lines, otherwise PAL TB order).
1415 		 */
1416 		if (!V4L2_FIELD_IS_SEQUENTIAL(sdformat->format.field))
1417 			sdformat->format.field = (infmt->height == 480 / 2) ?
1418 				V4L2_FIELD_SEQ_BT : V4L2_FIELD_SEQ_TB;
1419 		break;
1420 	default:
1421 		/* Passthrough for all other input field types */
1422 		sdformat->format.field = infmt->field;
1423 		break;
1424 	}
1425 }
1426 
1427 static void csi_try_fmt(struct csi_priv *priv,
1428 			struct v4l2_fwnode_endpoint *upstream_ep,
1429 			struct v4l2_subdev_state *sd_state,
1430 			struct v4l2_subdev_format *sdformat,
1431 			struct v4l2_rect *crop,
1432 			struct v4l2_rect *compose,
1433 			const struct imx_media_pixfmt **cc)
1434 {
1435 	const struct imx_media_pixfmt *incc;
1436 	struct v4l2_mbus_framefmt *infmt;
1437 	u32 code;
1438 
1439 	infmt = __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, sdformat->which);
1440 
1441 	switch (sdformat->pad) {
1442 	case CSI_SRC_PAD_DIRECT:
1443 	case CSI_SRC_PAD_IDMAC:
1444 		incc = imx_media_find_mbus_format(infmt->code, PIXFMT_SEL_ANY);
1445 
1446 		sdformat->format.width = compose->width;
1447 		sdformat->format.height = compose->height;
1448 
1449 		if (requires_passthrough(upstream_ep, infmt, incc)) {
1450 			sdformat->format.code = infmt->code;
1451 			*cc = incc;
1452 		} else {
1453 			enum imx_pixfmt_sel fmt_sel =
1454 				(incc->cs == IPUV3_COLORSPACE_YUV) ?
1455 				PIXFMT_SEL_YUV : PIXFMT_SEL_RGB;
1456 
1457 			*cc = imx_media_find_ipu_format(sdformat->format.code,
1458 							fmt_sel);
1459 			if (!*cc) {
1460 				imx_media_enum_ipu_formats(&code, 0, fmt_sel);
1461 				*cc = imx_media_find_ipu_format(code, fmt_sel);
1462 				sdformat->format.code = (*cc)->codes[0];
1463 			}
1464 		}
1465 
1466 		csi_try_field(priv, sd_state, sdformat);
1467 
1468 		/* propagate colorimetry from sink */
1469 		sdformat->format.colorspace = infmt->colorspace;
1470 		sdformat->format.xfer_func = infmt->xfer_func;
1471 		sdformat->format.quantization = infmt->quantization;
1472 		sdformat->format.ycbcr_enc = infmt->ycbcr_enc;
1473 
1474 		break;
1475 	case CSI_SINK_PAD:
1476 		v4l_bound_align_image(&sdformat->format.width, MIN_W, MAX_W,
1477 				      W_ALIGN, &sdformat->format.height,
1478 				      MIN_H, MAX_H, H_ALIGN, S_ALIGN);
1479 
1480 		*cc = imx_media_find_mbus_format(sdformat->format.code,
1481 						 PIXFMT_SEL_ANY);
1482 		if (!*cc) {
1483 			imx_media_enum_mbus_formats(&code, 0,
1484 						    PIXFMT_SEL_YUV_RGB);
1485 			*cc = imx_media_find_mbus_format(code,
1486 							 PIXFMT_SEL_YUV_RGB);
1487 			sdformat->format.code = (*cc)->codes[0];
1488 		}
1489 
1490 		csi_try_field(priv, sd_state, sdformat);
1491 
1492 		/* Reset crop and compose rectangles */
1493 		crop->left = 0;
1494 		crop->top = 0;
1495 		crop->width = sdformat->format.width;
1496 		crop->height = sdformat->format.height;
1497 		if (sdformat->format.field == V4L2_FIELD_ALTERNATE)
1498 			crop->height *= 2;
1499 		csi_try_crop(priv, crop, sd_state, &sdformat->format,
1500 			     upstream_ep);
1501 		compose->left = 0;
1502 		compose->top = 0;
1503 		compose->width = crop->width;
1504 		compose->height = crop->height;
1505 
1506 		break;
1507 	}
1508 
1509 	imx_media_try_colorimetry(&sdformat->format,
1510 			priv->active_output_pad == CSI_SRC_PAD_DIRECT);
1511 }
1512 
1513 static int csi_set_fmt(struct v4l2_subdev *sd,
1514 		       struct v4l2_subdev_state *sd_state,
1515 		       struct v4l2_subdev_format *sdformat)
1516 {
1517 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1518 	struct v4l2_fwnode_endpoint upstream_ep = { .bus_type = 0 };
1519 	const struct imx_media_pixfmt *cc;
1520 	struct v4l2_mbus_framefmt *fmt;
1521 	struct v4l2_rect *crop, *compose;
1522 	int ret;
1523 
1524 	if (sdformat->pad >= CSI_NUM_PADS)
1525 		return -EINVAL;
1526 
1527 	ret = csi_get_upstream_endpoint(priv, &upstream_ep);
1528 	if (ret) {
1529 		v4l2_err(&priv->sd, "failed to find upstream endpoint\n");
1530 		return ret;
1531 	}
1532 
1533 	mutex_lock(&priv->lock);
1534 
1535 	if (priv->stream_count > 0) {
1536 		ret = -EBUSY;
1537 		goto out;
1538 	}
1539 
1540 	crop = __csi_get_crop(priv, sd_state, sdformat->which);
1541 	compose = __csi_get_compose(priv, sd_state, sdformat->which);
1542 
1543 	csi_try_fmt(priv, &upstream_ep, sd_state, sdformat, crop, compose,
1544 		    &cc);
1545 
1546 	fmt = __csi_get_fmt(priv, sd_state, sdformat->pad, sdformat->which);
1547 	*fmt = sdformat->format;
1548 
1549 	if (sdformat->pad == CSI_SINK_PAD) {
1550 		int pad;
1551 
1552 		/* propagate format to source pads */
1553 		for (pad = CSI_SINK_PAD + 1; pad < CSI_NUM_PADS; pad++) {
1554 			const struct imx_media_pixfmt *outcc;
1555 			struct v4l2_mbus_framefmt *outfmt;
1556 			struct v4l2_subdev_format format;
1557 
1558 			format.pad = pad;
1559 			format.which = sdformat->which;
1560 			format.format = sdformat->format;
1561 			csi_try_fmt(priv, &upstream_ep, sd_state, &format,
1562 				    NULL, compose, &outcc);
1563 
1564 			outfmt = __csi_get_fmt(priv, sd_state, pad,
1565 					       sdformat->which);
1566 			*outfmt = format.format;
1567 
1568 			if (sdformat->which == V4L2_SUBDEV_FORMAT_ACTIVE)
1569 				priv->cc[pad] = outcc;
1570 		}
1571 	}
1572 
1573 	if (sdformat->which == V4L2_SUBDEV_FORMAT_ACTIVE)
1574 		priv->cc[sdformat->pad] = cc;
1575 
1576 out:
1577 	mutex_unlock(&priv->lock);
1578 	return ret;
1579 }
1580 
1581 static int csi_get_selection(struct v4l2_subdev *sd,
1582 			     struct v4l2_subdev_state *sd_state,
1583 			     struct v4l2_subdev_selection *sel)
1584 {
1585 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1586 	struct v4l2_mbus_framefmt *infmt;
1587 	struct v4l2_rect *crop, *compose;
1588 	int ret = 0;
1589 
1590 	if (sel->pad != CSI_SINK_PAD)
1591 		return -EINVAL;
1592 
1593 	mutex_lock(&priv->lock);
1594 
1595 	infmt = __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, sel->which);
1596 	crop = __csi_get_crop(priv, sd_state, sel->which);
1597 	compose = __csi_get_compose(priv, sd_state, sel->which);
1598 
1599 	switch (sel->target) {
1600 	case V4L2_SEL_TGT_CROP_BOUNDS:
1601 		sel->r.left = 0;
1602 		sel->r.top = 0;
1603 		sel->r.width = infmt->width;
1604 		sel->r.height = infmt->height;
1605 		if (infmt->field == V4L2_FIELD_ALTERNATE)
1606 			sel->r.height *= 2;
1607 		break;
1608 	case V4L2_SEL_TGT_CROP:
1609 		sel->r = *crop;
1610 		break;
1611 	case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1612 		sel->r.left = 0;
1613 		sel->r.top = 0;
1614 		sel->r.width = crop->width;
1615 		sel->r.height = crop->height;
1616 		break;
1617 	case V4L2_SEL_TGT_COMPOSE:
1618 		sel->r = *compose;
1619 		break;
1620 	default:
1621 		ret = -EINVAL;
1622 	}
1623 
1624 	mutex_unlock(&priv->lock);
1625 	return ret;
1626 }
1627 
1628 static int csi_set_scale(u32 *compose, u32 crop, u32 flags)
1629 {
1630 	if ((flags & (V4L2_SEL_FLAG_LE | V4L2_SEL_FLAG_GE)) ==
1631 		     (V4L2_SEL_FLAG_LE | V4L2_SEL_FLAG_GE) &&
1632 	    *compose != crop && *compose != crop / 2)
1633 		return -ERANGE;
1634 
1635 	if (*compose <= crop / 2 ||
1636 	    (*compose < crop * 3 / 4 && !(flags & V4L2_SEL_FLAG_GE)) ||
1637 	    (*compose < crop && (flags & V4L2_SEL_FLAG_LE)))
1638 		*compose = crop / 2;
1639 	else
1640 		*compose = crop;
1641 
1642 	return 0;
1643 }
1644 
1645 static int csi_set_selection(struct v4l2_subdev *sd,
1646 			     struct v4l2_subdev_state *sd_state,
1647 			     struct v4l2_subdev_selection *sel)
1648 {
1649 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1650 	struct v4l2_fwnode_endpoint upstream_ep = { .bus_type = 0 };
1651 	struct v4l2_mbus_framefmt *infmt;
1652 	struct v4l2_rect *crop, *compose;
1653 	int pad, ret;
1654 
1655 	if (sel->pad != CSI_SINK_PAD)
1656 		return -EINVAL;
1657 
1658 	ret = csi_get_upstream_endpoint(priv, &upstream_ep);
1659 	if (ret) {
1660 		v4l2_err(&priv->sd, "failed to find upstream endpoint\n");
1661 		return ret;
1662 	}
1663 
1664 	mutex_lock(&priv->lock);
1665 
1666 	if (priv->stream_count > 0) {
1667 		ret = -EBUSY;
1668 		goto out;
1669 	}
1670 
1671 	infmt = __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, sel->which);
1672 	crop = __csi_get_crop(priv, sd_state, sel->which);
1673 	compose = __csi_get_compose(priv, sd_state, sel->which);
1674 
1675 	switch (sel->target) {
1676 	case V4L2_SEL_TGT_CROP:
1677 		/*
1678 		 * Modifying the crop rectangle always changes the format on
1679 		 * the source pads. If the KEEP_CONFIG flag is set, just return
1680 		 * the current crop rectangle.
1681 		 */
1682 		if (sel->flags & V4L2_SEL_FLAG_KEEP_CONFIG) {
1683 			sel->r = priv->crop;
1684 			if (sel->which == V4L2_SUBDEV_FORMAT_TRY)
1685 				*crop = sel->r;
1686 			goto out;
1687 		}
1688 
1689 		csi_try_crop(priv, &sel->r, sd_state, infmt, &upstream_ep);
1690 
1691 		*crop = sel->r;
1692 
1693 		/* Reset scaling to 1:1 */
1694 		compose->width = crop->width;
1695 		compose->height = crop->height;
1696 		break;
1697 	case V4L2_SEL_TGT_COMPOSE:
1698 		/*
1699 		 * Modifying the compose rectangle always changes the format on
1700 		 * the source pads. If the KEEP_CONFIG flag is set, just return
1701 		 * the current compose rectangle.
1702 		 */
1703 		if (sel->flags & V4L2_SEL_FLAG_KEEP_CONFIG) {
1704 			sel->r = priv->compose;
1705 			if (sel->which == V4L2_SUBDEV_FORMAT_TRY)
1706 				*compose = sel->r;
1707 			goto out;
1708 		}
1709 
1710 		sel->r.left = 0;
1711 		sel->r.top = 0;
1712 		ret = csi_set_scale(&sel->r.width, crop->width, sel->flags);
1713 		if (ret)
1714 			goto out;
1715 		ret = csi_set_scale(&sel->r.height, crop->height, sel->flags);
1716 		if (ret)
1717 			goto out;
1718 
1719 		*compose = sel->r;
1720 		break;
1721 	default:
1722 		ret = -EINVAL;
1723 		goto out;
1724 	}
1725 
1726 	/* Reset source pads to sink compose rectangle */
1727 	for (pad = CSI_SINK_PAD + 1; pad < CSI_NUM_PADS; pad++) {
1728 		struct v4l2_mbus_framefmt *outfmt;
1729 
1730 		outfmt = __csi_get_fmt(priv, sd_state, pad, sel->which);
1731 		outfmt->width = compose->width;
1732 		outfmt->height = compose->height;
1733 	}
1734 
1735 out:
1736 	mutex_unlock(&priv->lock);
1737 	return ret;
1738 }
1739 
1740 static int csi_subscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh,
1741 			       struct v4l2_event_subscription *sub)
1742 {
1743 	if (sub->type != V4L2_EVENT_IMX_FRAME_INTERVAL_ERROR)
1744 		return -EINVAL;
1745 	if (sub->id != 0)
1746 		return -EINVAL;
1747 
1748 	return v4l2_event_subscribe(fh, sub, 0, NULL);
1749 }
1750 
1751 static int csi_unsubscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh,
1752 				 struct v4l2_event_subscription *sub)
1753 {
1754 	return v4l2_event_unsubscribe(fh, sub);
1755 }
1756 
1757 static int csi_registered(struct v4l2_subdev *sd)
1758 {
1759 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1760 	struct ipu_csi *csi;
1761 	int i, ret;
1762 	u32 code;
1763 
1764 	/* get handle to IPU CSI */
1765 	csi = ipu_csi_get(priv->ipu, priv->csi_id);
1766 	if (IS_ERR(csi)) {
1767 		v4l2_err(&priv->sd, "failed to get CSI%d\n", priv->csi_id);
1768 		return PTR_ERR(csi);
1769 	}
1770 	priv->csi = csi;
1771 
1772 	for (i = 0; i < CSI_NUM_PADS; i++) {
1773 		code = 0;
1774 		if (i != CSI_SINK_PAD)
1775 			imx_media_enum_ipu_formats(&code, 0, PIXFMT_SEL_YUV);
1776 
1777 		/* set a default mbus format  */
1778 		ret = imx_media_init_mbus_fmt(&priv->format_mbus[i],
1779 					      IMX_MEDIA_DEF_PIX_WIDTH,
1780 					      IMX_MEDIA_DEF_PIX_HEIGHT, code,
1781 					      V4L2_FIELD_NONE, &priv->cc[i]);
1782 		if (ret)
1783 			goto put_csi;
1784 
1785 		/* init default frame interval */
1786 		priv->frame_interval[i].numerator = 1;
1787 		priv->frame_interval[i].denominator = 30;
1788 	}
1789 
1790 	/* disable frame skipping */
1791 	priv->skip = &csi_skip[0];
1792 
1793 	/* init default crop and compose rectangle sizes */
1794 	priv->crop.width = IMX_MEDIA_DEF_PIX_WIDTH;
1795 	priv->crop.height = IMX_MEDIA_DEF_PIX_HEIGHT;
1796 	priv->compose.width = IMX_MEDIA_DEF_PIX_WIDTH;
1797 	priv->compose.height = IMX_MEDIA_DEF_PIX_HEIGHT;
1798 
1799 	priv->fim = imx_media_fim_init(&priv->sd);
1800 	if (IS_ERR(priv->fim)) {
1801 		ret = PTR_ERR(priv->fim);
1802 		goto put_csi;
1803 	}
1804 
1805 	priv->vdev = imx_media_capture_device_init(priv->sd.dev, &priv->sd,
1806 						   CSI_SRC_PAD_IDMAC, true);
1807 	if (IS_ERR(priv->vdev)) {
1808 		ret = PTR_ERR(priv->vdev);
1809 		goto free_fim;
1810 	}
1811 
1812 	ret = imx_media_capture_device_register(priv->vdev, 0);
1813 	if (ret)
1814 		goto remove_vdev;
1815 
1816 	return 0;
1817 
1818 remove_vdev:
1819 	imx_media_capture_device_remove(priv->vdev);
1820 free_fim:
1821 	if (priv->fim)
1822 		imx_media_fim_free(priv->fim);
1823 put_csi:
1824 	ipu_csi_put(priv->csi);
1825 	return ret;
1826 }
1827 
1828 static void csi_unregistered(struct v4l2_subdev *sd)
1829 {
1830 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1831 
1832 	imx_media_capture_device_unregister(priv->vdev);
1833 	imx_media_capture_device_remove(priv->vdev);
1834 
1835 	if (priv->fim)
1836 		imx_media_fim_free(priv->fim);
1837 
1838 	if (priv->csi)
1839 		ipu_csi_put(priv->csi);
1840 }
1841 
1842 /*
1843  * The CSI has only one fwnode endpoint, at the sink pad. Verify the
1844  * endpoint belongs to us, and return CSI_SINK_PAD.
1845  */
1846 static int csi_get_fwnode_pad(struct media_entity *entity,
1847 			      struct fwnode_endpoint *endpoint)
1848 {
1849 	struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
1850 	struct csi_priv *priv = v4l2_get_subdevdata(sd);
1851 	struct fwnode_handle *csi_port = dev_fwnode(priv->dev);
1852 	struct fwnode_handle *csi_ep;
1853 	int ret;
1854 
1855 	csi_ep = fwnode_get_next_child_node(csi_port, NULL);
1856 
1857 	ret = endpoint->local_fwnode == csi_ep ? CSI_SINK_PAD : -ENXIO;
1858 
1859 	fwnode_handle_put(csi_ep);
1860 
1861 	return ret;
1862 }
1863 
1864 static const struct media_entity_operations csi_entity_ops = {
1865 	.link_setup = csi_link_setup,
1866 	.link_validate = v4l2_subdev_link_validate,
1867 	.get_fwnode_pad = csi_get_fwnode_pad,
1868 };
1869 
1870 static const struct v4l2_subdev_core_ops csi_core_ops = {
1871 	.subscribe_event = csi_subscribe_event,
1872 	.unsubscribe_event = csi_unsubscribe_event,
1873 };
1874 
1875 static const struct v4l2_subdev_video_ops csi_video_ops = {
1876 	.g_frame_interval = csi_g_frame_interval,
1877 	.s_frame_interval = csi_s_frame_interval,
1878 	.s_stream = csi_s_stream,
1879 };
1880 
1881 static const struct v4l2_subdev_pad_ops csi_pad_ops = {
1882 	.init_cfg = imx_media_init_cfg,
1883 	.enum_mbus_code = csi_enum_mbus_code,
1884 	.enum_frame_size = csi_enum_frame_size,
1885 	.enum_frame_interval = csi_enum_frame_interval,
1886 	.get_fmt = csi_get_fmt,
1887 	.set_fmt = csi_set_fmt,
1888 	.get_selection = csi_get_selection,
1889 	.set_selection = csi_set_selection,
1890 	.link_validate = csi_link_validate,
1891 };
1892 
1893 static const struct v4l2_subdev_ops csi_subdev_ops = {
1894 	.core = &csi_core_ops,
1895 	.video = &csi_video_ops,
1896 	.pad = &csi_pad_ops,
1897 };
1898 
1899 static const struct v4l2_subdev_internal_ops csi_internal_ops = {
1900 	.registered = csi_registered,
1901 	.unregistered = csi_unregistered,
1902 };
1903 
1904 static int imx_csi_notify_bound(struct v4l2_async_notifier *notifier,
1905 				struct v4l2_subdev *sd,
1906 				struct v4l2_async_subdev *asd)
1907 {
1908 	struct csi_priv *priv = notifier_to_dev(notifier);
1909 	struct media_pad *sink = &priv->sd.entity.pads[CSI_SINK_PAD];
1910 
1911 	/*
1912 	 * If the subdev is a video mux, it must be one of the CSI
1913 	 * muxes. Mark it as such via its group id.
1914 	 */
1915 	if (sd->entity.function == MEDIA_ENT_F_VID_MUX)
1916 		sd->grp_id = IMX_MEDIA_GRP_ID_CSI_MUX;
1917 
1918 	return v4l2_create_fwnode_links_to_pad(sd, sink, 0);
1919 }
1920 
1921 static const struct v4l2_async_notifier_operations csi_notify_ops = {
1922 	.bound = imx_csi_notify_bound,
1923 };
1924 
1925 static int imx_csi_async_register(struct csi_priv *priv)
1926 {
1927 	struct v4l2_async_subdev *asd = NULL;
1928 	struct fwnode_handle *ep;
1929 	unsigned int port;
1930 	int ret;
1931 
1932 	v4l2_async_nf_init(&priv->notifier);
1933 
1934 	/* get this CSI's port id */
1935 	ret = fwnode_property_read_u32(dev_fwnode(priv->dev), "reg", &port);
1936 	if (ret < 0)
1937 		return ret;
1938 
1939 	ep = fwnode_graph_get_endpoint_by_id(dev_fwnode(priv->dev->parent),
1940 					     port, 0,
1941 					     FWNODE_GRAPH_ENDPOINT_NEXT);
1942 	if (ep) {
1943 		asd = v4l2_async_nf_add_fwnode_remote(&priv->notifier, ep,
1944 						      struct v4l2_async_subdev);
1945 
1946 		fwnode_handle_put(ep);
1947 
1948 		if (IS_ERR(asd)) {
1949 			ret = PTR_ERR(asd);
1950 			/* OK if asd already exists */
1951 			if (ret != -EEXIST)
1952 				return ret;
1953 		}
1954 	}
1955 
1956 	priv->notifier.ops = &csi_notify_ops;
1957 
1958 	ret = v4l2_async_subdev_nf_register(&priv->sd, &priv->notifier);
1959 	if (ret)
1960 		return ret;
1961 
1962 	return v4l2_async_register_subdev(&priv->sd);
1963 }
1964 
1965 static int imx_csi_probe(struct platform_device *pdev)
1966 {
1967 	struct ipu_client_platformdata *pdata;
1968 	struct pinctrl *pinctrl;
1969 	struct csi_priv *priv;
1970 	int i, ret;
1971 
1972 	priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
1973 	if (!priv)
1974 		return -ENOMEM;
1975 
1976 	platform_set_drvdata(pdev, &priv->sd);
1977 	priv->dev = &pdev->dev;
1978 
1979 	ret = dma_set_coherent_mask(priv->dev, DMA_BIT_MASK(32));
1980 	if (ret)
1981 		return ret;
1982 
1983 	/* get parent IPU */
1984 	priv->ipu = dev_get_drvdata(priv->dev->parent);
1985 
1986 	/* get our CSI id */
1987 	pdata = priv->dev->platform_data;
1988 	priv->csi_id = pdata->csi;
1989 	priv->smfc_id = (priv->csi_id == 0) ? 0 : 2;
1990 
1991 	priv->active_output_pad = CSI_SRC_PAD_IDMAC;
1992 
1993 	timer_setup(&priv->eof_timeout_timer, csi_idmac_eof_timeout, 0);
1994 	spin_lock_init(&priv->irqlock);
1995 
1996 	v4l2_subdev_init(&priv->sd, &csi_subdev_ops);
1997 	v4l2_set_subdevdata(&priv->sd, priv);
1998 	priv->sd.internal_ops = &csi_internal_ops;
1999 	priv->sd.entity.ops = &csi_entity_ops;
2000 	priv->sd.entity.function = MEDIA_ENT_F_PROC_VIDEO_PIXEL_FORMATTER;
2001 	priv->sd.dev = &pdev->dev;
2002 	priv->sd.fwnode = of_fwnode_handle(pdata->of_node);
2003 	priv->sd.owner = THIS_MODULE;
2004 	priv->sd.flags = V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS;
2005 	priv->sd.grp_id = priv->csi_id ?
2006 		IMX_MEDIA_GRP_ID_IPU_CSI1 : IMX_MEDIA_GRP_ID_IPU_CSI0;
2007 	imx_media_grp_id_to_sd_name(priv->sd.name, sizeof(priv->sd.name),
2008 				    priv->sd.grp_id, ipu_get_num(priv->ipu));
2009 
2010 	for (i = 0; i < CSI_NUM_PADS; i++)
2011 		priv->pad[i].flags = (i == CSI_SINK_PAD) ?
2012 			MEDIA_PAD_FL_SINK : MEDIA_PAD_FL_SOURCE;
2013 
2014 	ret = media_entity_pads_init(&priv->sd.entity, CSI_NUM_PADS,
2015 				     priv->pad);
2016 	if (ret)
2017 		return ret;
2018 
2019 	mutex_init(&priv->lock);
2020 
2021 	v4l2_ctrl_handler_init(&priv->ctrl_hdlr, 0);
2022 	priv->sd.ctrl_handler = &priv->ctrl_hdlr;
2023 
2024 	/*
2025 	 * The IPUv3 driver did not assign an of_node to this
2026 	 * device. As a result, pinctrl does not automatically
2027 	 * configure our pin groups, so we need to do that manually
2028 	 * here, after setting this device's of_node.
2029 	 */
2030 	priv->dev->of_node = pdata->of_node;
2031 	pinctrl = devm_pinctrl_get_select_default(priv->dev);
2032 	if (IS_ERR(pinctrl)) {
2033 		ret = PTR_ERR(pinctrl);
2034 		dev_dbg(priv->dev,
2035 			"devm_pinctrl_get_select_default() failed: %d\n", ret);
2036 		if (ret != -ENODEV)
2037 			goto free;
2038 	}
2039 
2040 	ret = imx_csi_async_register(priv);
2041 	if (ret)
2042 		goto cleanup;
2043 
2044 	return 0;
2045 
2046 cleanup:
2047 	v4l2_async_nf_unregister(&priv->notifier);
2048 	v4l2_async_nf_cleanup(&priv->notifier);
2049 free:
2050 	v4l2_ctrl_handler_free(&priv->ctrl_hdlr);
2051 	mutex_destroy(&priv->lock);
2052 	return ret;
2053 }
2054 
2055 static int imx_csi_remove(struct platform_device *pdev)
2056 {
2057 	struct v4l2_subdev *sd = platform_get_drvdata(pdev);
2058 	struct csi_priv *priv = sd_to_dev(sd);
2059 
2060 	v4l2_ctrl_handler_free(&priv->ctrl_hdlr);
2061 	mutex_destroy(&priv->lock);
2062 	v4l2_async_nf_unregister(&priv->notifier);
2063 	v4l2_async_nf_cleanup(&priv->notifier);
2064 	v4l2_async_unregister_subdev(sd);
2065 	media_entity_cleanup(&sd->entity);
2066 
2067 	return 0;
2068 }
2069 
2070 static const struct platform_device_id imx_csi_ids[] = {
2071 	{ .name = "imx-ipuv3-csi" },
2072 	{ },
2073 };
2074 MODULE_DEVICE_TABLE(platform, imx_csi_ids);
2075 
2076 static struct platform_driver imx_csi_driver = {
2077 	.probe = imx_csi_probe,
2078 	.remove = imx_csi_remove,
2079 	.id_table = imx_csi_ids,
2080 	.driver = {
2081 		.name = "imx-ipuv3-csi",
2082 	},
2083 };
2084 module_platform_driver(imx_csi_driver);
2085 
2086 MODULE_DESCRIPTION("i.MX CSI subdev driver");
2087 MODULE_AUTHOR("Steve Longerbeam <steve_longerbeam@mentor.com>");
2088 MODULE_LICENSE("GPL");
2089