GNU Linux-libre 5.19-rc6-gnu
[releases.git] / drivers / staging / media / imx / imx-media-csi.c
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         if (is_parallel_bus(&priv->upstream_ep))
722                 mbus_cfg.bus.parallel = priv->upstream_ep.bus.parallel;
723         else
724                 mbus_cfg.bus.mipi_csi2 = priv->upstream_ep.bus.mipi_csi2;
725
726         if_fmt = *infmt;
727         crop = priv->crop;
728
729         /*
730          * if cycles is set, we need to handle this over multiple cycles as
731          * generic/bayer data
732          */
733         if (is_parallel_bus(&priv->upstream_ep) && incc->cycles) {
734                 if_fmt.width *= incc->cycles;
735                 crop.width *= incc->cycles;
736         }
737
738         ipu_csi_set_window(priv->csi, &crop);
739
740         ipu_csi_set_downsize(priv->csi,
741                              priv->crop.width == 2 * priv->compose.width,
742                              priv->crop.height == 2 * priv->compose.height);
743
744         ipu_csi_init_interface(priv->csi, &mbus_cfg, &if_fmt, outfmt);
745
746         ipu_csi_set_dest(priv->csi, priv->dest);
747
748         if (priv->dest == IPU_CSI_DEST_IDMAC)
749                 ipu_csi_set_skip_smfc(priv->csi, priv->skip->skip_smfc,
750                                       priv->skip->max_ratio - 1, 0);
751
752         ipu_csi_dump(priv->csi);
753
754         return 0;
755 }
756
757 static int csi_start(struct csi_priv *priv)
758 {
759         struct v4l2_fract *input_fi, *output_fi;
760         int ret;
761
762         input_fi = &priv->frame_interval[CSI_SINK_PAD];
763         output_fi = &priv->frame_interval[priv->active_output_pad];
764
765         /* start upstream */
766         ret = v4l2_subdev_call(priv->src_sd, video, s_stream, 1);
767         ret = (ret && ret != -ENOIOCTLCMD) ? ret : 0;
768         if (ret)
769                 return ret;
770
771         /* Skip first few frames from a BT.656 source */
772         if (priv->upstream_ep.bus_type == V4L2_MBUS_BT656) {
773                 u32 delay_usec, bad_frames = 20;
774
775                 delay_usec = DIV_ROUND_UP_ULL((u64)USEC_PER_SEC *
776                         input_fi->numerator * bad_frames,
777                         input_fi->denominator);
778
779                 usleep_range(delay_usec, delay_usec + 1000);
780         }
781
782         if (priv->dest == IPU_CSI_DEST_IDMAC) {
783                 ret = csi_idmac_start(priv);
784                 if (ret)
785                         goto stop_upstream;
786         }
787
788         ret = csi_setup(priv);
789         if (ret)
790                 goto idmac_stop;
791
792         /* start the frame interval monitor */
793         if (priv->fim && priv->dest == IPU_CSI_DEST_IDMAC) {
794                 ret = imx_media_fim_set_stream(priv->fim, output_fi, true);
795                 if (ret)
796                         goto idmac_stop;
797         }
798
799         ret = ipu_csi_enable(priv->csi);
800         if (ret) {
801                 v4l2_err(&priv->sd, "CSI enable error: %d\n", ret);
802                 goto fim_off;
803         }
804
805         return 0;
806
807 fim_off:
808         if (priv->fim && priv->dest == IPU_CSI_DEST_IDMAC)
809                 imx_media_fim_set_stream(priv->fim, NULL, false);
810 idmac_stop:
811         if (priv->dest == IPU_CSI_DEST_IDMAC)
812                 csi_idmac_stop(priv);
813 stop_upstream:
814         v4l2_subdev_call(priv->src_sd, video, s_stream, 0);
815         return ret;
816 }
817
818 static void csi_stop(struct csi_priv *priv)
819 {
820         if (priv->dest == IPU_CSI_DEST_IDMAC)
821                 csi_idmac_wait_last_eof(priv);
822
823         /*
824          * Disable the CSI asap, after syncing with the last EOF.
825          * Doing so after the IDMA channel is disabled has shown to
826          * create hard system-wide hangs.
827          */
828         ipu_csi_disable(priv->csi);
829
830         /* stop upstream */
831         v4l2_subdev_call(priv->src_sd, video, s_stream, 0);
832
833         if (priv->dest == IPU_CSI_DEST_IDMAC) {
834                 csi_idmac_stop(priv);
835
836                 /* stop the frame interval monitor */
837                 if (priv->fim)
838                         imx_media_fim_set_stream(priv->fim, NULL, false);
839         }
840 }
841
842 static const struct csi_skip_desc csi_skip[12] = {
843         { 1, 1, 0x00 }, /* Keep all frames */
844         { 5, 6, 0x10 }, /* Skip every sixth frame */
845         { 4, 5, 0x08 }, /* Skip every fifth frame */
846         { 3, 4, 0x04 }, /* Skip every fourth frame */
847         { 2, 3, 0x02 }, /* Skip every third frame */
848         { 3, 5, 0x0a }, /* Skip frames 1 and 3 of every 5 */
849         { 1, 2, 0x01 }, /* Skip every second frame */
850         { 2, 5, 0x0b }, /* Keep frames 1 and 4 of every 5 */
851         { 1, 3, 0x03 }, /* Keep one in three frames */
852         { 1, 4, 0x07 }, /* Keep one in four frames */
853         { 1, 5, 0x0f }, /* Keep one in five frames */
854         { 1, 6, 0x1f }, /* Keep one in six frames */
855 };
856
857 static void csi_apply_skip_interval(const struct csi_skip_desc *skip,
858                                     struct v4l2_fract *interval)
859 {
860         unsigned int div;
861
862         interval->numerator *= skip->max_ratio;
863         interval->denominator *= skip->keep;
864
865         /* Reduce fraction to lowest terms */
866         div = gcd(interval->numerator, interval->denominator);
867         if (div > 1) {
868                 interval->numerator /= div;
869                 interval->denominator /= div;
870         }
871 }
872
873 /*
874  * Find the skip pattern to produce the output frame interval closest to the
875  * requested one, for the given input frame interval. Updates the output frame
876  * interval to the exact value.
877  */
878 static const struct csi_skip_desc *csi_find_best_skip(struct v4l2_fract *in,
879                                                       struct v4l2_fract *out)
880 {
881         const struct csi_skip_desc *skip = &csi_skip[0], *best_skip = skip;
882         u32 min_err = UINT_MAX;
883         u64 want_us;
884         int i;
885
886         /* Default to 1:1 ratio */
887         if (out->numerator == 0 || out->denominator == 0 ||
888             in->numerator == 0 || in->denominator == 0) {
889                 *out = *in;
890                 return best_skip;
891         }
892
893         want_us = div_u64((u64)USEC_PER_SEC * out->numerator, out->denominator);
894
895         /* Find the reduction closest to the requested time per frame */
896         for (i = 0; i < ARRAY_SIZE(csi_skip); i++, skip++) {
897                 u64 tmp, err;
898
899                 tmp = div_u64((u64)USEC_PER_SEC * in->numerator *
900                               skip->max_ratio, in->denominator * skip->keep);
901
902                 err = abs((s64)tmp - want_us);
903                 if (err < min_err) {
904                         min_err = err;
905                         best_skip = skip;
906                 }
907         }
908
909         *out = *in;
910         csi_apply_skip_interval(best_skip, out);
911
912         return best_skip;
913 }
914
915 /*
916  * V4L2 subdev operations.
917  */
918
919 static int csi_g_frame_interval(struct v4l2_subdev *sd,
920                                 struct v4l2_subdev_frame_interval *fi)
921 {
922         struct csi_priv *priv = v4l2_get_subdevdata(sd);
923
924         if (fi->pad >= CSI_NUM_PADS)
925                 return -EINVAL;
926
927         mutex_lock(&priv->lock);
928
929         fi->interval = priv->frame_interval[fi->pad];
930
931         mutex_unlock(&priv->lock);
932
933         return 0;
934 }
935
936 static int csi_s_frame_interval(struct v4l2_subdev *sd,
937                                 struct v4l2_subdev_frame_interval *fi)
938 {
939         struct csi_priv *priv = v4l2_get_subdevdata(sd);
940         struct v4l2_fract *input_fi;
941         int ret = 0;
942
943         mutex_lock(&priv->lock);
944
945         input_fi = &priv->frame_interval[CSI_SINK_PAD];
946
947         switch (fi->pad) {
948         case CSI_SINK_PAD:
949                 /* No limits on valid input frame intervals */
950                 if (fi->interval.numerator == 0 ||
951                     fi->interval.denominator == 0)
952                         fi->interval = *input_fi;
953                 /* Reset output intervals and frame skipping ratio to 1:1 */
954                 priv->frame_interval[CSI_SRC_PAD_IDMAC] = fi->interval;
955                 priv->frame_interval[CSI_SRC_PAD_DIRECT] = fi->interval;
956                 priv->skip = &csi_skip[0];
957                 break;
958         case CSI_SRC_PAD_IDMAC:
959                 /*
960                  * frame interval at IDMAC output pad depends on input
961                  * interval, modified by frame skipping.
962                  */
963                 priv->skip = csi_find_best_skip(input_fi, &fi->interval);
964                 break;
965         case CSI_SRC_PAD_DIRECT:
966                 /*
967                  * frame interval at DIRECT output pad is same as input
968                  * interval.
969                  */
970                 fi->interval = *input_fi;
971                 break;
972         default:
973                 ret = -EINVAL;
974                 goto out;
975         }
976
977         priv->frame_interval[fi->pad] = fi->interval;
978 out:
979         mutex_unlock(&priv->lock);
980         return ret;
981 }
982
983 static int csi_s_stream(struct v4l2_subdev *sd, int enable)
984 {
985         struct csi_priv *priv = v4l2_get_subdevdata(sd);
986         int ret = 0;
987
988         mutex_lock(&priv->lock);
989
990         if (!priv->src_sd || !priv->sink) {
991                 ret = -EPIPE;
992                 goto out;
993         }
994
995         /*
996          * enable/disable streaming only if stream_count is
997          * going from 0 to 1 / 1 to 0.
998          */
999         if (priv->stream_count != !enable)
1000                 goto update_count;
1001
1002         if (enable) {
1003                 dev_dbg(priv->dev, "stream ON\n");
1004                 ret = csi_start(priv);
1005                 if (ret)
1006                         goto out;
1007         } else {
1008                 dev_dbg(priv->dev, "stream OFF\n");
1009                 csi_stop(priv);
1010         }
1011
1012 update_count:
1013         priv->stream_count += enable ? 1 : -1;
1014         if (priv->stream_count < 0)
1015                 priv->stream_count = 0;
1016 out:
1017         mutex_unlock(&priv->lock);
1018         return ret;
1019 }
1020
1021 static int csi_link_setup(struct media_entity *entity,
1022                           const struct media_pad *local,
1023                           const struct media_pad *remote, u32 flags)
1024 {
1025         struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
1026         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1027         struct v4l2_subdev *remote_sd;
1028         int ret = 0;
1029
1030         dev_dbg(priv->dev, "link setup %s -> %s\n", remote->entity->name,
1031                 local->entity->name);
1032
1033         mutex_lock(&priv->lock);
1034
1035         if (local->flags & MEDIA_PAD_FL_SINK) {
1036                 if (!is_media_entity_v4l2_subdev(remote->entity)) {
1037                         ret = -EINVAL;
1038                         goto out;
1039                 }
1040
1041                 remote_sd = media_entity_to_v4l2_subdev(remote->entity);
1042
1043                 if (flags & MEDIA_LNK_FL_ENABLED) {
1044                         if (priv->src_sd) {
1045                                 ret = -EBUSY;
1046                                 goto out;
1047                         }
1048                         priv->src_sd = remote_sd;
1049                 } else {
1050                         priv->src_sd = NULL;
1051                 }
1052
1053                 goto out;
1054         }
1055
1056         /* this is a source pad */
1057
1058         if (flags & MEDIA_LNK_FL_ENABLED) {
1059                 if (priv->sink) {
1060                         ret = -EBUSY;
1061                         goto out;
1062                 }
1063         } else {
1064                 v4l2_ctrl_handler_free(&priv->ctrl_hdlr);
1065                 v4l2_ctrl_handler_init(&priv->ctrl_hdlr, 0);
1066                 priv->sink = NULL;
1067                 /* do not apply IC burst alignment in csi_try_crop */
1068                 priv->active_output_pad = CSI_SRC_PAD_IDMAC;
1069                 goto out;
1070         }
1071
1072         /* record which output pad is now active */
1073         priv->active_output_pad = local->index;
1074
1075         /* set CSI destination */
1076         if (local->index == CSI_SRC_PAD_IDMAC) {
1077                 if (!is_media_entity_v4l2_video_device(remote->entity)) {
1078                         ret = -EINVAL;
1079                         goto out;
1080                 }
1081
1082                 if (priv->fim) {
1083                         ret = imx_media_fim_add_controls(priv->fim);
1084                         if (ret)
1085                                 goto out;
1086                 }
1087
1088                 priv->dest = IPU_CSI_DEST_IDMAC;
1089         } else {
1090                 if (!is_media_entity_v4l2_subdev(remote->entity)) {
1091                         ret = -EINVAL;
1092                         goto out;
1093                 }
1094
1095                 remote_sd = media_entity_to_v4l2_subdev(remote->entity);
1096                 switch (remote_sd->grp_id) {
1097                 case IMX_MEDIA_GRP_ID_IPU_VDIC:
1098                         priv->dest = IPU_CSI_DEST_VDIC;
1099                         break;
1100                 case IMX_MEDIA_GRP_ID_IPU_IC_PRP:
1101                         priv->dest = IPU_CSI_DEST_IC;
1102                         break;
1103                 default:
1104                         ret = -EINVAL;
1105                         goto out;
1106                 }
1107         }
1108
1109         priv->sink = remote->entity;
1110 out:
1111         mutex_unlock(&priv->lock);
1112         return ret;
1113 }
1114
1115 static int csi_link_validate(struct v4l2_subdev *sd,
1116                              struct media_link *link,
1117                              struct v4l2_subdev_format *source_fmt,
1118                              struct v4l2_subdev_format *sink_fmt)
1119 {
1120         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1121         struct v4l2_fwnode_endpoint upstream_ep = { .bus_type = 0 };
1122         bool is_csi2;
1123         int ret;
1124
1125         ret = v4l2_subdev_link_validate_default(sd, link,
1126                                                 source_fmt, sink_fmt);
1127         if (ret)
1128                 return ret;
1129
1130         ret = csi_get_upstream_endpoint(priv, &upstream_ep);
1131         if (ret) {
1132                 v4l2_err(&priv->sd, "failed to find upstream endpoint\n");
1133                 return ret;
1134         }
1135
1136         mutex_lock(&priv->lock);
1137
1138         priv->upstream_ep = upstream_ep;
1139         is_csi2 = !is_parallel_bus(&upstream_ep);
1140         if (is_csi2) {
1141                 /*
1142                  * NOTE! It seems the virtual channels from the mipi csi-2
1143                  * receiver are used only for routing by the video mux's,
1144                  * or for hard-wired routing to the CSI's. Once the stream
1145                  * enters the CSI's however, they are treated internally
1146                  * in the IPU as virtual channel 0.
1147                  */
1148                 ipu_csi_set_mipi_datatype(priv->csi, 0,
1149                                           &priv->format_mbus[CSI_SINK_PAD]);
1150         }
1151
1152         /* select either parallel or MIPI-CSI2 as input to CSI */
1153         ipu_set_csi_src_mux(priv->ipu, priv->csi_id, is_csi2);
1154
1155         mutex_unlock(&priv->lock);
1156         return ret;
1157 }
1158
1159 static struct v4l2_mbus_framefmt *
1160 __csi_get_fmt(struct csi_priv *priv, struct v4l2_subdev_state *sd_state,
1161               unsigned int pad, enum v4l2_subdev_format_whence which)
1162 {
1163         if (which == V4L2_SUBDEV_FORMAT_TRY)
1164                 return v4l2_subdev_get_try_format(&priv->sd, sd_state, pad);
1165         else
1166                 return &priv->format_mbus[pad];
1167 }
1168
1169 static struct v4l2_rect *
1170 __csi_get_crop(struct csi_priv *priv, struct v4l2_subdev_state *sd_state,
1171                enum v4l2_subdev_format_whence which)
1172 {
1173         if (which == V4L2_SUBDEV_FORMAT_TRY)
1174                 return v4l2_subdev_get_try_crop(&priv->sd, sd_state,
1175                                                 CSI_SINK_PAD);
1176         else
1177                 return &priv->crop;
1178 }
1179
1180 static struct v4l2_rect *
1181 __csi_get_compose(struct csi_priv *priv, struct v4l2_subdev_state *sd_state,
1182                   enum v4l2_subdev_format_whence which)
1183 {
1184         if (which == V4L2_SUBDEV_FORMAT_TRY)
1185                 return v4l2_subdev_get_try_compose(&priv->sd, sd_state,
1186                                                    CSI_SINK_PAD);
1187         else
1188                 return &priv->compose;
1189 }
1190
1191 static void csi_try_crop(struct csi_priv *priv,
1192                          struct v4l2_rect *crop,
1193                          struct v4l2_subdev_state *sd_state,
1194                          struct v4l2_mbus_framefmt *infmt,
1195                          struct v4l2_fwnode_endpoint *upstream_ep)
1196 {
1197         u32 in_height;
1198
1199         crop->width = min_t(__u32, infmt->width, crop->width);
1200         if (crop->left + crop->width > infmt->width)
1201                 crop->left = infmt->width - crop->width;
1202         /* adjust crop left/width to h/w alignment restrictions */
1203         crop->left &= ~0x3;
1204         if (priv->active_output_pad == CSI_SRC_PAD_DIRECT)
1205                 crop->width &= ~0x7; /* multiple of 8 pixels (IC burst) */
1206         else
1207                 crop->width &= ~0x1; /* multiple of 2 pixels */
1208
1209         in_height = infmt->height;
1210         if (infmt->field == V4L2_FIELD_ALTERNATE)
1211                 in_height *= 2;
1212
1213         /*
1214          * FIXME: not sure why yet, but on interlaced bt.656,
1215          * changing the vertical cropping causes loss of vertical
1216          * sync, so fix it to NTSC/PAL active lines. NTSC contains
1217          * 2 extra lines of active video that need to be cropped.
1218          */
1219         if (upstream_ep->bus_type == V4L2_MBUS_BT656 &&
1220             (V4L2_FIELD_HAS_BOTH(infmt->field) ||
1221              infmt->field == V4L2_FIELD_ALTERNATE)) {
1222                 crop->height = in_height;
1223                 crop->top = (in_height == 480) ? 2 : 0;
1224         } else {
1225                 crop->height = min_t(__u32, in_height, crop->height);
1226                 if (crop->top + crop->height > in_height)
1227                         crop->top = in_height - crop->height;
1228         }
1229 }
1230
1231 static int csi_enum_mbus_code(struct v4l2_subdev *sd,
1232                               struct v4l2_subdev_state *sd_state,
1233                               struct v4l2_subdev_mbus_code_enum *code)
1234 {
1235         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1236         struct v4l2_fwnode_endpoint upstream_ep = { .bus_type = 0 };
1237         const struct imx_media_pixfmt *incc;
1238         struct v4l2_mbus_framefmt *infmt;
1239         int ret = 0;
1240
1241         mutex_lock(&priv->lock);
1242
1243         infmt = __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, code->which);
1244         incc = imx_media_find_mbus_format(infmt->code, PIXFMT_SEL_ANY);
1245
1246         switch (code->pad) {
1247         case CSI_SINK_PAD:
1248                 ret = imx_media_enum_mbus_formats(&code->code, code->index,
1249                                                   PIXFMT_SEL_ANY);
1250                 break;
1251         case CSI_SRC_PAD_DIRECT:
1252         case CSI_SRC_PAD_IDMAC:
1253                 ret = csi_get_upstream_endpoint(priv, &upstream_ep);
1254                 if (ret) {
1255                         v4l2_err(&priv->sd, "failed to find upstream endpoint\n");
1256                         goto out;
1257                 }
1258
1259                 if (requires_passthrough(&upstream_ep, infmt, incc)) {
1260                         if (code->index != 0) {
1261                                 ret = -EINVAL;
1262                                 goto out;
1263                         }
1264                         code->code = infmt->code;
1265                 } else {
1266                         enum imx_pixfmt_sel fmt_sel =
1267                                 (incc->cs == IPUV3_COLORSPACE_YUV) ?
1268                                 PIXFMT_SEL_YUV : PIXFMT_SEL_RGB;
1269
1270                         ret = imx_media_enum_ipu_formats(&code->code,
1271                                                          code->index,
1272                                                          fmt_sel);
1273                 }
1274                 break;
1275         default:
1276                 ret = -EINVAL;
1277         }
1278
1279 out:
1280         mutex_unlock(&priv->lock);
1281         return ret;
1282 }
1283
1284 static int csi_enum_frame_size(struct v4l2_subdev *sd,
1285                                struct v4l2_subdev_state *sd_state,
1286                                struct v4l2_subdev_frame_size_enum *fse)
1287 {
1288         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1289         struct v4l2_rect *crop;
1290         int ret = 0;
1291
1292         if (fse->pad >= CSI_NUM_PADS ||
1293             fse->index > (fse->pad == CSI_SINK_PAD ? 0 : 3))
1294                 return -EINVAL;
1295
1296         mutex_lock(&priv->lock);
1297
1298         if (fse->pad == CSI_SINK_PAD) {
1299                 fse->min_width = MIN_W;
1300                 fse->max_width = MAX_W;
1301                 fse->min_height = MIN_H;
1302                 fse->max_height = MAX_H;
1303         } else {
1304                 crop = __csi_get_crop(priv, sd_state, fse->which);
1305
1306                 fse->min_width = fse->index & 1 ?
1307                         crop->width / 2 : crop->width;
1308                 fse->max_width = fse->min_width;
1309                 fse->min_height = fse->index & 2 ?
1310                         crop->height / 2 : crop->height;
1311                 fse->max_height = fse->min_height;
1312         }
1313
1314         mutex_unlock(&priv->lock);
1315         return ret;
1316 }
1317
1318 static int csi_enum_frame_interval(struct v4l2_subdev *sd,
1319                                    struct v4l2_subdev_state *sd_state,
1320                                    struct v4l2_subdev_frame_interval_enum *fie)
1321 {
1322         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1323         struct v4l2_fract *input_fi;
1324         struct v4l2_rect *crop;
1325         int ret = 0;
1326
1327         if (fie->pad >= CSI_NUM_PADS ||
1328             fie->index >= (fie->pad != CSI_SRC_PAD_IDMAC ?
1329                            1 : ARRAY_SIZE(csi_skip)))
1330                 return -EINVAL;
1331
1332         mutex_lock(&priv->lock);
1333
1334         input_fi = &priv->frame_interval[CSI_SINK_PAD];
1335         crop = __csi_get_crop(priv, sd_state, fie->which);
1336
1337         if ((fie->width != crop->width && fie->width != crop->width / 2) ||
1338             (fie->height != crop->height && fie->height != crop->height / 2)) {
1339                 ret = -EINVAL;
1340                 goto out;
1341         }
1342
1343         fie->interval = *input_fi;
1344
1345         if (fie->pad == CSI_SRC_PAD_IDMAC)
1346                 csi_apply_skip_interval(&csi_skip[fie->index],
1347                                         &fie->interval);
1348
1349 out:
1350         mutex_unlock(&priv->lock);
1351         return ret;
1352 }
1353
1354 static int csi_get_fmt(struct v4l2_subdev *sd,
1355                        struct v4l2_subdev_state *sd_state,
1356                        struct v4l2_subdev_format *sdformat)
1357 {
1358         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1359         struct v4l2_mbus_framefmt *fmt;
1360         int ret = 0;
1361
1362         if (sdformat->pad >= CSI_NUM_PADS)
1363                 return -EINVAL;
1364
1365         mutex_lock(&priv->lock);
1366
1367         fmt = __csi_get_fmt(priv, sd_state, sdformat->pad, sdformat->which);
1368         if (!fmt) {
1369                 ret = -EINVAL;
1370                 goto out;
1371         }
1372
1373         sdformat->format = *fmt;
1374 out:
1375         mutex_unlock(&priv->lock);
1376         return ret;
1377 }
1378
1379 static void csi_try_field(struct csi_priv *priv,
1380                           struct v4l2_subdev_state *sd_state,
1381                           struct v4l2_subdev_format *sdformat)
1382 {
1383         struct v4l2_mbus_framefmt *infmt =
1384                 __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, sdformat->which);
1385
1386         /*
1387          * no restrictions on sink pad field type except must
1388          * be initialized.
1389          */
1390         if (sdformat->pad == CSI_SINK_PAD) {
1391                 if (sdformat->format.field == V4L2_FIELD_ANY)
1392                         sdformat->format.field = V4L2_FIELD_NONE;
1393                 return;
1394         }
1395
1396         switch (infmt->field) {
1397         case V4L2_FIELD_SEQ_TB:
1398         case V4L2_FIELD_SEQ_BT:
1399                 /*
1400                  * If the user requests sequential at the source pad,
1401                  * allow it (along with possibly inverting field order).
1402                  * Otherwise passthrough the field type.
1403                  */
1404                 if (!V4L2_FIELD_IS_SEQUENTIAL(sdformat->format.field))
1405                         sdformat->format.field = infmt->field;
1406                 break;
1407         case V4L2_FIELD_ALTERNATE:
1408                 /*
1409                  * This driver does not support alternate field mode, and
1410                  * the CSI captures a whole frame, so the CSI never presents
1411                  * alternate mode at its source pads. If user has not
1412                  * already requested sequential, translate ALTERNATE at
1413                  * sink pad to SEQ_TB or SEQ_BT at the source pad depending
1414                  * on input height (assume NTSC BT order if 480 total active
1415                  * frame lines, otherwise PAL TB order).
1416                  */
1417                 if (!V4L2_FIELD_IS_SEQUENTIAL(sdformat->format.field))
1418                         sdformat->format.field = (infmt->height == 480 / 2) ?
1419                                 V4L2_FIELD_SEQ_BT : V4L2_FIELD_SEQ_TB;
1420                 break;
1421         default:
1422                 /* Passthrough for all other input field types */
1423                 sdformat->format.field = infmt->field;
1424                 break;
1425         }
1426 }
1427
1428 static void csi_try_fmt(struct csi_priv *priv,
1429                         struct v4l2_fwnode_endpoint *upstream_ep,
1430                         struct v4l2_subdev_state *sd_state,
1431                         struct v4l2_subdev_format *sdformat,
1432                         struct v4l2_rect *crop,
1433                         struct v4l2_rect *compose,
1434                         const struct imx_media_pixfmt **cc)
1435 {
1436         const struct imx_media_pixfmt *incc;
1437         struct v4l2_mbus_framefmt *infmt;
1438         u32 code;
1439
1440         infmt = __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, sdformat->which);
1441
1442         switch (sdformat->pad) {
1443         case CSI_SRC_PAD_DIRECT:
1444         case CSI_SRC_PAD_IDMAC:
1445                 incc = imx_media_find_mbus_format(infmt->code, PIXFMT_SEL_ANY);
1446
1447                 sdformat->format.width = compose->width;
1448                 sdformat->format.height = compose->height;
1449
1450                 if (requires_passthrough(upstream_ep, infmt, incc)) {
1451                         sdformat->format.code = infmt->code;
1452                         *cc = incc;
1453                 } else {
1454                         enum imx_pixfmt_sel fmt_sel =
1455                                 (incc->cs == IPUV3_COLORSPACE_YUV) ?
1456                                 PIXFMT_SEL_YUV : PIXFMT_SEL_RGB;
1457
1458                         *cc = imx_media_find_ipu_format(sdformat->format.code,
1459                                                         fmt_sel);
1460                         if (!*cc) {
1461                                 imx_media_enum_ipu_formats(&code, 0, fmt_sel);
1462                                 *cc = imx_media_find_ipu_format(code, fmt_sel);
1463                                 sdformat->format.code = (*cc)->codes[0];
1464                         }
1465                 }
1466
1467                 csi_try_field(priv, sd_state, sdformat);
1468
1469                 /* propagate colorimetry from sink */
1470                 sdformat->format.colorspace = infmt->colorspace;
1471                 sdformat->format.xfer_func = infmt->xfer_func;
1472                 sdformat->format.quantization = infmt->quantization;
1473                 sdformat->format.ycbcr_enc = infmt->ycbcr_enc;
1474
1475                 break;
1476         case CSI_SINK_PAD:
1477                 v4l_bound_align_image(&sdformat->format.width, MIN_W, MAX_W,
1478                                       W_ALIGN, &sdformat->format.height,
1479                                       MIN_H, MAX_H, H_ALIGN, S_ALIGN);
1480
1481                 *cc = imx_media_find_mbus_format(sdformat->format.code,
1482                                                  PIXFMT_SEL_ANY);
1483                 if (!*cc) {
1484                         imx_media_enum_mbus_formats(&code, 0,
1485                                                     PIXFMT_SEL_YUV_RGB);
1486                         *cc = imx_media_find_mbus_format(code,
1487                                                          PIXFMT_SEL_YUV_RGB);
1488                         sdformat->format.code = (*cc)->codes[0];
1489                 }
1490
1491                 csi_try_field(priv, sd_state, sdformat);
1492
1493                 /* Reset crop and compose rectangles */
1494                 crop->left = 0;
1495                 crop->top = 0;
1496                 crop->width = sdformat->format.width;
1497                 crop->height = sdformat->format.height;
1498                 if (sdformat->format.field == V4L2_FIELD_ALTERNATE)
1499                         crop->height *= 2;
1500                 csi_try_crop(priv, crop, sd_state, &sdformat->format,
1501                              upstream_ep);
1502                 compose->left = 0;
1503                 compose->top = 0;
1504                 compose->width = crop->width;
1505                 compose->height = crop->height;
1506
1507                 break;
1508         }
1509
1510         imx_media_try_colorimetry(&sdformat->format,
1511                         priv->active_output_pad == CSI_SRC_PAD_DIRECT);
1512 }
1513
1514 static int csi_set_fmt(struct v4l2_subdev *sd,
1515                        struct v4l2_subdev_state *sd_state,
1516                        struct v4l2_subdev_format *sdformat)
1517 {
1518         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1519         struct v4l2_fwnode_endpoint upstream_ep = { .bus_type = 0 };
1520         const struct imx_media_pixfmt *cc;
1521         struct v4l2_mbus_framefmt *fmt;
1522         struct v4l2_rect *crop, *compose;
1523         int ret;
1524
1525         if (sdformat->pad >= CSI_NUM_PADS)
1526                 return -EINVAL;
1527
1528         ret = csi_get_upstream_endpoint(priv, &upstream_ep);
1529         if (ret) {
1530                 v4l2_err(&priv->sd, "failed to find upstream endpoint\n");
1531                 return ret;
1532         }
1533
1534         mutex_lock(&priv->lock);
1535
1536         if (priv->stream_count > 0) {
1537                 ret = -EBUSY;
1538                 goto out;
1539         }
1540
1541         crop = __csi_get_crop(priv, sd_state, sdformat->which);
1542         compose = __csi_get_compose(priv, sd_state, sdformat->which);
1543
1544         csi_try_fmt(priv, &upstream_ep, sd_state, sdformat, crop, compose,
1545                     &cc);
1546
1547         fmt = __csi_get_fmt(priv, sd_state, sdformat->pad, sdformat->which);
1548         *fmt = sdformat->format;
1549
1550         if (sdformat->pad == CSI_SINK_PAD) {
1551                 int pad;
1552
1553                 /* propagate format to source pads */
1554                 for (pad = CSI_SINK_PAD + 1; pad < CSI_NUM_PADS; pad++) {
1555                         const struct imx_media_pixfmt *outcc;
1556                         struct v4l2_mbus_framefmt *outfmt;
1557                         struct v4l2_subdev_format format;
1558
1559                         format.pad = pad;
1560                         format.which = sdformat->which;
1561                         format.format = sdformat->format;
1562                         csi_try_fmt(priv, &upstream_ep, sd_state, &format,
1563                                     NULL, compose, &outcc);
1564
1565                         outfmt = __csi_get_fmt(priv, sd_state, pad,
1566                                                sdformat->which);
1567                         *outfmt = format.format;
1568
1569                         if (sdformat->which == V4L2_SUBDEV_FORMAT_ACTIVE)
1570                                 priv->cc[pad] = outcc;
1571                 }
1572         }
1573
1574         if (sdformat->which == V4L2_SUBDEV_FORMAT_ACTIVE)
1575                 priv->cc[sdformat->pad] = cc;
1576
1577 out:
1578         mutex_unlock(&priv->lock);
1579         return ret;
1580 }
1581
1582 static int csi_get_selection(struct v4l2_subdev *sd,
1583                              struct v4l2_subdev_state *sd_state,
1584                              struct v4l2_subdev_selection *sel)
1585 {
1586         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1587         struct v4l2_mbus_framefmt *infmt;
1588         struct v4l2_rect *crop, *compose;
1589         int ret = 0;
1590
1591         if (sel->pad != CSI_SINK_PAD)
1592                 return -EINVAL;
1593
1594         mutex_lock(&priv->lock);
1595
1596         infmt = __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, sel->which);
1597         crop = __csi_get_crop(priv, sd_state, sel->which);
1598         compose = __csi_get_compose(priv, sd_state, sel->which);
1599
1600         switch (sel->target) {
1601         case V4L2_SEL_TGT_CROP_BOUNDS:
1602                 sel->r.left = 0;
1603                 sel->r.top = 0;
1604                 sel->r.width = infmt->width;
1605                 sel->r.height = infmt->height;
1606                 if (infmt->field == V4L2_FIELD_ALTERNATE)
1607                         sel->r.height *= 2;
1608                 break;
1609         case V4L2_SEL_TGT_CROP:
1610                 sel->r = *crop;
1611                 break;
1612         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1613                 sel->r.left = 0;
1614                 sel->r.top = 0;
1615                 sel->r.width = crop->width;
1616                 sel->r.height = crop->height;
1617                 break;
1618         case V4L2_SEL_TGT_COMPOSE:
1619                 sel->r = *compose;
1620                 break;
1621         default:
1622                 ret = -EINVAL;
1623         }
1624
1625         mutex_unlock(&priv->lock);
1626         return ret;
1627 }
1628
1629 static int csi_set_scale(u32 *compose, u32 crop, u32 flags)
1630 {
1631         if ((flags & (V4L2_SEL_FLAG_LE | V4L2_SEL_FLAG_GE)) ==
1632                      (V4L2_SEL_FLAG_LE | V4L2_SEL_FLAG_GE) &&
1633             *compose != crop && *compose != crop / 2)
1634                 return -ERANGE;
1635
1636         if (*compose <= crop / 2 ||
1637             (*compose < crop * 3 / 4 && !(flags & V4L2_SEL_FLAG_GE)) ||
1638             (*compose < crop && (flags & V4L2_SEL_FLAG_LE)))
1639                 *compose = crop / 2;
1640         else
1641                 *compose = crop;
1642
1643         return 0;
1644 }
1645
1646 static int csi_set_selection(struct v4l2_subdev *sd,
1647                              struct v4l2_subdev_state *sd_state,
1648                              struct v4l2_subdev_selection *sel)
1649 {
1650         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1651         struct v4l2_fwnode_endpoint upstream_ep = { .bus_type = 0 };
1652         struct v4l2_mbus_framefmt *infmt;
1653         struct v4l2_rect *crop, *compose;
1654         int pad, ret;
1655
1656         if (sel->pad != CSI_SINK_PAD)
1657                 return -EINVAL;
1658
1659         ret = csi_get_upstream_endpoint(priv, &upstream_ep);
1660         if (ret) {
1661                 v4l2_err(&priv->sd, "failed to find upstream endpoint\n");
1662                 return ret;
1663         }
1664
1665         mutex_lock(&priv->lock);
1666
1667         if (priv->stream_count > 0) {
1668                 ret = -EBUSY;
1669                 goto out;
1670         }
1671
1672         infmt = __csi_get_fmt(priv, sd_state, CSI_SINK_PAD, sel->which);
1673         crop = __csi_get_crop(priv, sd_state, sel->which);
1674         compose = __csi_get_compose(priv, sd_state, sel->which);
1675
1676         switch (sel->target) {
1677         case V4L2_SEL_TGT_CROP:
1678                 /*
1679                  * Modifying the crop rectangle always changes the format on
1680                  * the source pads. If the KEEP_CONFIG flag is set, just return
1681                  * the current crop rectangle.
1682                  */
1683                 if (sel->flags & V4L2_SEL_FLAG_KEEP_CONFIG) {
1684                         sel->r = priv->crop;
1685                         if (sel->which == V4L2_SUBDEV_FORMAT_TRY)
1686                                 *crop = sel->r;
1687                         goto out;
1688                 }
1689
1690                 csi_try_crop(priv, &sel->r, sd_state, infmt, &upstream_ep);
1691
1692                 *crop = sel->r;
1693
1694                 /* Reset scaling to 1:1 */
1695                 compose->width = crop->width;
1696                 compose->height = crop->height;
1697                 break;
1698         case V4L2_SEL_TGT_COMPOSE:
1699                 /*
1700                  * Modifying the compose rectangle always changes the format on
1701                  * the source pads. If the KEEP_CONFIG flag is set, just return
1702                  * the current compose rectangle.
1703                  */
1704                 if (sel->flags & V4L2_SEL_FLAG_KEEP_CONFIG) {
1705                         sel->r = priv->compose;
1706                         if (sel->which == V4L2_SUBDEV_FORMAT_TRY)
1707                                 *compose = sel->r;
1708                         goto out;
1709                 }
1710
1711                 sel->r.left = 0;
1712                 sel->r.top = 0;
1713                 ret = csi_set_scale(&sel->r.width, crop->width, sel->flags);
1714                 if (ret)
1715                         goto out;
1716                 ret = csi_set_scale(&sel->r.height, crop->height, sel->flags);
1717                 if (ret)
1718                         goto out;
1719
1720                 *compose = sel->r;
1721                 break;
1722         default:
1723                 ret = -EINVAL;
1724                 goto out;
1725         }
1726
1727         /* Reset source pads to sink compose rectangle */
1728         for (pad = CSI_SINK_PAD + 1; pad < CSI_NUM_PADS; pad++) {
1729                 struct v4l2_mbus_framefmt *outfmt;
1730
1731                 outfmt = __csi_get_fmt(priv, sd_state, pad, sel->which);
1732                 outfmt->width = compose->width;
1733                 outfmt->height = compose->height;
1734         }
1735
1736 out:
1737         mutex_unlock(&priv->lock);
1738         return ret;
1739 }
1740
1741 static int csi_subscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh,
1742                                struct v4l2_event_subscription *sub)
1743 {
1744         if (sub->type != V4L2_EVENT_IMX_FRAME_INTERVAL_ERROR)
1745                 return -EINVAL;
1746         if (sub->id != 0)
1747                 return -EINVAL;
1748
1749         return v4l2_event_subscribe(fh, sub, 0, NULL);
1750 }
1751
1752 static int csi_unsubscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh,
1753                                  struct v4l2_event_subscription *sub)
1754 {
1755         return v4l2_event_unsubscribe(fh, sub);
1756 }
1757
1758 static int csi_registered(struct v4l2_subdev *sd)
1759 {
1760         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1761         struct ipu_csi *csi;
1762         int i, ret;
1763         u32 code;
1764
1765         /* get handle to IPU CSI */
1766         csi = ipu_csi_get(priv->ipu, priv->csi_id);
1767         if (IS_ERR(csi)) {
1768                 v4l2_err(&priv->sd, "failed to get CSI%d\n", priv->csi_id);
1769                 return PTR_ERR(csi);
1770         }
1771         priv->csi = csi;
1772
1773         for (i = 0; i < CSI_NUM_PADS; i++) {
1774                 code = 0;
1775                 if (i != CSI_SINK_PAD)
1776                         imx_media_enum_ipu_formats(&code, 0, PIXFMT_SEL_YUV);
1777
1778                 /* set a default mbus format  */
1779                 ret = imx_media_init_mbus_fmt(&priv->format_mbus[i],
1780                                               IMX_MEDIA_DEF_PIX_WIDTH,
1781                                               IMX_MEDIA_DEF_PIX_HEIGHT, code,
1782                                               V4L2_FIELD_NONE, &priv->cc[i]);
1783                 if (ret)
1784                         goto put_csi;
1785
1786                 /* init default frame interval */
1787                 priv->frame_interval[i].numerator = 1;
1788                 priv->frame_interval[i].denominator = 30;
1789         }
1790
1791         /* disable frame skipping */
1792         priv->skip = &csi_skip[0];
1793
1794         /* init default crop and compose rectangle sizes */
1795         priv->crop.width = IMX_MEDIA_DEF_PIX_WIDTH;
1796         priv->crop.height = IMX_MEDIA_DEF_PIX_HEIGHT;
1797         priv->compose.width = IMX_MEDIA_DEF_PIX_WIDTH;
1798         priv->compose.height = IMX_MEDIA_DEF_PIX_HEIGHT;
1799
1800         priv->fim = imx_media_fim_init(&priv->sd);
1801         if (IS_ERR(priv->fim)) {
1802                 ret = PTR_ERR(priv->fim);
1803                 goto put_csi;
1804         }
1805
1806         priv->vdev = imx_media_capture_device_init(priv->sd.dev, &priv->sd,
1807                                                    CSI_SRC_PAD_IDMAC, true);
1808         if (IS_ERR(priv->vdev)) {
1809                 ret = PTR_ERR(priv->vdev);
1810                 goto free_fim;
1811         }
1812
1813         ret = imx_media_capture_device_register(priv->vdev, 0);
1814         if (ret)
1815                 goto remove_vdev;
1816
1817         return 0;
1818
1819 remove_vdev:
1820         imx_media_capture_device_remove(priv->vdev);
1821 free_fim:
1822         if (priv->fim)
1823                 imx_media_fim_free(priv->fim);
1824 put_csi:
1825         ipu_csi_put(priv->csi);
1826         return ret;
1827 }
1828
1829 static void csi_unregistered(struct v4l2_subdev *sd)
1830 {
1831         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1832
1833         imx_media_capture_device_unregister(priv->vdev);
1834         imx_media_capture_device_remove(priv->vdev);
1835
1836         if (priv->fim)
1837                 imx_media_fim_free(priv->fim);
1838
1839         if (priv->csi)
1840                 ipu_csi_put(priv->csi);
1841 }
1842
1843 /*
1844  * The CSI has only one fwnode endpoint, at the sink pad. Verify the
1845  * endpoint belongs to us, and return CSI_SINK_PAD.
1846  */
1847 static int csi_get_fwnode_pad(struct media_entity *entity,
1848                               struct fwnode_endpoint *endpoint)
1849 {
1850         struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
1851         struct csi_priv *priv = v4l2_get_subdevdata(sd);
1852         struct fwnode_handle *csi_port = dev_fwnode(priv->dev);
1853         struct fwnode_handle *csi_ep;
1854         int ret;
1855
1856         csi_ep = fwnode_get_next_child_node(csi_port, NULL);
1857
1858         ret = endpoint->local_fwnode == csi_ep ? CSI_SINK_PAD : -ENXIO;
1859
1860         fwnode_handle_put(csi_ep);
1861
1862         return ret;
1863 }
1864
1865 static const struct media_entity_operations csi_entity_ops = {
1866         .link_setup = csi_link_setup,
1867         .link_validate = v4l2_subdev_link_validate,
1868         .get_fwnode_pad = csi_get_fwnode_pad,
1869 };
1870
1871 static const struct v4l2_subdev_core_ops csi_core_ops = {
1872         .subscribe_event = csi_subscribe_event,
1873         .unsubscribe_event = csi_unsubscribe_event,
1874 };
1875
1876 static const struct v4l2_subdev_video_ops csi_video_ops = {
1877         .g_frame_interval = csi_g_frame_interval,
1878         .s_frame_interval = csi_s_frame_interval,
1879         .s_stream = csi_s_stream,
1880 };
1881
1882 static const struct v4l2_subdev_pad_ops csi_pad_ops = {
1883         .init_cfg = imx_media_init_cfg,
1884         .enum_mbus_code = csi_enum_mbus_code,
1885         .enum_frame_size = csi_enum_frame_size,
1886         .enum_frame_interval = csi_enum_frame_interval,
1887         .get_fmt = csi_get_fmt,
1888         .set_fmt = csi_set_fmt,
1889         .get_selection = csi_get_selection,
1890         .set_selection = csi_set_selection,
1891         .link_validate = csi_link_validate,
1892 };
1893
1894 static const struct v4l2_subdev_ops csi_subdev_ops = {
1895         .core = &csi_core_ops,
1896         .video = &csi_video_ops,
1897         .pad = &csi_pad_ops,
1898 };
1899
1900 static const struct v4l2_subdev_internal_ops csi_internal_ops = {
1901         .registered = csi_registered,
1902         .unregistered = csi_unregistered,
1903 };
1904
1905 static int imx_csi_notify_bound(struct v4l2_async_notifier *notifier,
1906                                 struct v4l2_subdev *sd,
1907                                 struct v4l2_async_subdev *asd)
1908 {
1909         struct csi_priv *priv = notifier_to_dev(notifier);
1910         struct media_pad *sink = &priv->sd.entity.pads[CSI_SINK_PAD];
1911
1912         /*
1913          * If the subdev is a video mux, it must be one of the CSI
1914          * muxes. Mark it as such via its group id.
1915          */
1916         if (sd->entity.function == MEDIA_ENT_F_VID_MUX)
1917                 sd->grp_id = IMX_MEDIA_GRP_ID_CSI_MUX;
1918
1919         return v4l2_create_fwnode_links_to_pad(sd, sink, 0);
1920 }
1921
1922 static const struct v4l2_async_notifier_operations csi_notify_ops = {
1923         .bound = imx_csi_notify_bound,
1924 };
1925
1926 static int imx_csi_async_register(struct csi_priv *priv)
1927 {
1928         struct v4l2_async_subdev *asd = NULL;
1929         struct fwnode_handle *ep;
1930         unsigned int port;
1931         int ret;
1932
1933         v4l2_async_nf_init(&priv->notifier);
1934
1935         /* get this CSI's port id */
1936         ret = fwnode_property_read_u32(dev_fwnode(priv->dev), "reg", &port);
1937         if (ret < 0)
1938                 return ret;
1939
1940         ep = fwnode_graph_get_endpoint_by_id(dev_fwnode(priv->dev->parent),
1941                                              port, 0,
1942                                              FWNODE_GRAPH_ENDPOINT_NEXT);
1943         if (ep) {
1944                 asd = v4l2_async_nf_add_fwnode_remote(&priv->notifier, ep,
1945                                                       struct v4l2_async_subdev);
1946
1947                 fwnode_handle_put(ep);
1948
1949                 if (IS_ERR(asd)) {
1950                         ret = PTR_ERR(asd);
1951                         /* OK if asd already exists */
1952                         if (ret != -EEXIST)
1953                                 return ret;
1954                 }
1955         }
1956
1957         priv->notifier.ops = &csi_notify_ops;
1958
1959         ret = v4l2_async_subdev_nf_register(&priv->sd, &priv->notifier);
1960         if (ret)
1961                 return ret;
1962
1963         return v4l2_async_register_subdev(&priv->sd);
1964 }
1965
1966 static int imx_csi_probe(struct platform_device *pdev)
1967 {
1968         struct ipu_client_platformdata *pdata;
1969         struct pinctrl *pinctrl;
1970         struct csi_priv *priv;
1971         int i, ret;
1972
1973         priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
1974         if (!priv)
1975                 return -ENOMEM;
1976
1977         platform_set_drvdata(pdev, &priv->sd);
1978         priv->dev = &pdev->dev;
1979
1980         ret = dma_set_coherent_mask(priv->dev, DMA_BIT_MASK(32));
1981         if (ret)
1982                 return ret;
1983
1984         /* get parent IPU */
1985         priv->ipu = dev_get_drvdata(priv->dev->parent);
1986
1987         /* get our CSI id */
1988         pdata = priv->dev->platform_data;
1989         priv->csi_id = pdata->csi;
1990         priv->smfc_id = (priv->csi_id == 0) ? 0 : 2;
1991
1992         priv->active_output_pad = CSI_SRC_PAD_IDMAC;
1993
1994         timer_setup(&priv->eof_timeout_timer, csi_idmac_eof_timeout, 0);
1995         spin_lock_init(&priv->irqlock);
1996
1997         v4l2_subdev_init(&priv->sd, &csi_subdev_ops);
1998         v4l2_set_subdevdata(&priv->sd, priv);
1999         priv->sd.internal_ops = &csi_internal_ops;
2000         priv->sd.entity.ops = &csi_entity_ops;
2001         priv->sd.entity.function = MEDIA_ENT_F_PROC_VIDEO_PIXEL_FORMATTER;
2002         priv->sd.dev = &pdev->dev;
2003         priv->sd.fwnode = of_fwnode_handle(pdata->of_node);
2004         priv->sd.owner = THIS_MODULE;
2005         priv->sd.flags = V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS;
2006         priv->sd.grp_id = priv->csi_id ?
2007                 IMX_MEDIA_GRP_ID_IPU_CSI1 : IMX_MEDIA_GRP_ID_IPU_CSI0;
2008         imx_media_grp_id_to_sd_name(priv->sd.name, sizeof(priv->sd.name),
2009                                     priv->sd.grp_id, ipu_get_num(priv->ipu));
2010
2011         for (i = 0; i < CSI_NUM_PADS; i++)
2012                 priv->pad[i].flags = (i == CSI_SINK_PAD) ?
2013                         MEDIA_PAD_FL_SINK : MEDIA_PAD_FL_SOURCE;
2014
2015         ret = media_entity_pads_init(&priv->sd.entity, CSI_NUM_PADS,
2016                                      priv->pad);
2017         if (ret)
2018                 return ret;
2019
2020         mutex_init(&priv->lock);
2021
2022         v4l2_ctrl_handler_init(&priv->ctrl_hdlr, 0);
2023         priv->sd.ctrl_handler = &priv->ctrl_hdlr;
2024
2025         /*
2026          * The IPUv3 driver did not assign an of_node to this
2027          * device. As a result, pinctrl does not automatically
2028          * configure our pin groups, so we need to do that manually
2029          * here, after setting this device's of_node.
2030          */
2031         priv->dev->of_node = pdata->of_node;
2032         pinctrl = devm_pinctrl_get_select_default(priv->dev);
2033         if (IS_ERR(pinctrl)) {
2034                 ret = PTR_ERR(pinctrl);
2035                 dev_dbg(priv->dev,
2036                         "devm_pinctrl_get_select_default() failed: %d\n", ret);
2037                 if (ret != -ENODEV)
2038                         goto free;
2039         }
2040
2041         ret = imx_csi_async_register(priv);
2042         if (ret)
2043                 goto cleanup;
2044
2045         return 0;
2046
2047 cleanup:
2048         v4l2_async_nf_unregister(&priv->notifier);
2049         v4l2_async_nf_cleanup(&priv->notifier);
2050 free:
2051         v4l2_ctrl_handler_free(&priv->ctrl_hdlr);
2052         mutex_destroy(&priv->lock);
2053         return ret;
2054 }
2055
2056 static int imx_csi_remove(struct platform_device *pdev)
2057 {
2058         struct v4l2_subdev *sd = platform_get_drvdata(pdev);
2059         struct csi_priv *priv = sd_to_dev(sd);
2060
2061         v4l2_ctrl_handler_free(&priv->ctrl_hdlr);
2062         mutex_destroy(&priv->lock);
2063         v4l2_async_nf_unregister(&priv->notifier);
2064         v4l2_async_nf_cleanup(&priv->notifier);
2065         v4l2_async_unregister_subdev(sd);
2066         media_entity_cleanup(&sd->entity);
2067
2068         return 0;
2069 }
2070
2071 static const struct platform_device_id imx_csi_ids[] = {
2072         { .name = "imx-ipuv3-csi" },
2073         { },
2074 };
2075 MODULE_DEVICE_TABLE(platform, imx_csi_ids);
2076
2077 static struct platform_driver imx_csi_driver = {
2078         .probe = imx_csi_probe,
2079         .remove = imx_csi_remove,
2080         .id_table = imx_csi_ids,
2081         .driver = {
2082                 .name = "imx-ipuv3-csi",
2083         },
2084 };
2085 module_platform_driver(imx_csi_driver);
2086
2087 MODULE_DESCRIPTION("i.MX CSI subdev driver");
2088 MODULE_AUTHOR("Steve Longerbeam <steve_longerbeam@mentor.com>");
2089 MODULE_LICENSE("GPL");