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