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