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