Merge tag 'for-5.2-rc4-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave...
[linux-2.6-block.git] / drivers / media / platform / ti-vpe / cal.c
1 /*
2  * TI CAL camera interface driver
3  *
4  * Copyright (c) 2015 Texas Instruments Inc.
5  * Benoit Parrot, <bparrot@ti.com>
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License version 2 as published by
9  * the Free Software Foundation
10  */
11
12 #include <linux/interrupt.h>
13 #include <linux/io.h>
14 #include <linux/ioctl.h>
15 #include <linux/module.h>
16 #include <linux/platform_device.h>
17 #include <linux/delay.h>
18 #include <linux/pm_runtime.h>
19 #include <linux/slab.h>
20 #include <linux/videodev2.h>
21 #include <linux/of_device.h>
22 #include <linux/of_graph.h>
23
24 #include <media/v4l2-fwnode.h>
25 #include <media/v4l2-async.h>
26 #include <media/v4l2-common.h>
27 #include <media/v4l2-ctrls.h>
28 #include <media/v4l2-device.h>
29 #include <media/v4l2-event.h>
30 #include <media/v4l2-ioctl.h>
31 #include <media/v4l2-fh.h>
32 #include <media/videobuf2-core.h>
33 #include <media/videobuf2-dma-contig.h>
34 #include "cal_regs.h"
35
36 #define CAL_MODULE_NAME "cal"
37
38 #define MAX_WIDTH 1920
39 #define MAX_HEIGHT 1200
40
41 #define CAL_VERSION "0.1.0"
42
43 MODULE_DESCRIPTION("TI CAL driver");
44 MODULE_AUTHOR("Benoit Parrot, <bparrot@ti.com>");
45 MODULE_LICENSE("GPL v2");
46 MODULE_VERSION(CAL_VERSION);
47
48 static unsigned video_nr = -1;
49 module_param(video_nr, uint, 0644);
50 MODULE_PARM_DESC(video_nr, "videoX start number, -1 is autodetect");
51
52 static unsigned debug;
53 module_param(debug, uint, 0644);
54 MODULE_PARM_DESC(debug, "activates debug info");
55
56 /* timeperframe: min/max and default */
57 static const struct v4l2_fract
58         tpf_default = {.numerator = 1001,       .denominator = 30000};
59
60 #define cal_dbg(level, caldev, fmt, arg...)     \
61                 v4l2_dbg(level, debug, &caldev->v4l2_dev, fmt, ##arg)
62 #define cal_info(caldev, fmt, arg...)   \
63                 v4l2_info(&caldev->v4l2_dev, fmt, ##arg)
64 #define cal_err(caldev, fmt, arg...)    \
65                 v4l2_err(&caldev->v4l2_dev, fmt, ##arg)
66
67 #define ctx_dbg(level, ctx, fmt, arg...)        \
68                 v4l2_dbg(level, debug, &ctx->v4l2_dev, fmt, ##arg)
69 #define ctx_info(ctx, fmt, arg...)      \
70                 v4l2_info(&ctx->v4l2_dev, fmt, ##arg)
71 #define ctx_err(ctx, fmt, arg...)       \
72                 v4l2_err(&ctx->v4l2_dev, fmt, ##arg)
73
74 #define CAL_NUM_INPUT 1
75 #define CAL_NUM_CONTEXT 2
76
77 #define bytes_per_line(pixel, bpp) (ALIGN(pixel * bpp, 16))
78
79 #define reg_read(dev, offset) ioread32(dev->base + offset)
80 #define reg_write(dev, offset, val) iowrite32(val, dev->base + offset)
81
82 #define reg_read_field(dev, offset, mask) get_field(reg_read(dev, offset), \
83                                                     mask)
84 #define reg_write_field(dev, offset, field, mask) { \
85         u32 val = reg_read(dev, offset); \
86         set_field(&val, field, mask); \
87         reg_write(dev, offset, val); }
88
89 /* ------------------------------------------------------------------
90  *      Basic structures
91  * ------------------------------------------------------------------
92  */
93
94 struct cal_fmt {
95         u32     fourcc;
96         u32     code;
97         u8      depth;
98 };
99
100 static struct cal_fmt cal_formats[] = {
101         {
102                 .fourcc         = V4L2_PIX_FMT_YUYV,
103                 .code           = MEDIA_BUS_FMT_YUYV8_2X8,
104                 .depth          = 16,
105         }, {
106                 .fourcc         = V4L2_PIX_FMT_UYVY,
107                 .code           = MEDIA_BUS_FMT_UYVY8_2X8,
108                 .depth          = 16,
109         }, {
110                 .fourcc         = V4L2_PIX_FMT_YVYU,
111                 .code           = MEDIA_BUS_FMT_YVYU8_2X8,
112                 .depth          = 16,
113         }, {
114                 .fourcc         = V4L2_PIX_FMT_VYUY,
115                 .code           = MEDIA_BUS_FMT_VYUY8_2X8,
116                 .depth          = 16,
117         }, {
118                 .fourcc         = V4L2_PIX_FMT_RGB565, /* gggbbbbb rrrrrggg */
119                 .code           = MEDIA_BUS_FMT_RGB565_2X8_LE,
120                 .depth          = 16,
121         }, {
122                 .fourcc         = V4L2_PIX_FMT_RGB565X, /* rrrrrggg gggbbbbb */
123                 .code           = MEDIA_BUS_FMT_RGB565_2X8_BE,
124                 .depth          = 16,
125         }, {
126                 .fourcc         = V4L2_PIX_FMT_RGB555, /* gggbbbbb arrrrrgg */
127                 .code           = MEDIA_BUS_FMT_RGB555_2X8_PADHI_LE,
128                 .depth          = 16,
129         }, {
130                 .fourcc         = V4L2_PIX_FMT_RGB555X, /* arrrrrgg gggbbbbb */
131                 .code           = MEDIA_BUS_FMT_RGB555_2X8_PADHI_BE,
132                 .depth          = 16,
133         }, {
134                 .fourcc         = V4L2_PIX_FMT_RGB24, /* rgb */
135                 .code           = MEDIA_BUS_FMT_RGB888_2X12_LE,
136                 .depth          = 24,
137         }, {
138                 .fourcc         = V4L2_PIX_FMT_BGR24, /* bgr */
139                 .code           = MEDIA_BUS_FMT_RGB888_2X12_BE,
140                 .depth          = 24,
141         }, {
142                 .fourcc         = V4L2_PIX_FMT_RGB32, /* argb */
143                 .code           = MEDIA_BUS_FMT_ARGB8888_1X32,
144                 .depth          = 32,
145         }, {
146                 .fourcc         = V4L2_PIX_FMT_SBGGR8,
147                 .code           = MEDIA_BUS_FMT_SBGGR8_1X8,
148                 .depth          = 8,
149         }, {
150                 .fourcc         = V4L2_PIX_FMT_SGBRG8,
151                 .code           = MEDIA_BUS_FMT_SGBRG8_1X8,
152                 .depth          = 8,
153         }, {
154                 .fourcc         = V4L2_PIX_FMT_SGRBG8,
155                 .code           = MEDIA_BUS_FMT_SGRBG8_1X8,
156                 .depth          = 8,
157         }, {
158                 .fourcc         = V4L2_PIX_FMT_SRGGB8,
159                 .code           = MEDIA_BUS_FMT_SRGGB8_1X8,
160                 .depth          = 8,
161         }, {
162                 .fourcc         = V4L2_PIX_FMT_SBGGR10,
163                 .code           = MEDIA_BUS_FMT_SBGGR10_1X10,
164                 .depth          = 16,
165         }, {
166                 .fourcc         = V4L2_PIX_FMT_SGBRG10,
167                 .code           = MEDIA_BUS_FMT_SGBRG10_1X10,
168                 .depth          = 16,
169         }, {
170                 .fourcc         = V4L2_PIX_FMT_SGRBG10,
171                 .code           = MEDIA_BUS_FMT_SGRBG10_1X10,
172                 .depth          = 16,
173         }, {
174                 .fourcc         = V4L2_PIX_FMT_SRGGB10,
175                 .code           = MEDIA_BUS_FMT_SRGGB10_1X10,
176                 .depth          = 16,
177         }, {
178                 .fourcc         = V4L2_PIX_FMT_SBGGR12,
179                 .code           = MEDIA_BUS_FMT_SBGGR12_1X12,
180                 .depth          = 16,
181         }, {
182                 .fourcc         = V4L2_PIX_FMT_SGBRG12,
183                 .code           = MEDIA_BUS_FMT_SGBRG12_1X12,
184                 .depth          = 16,
185         }, {
186                 .fourcc         = V4L2_PIX_FMT_SGRBG12,
187                 .code           = MEDIA_BUS_FMT_SGRBG12_1X12,
188                 .depth          = 16,
189         }, {
190                 .fourcc         = V4L2_PIX_FMT_SRGGB12,
191                 .code           = MEDIA_BUS_FMT_SRGGB12_1X12,
192                 .depth          = 16,
193         },
194 };
195
196 /*  Print Four-character-code (FOURCC) */
197 static char *fourcc_to_str(u32 fmt)
198 {
199         static char code[5];
200
201         code[0] = (unsigned char)(fmt & 0xff);
202         code[1] = (unsigned char)((fmt >> 8) & 0xff);
203         code[2] = (unsigned char)((fmt >> 16) & 0xff);
204         code[3] = (unsigned char)((fmt >> 24) & 0xff);
205         code[4] = '\0';
206
207         return code;
208 }
209
210 /* buffer for one video frame */
211 struct cal_buffer {
212         /* common v4l buffer stuff -- must be first */
213         struct vb2_v4l2_buffer  vb;
214         struct list_head        list;
215         const struct cal_fmt    *fmt;
216 };
217
218 struct cal_dmaqueue {
219         struct list_head        active;
220
221         /* Counters to control fps rate */
222         int                     frame;
223         int                     ini_jiffies;
224 };
225
226 struct cm_data {
227         void __iomem            *base;
228         struct resource         *res;
229
230         unsigned int            camerrx_control;
231
232         struct platform_device *pdev;
233 };
234
235 struct cc_data {
236         void __iomem            *base;
237         struct resource         *res;
238
239         struct platform_device *pdev;
240 };
241
242 /*
243  * there is one cal_dev structure in the driver, it is shared by
244  * all instances.
245  */
246 struct cal_dev {
247         int                     irq;
248         void __iomem            *base;
249         struct resource         *res;
250         struct platform_device  *pdev;
251         struct v4l2_device      v4l2_dev;
252
253         /* Control Module handle */
254         struct cm_data          *cm;
255         /* Camera Core Module handle */
256         struct cc_data          *cc[CAL_NUM_CSI2_PORTS];
257
258         struct cal_ctx          *ctx[CAL_NUM_CONTEXT];
259 };
260
261 /*
262  * There is one cal_ctx structure for each camera core context.
263  */
264 struct cal_ctx {
265         struct v4l2_device      v4l2_dev;
266         struct v4l2_ctrl_handler ctrl_handler;
267         struct video_device     vdev;
268         struct v4l2_async_notifier notifier;
269         struct v4l2_subdev      *sensor;
270         struct v4l2_fwnode_endpoint     endpoint;
271
272         struct v4l2_async_subdev asd;
273
274         struct v4l2_fh          fh;
275         struct cal_dev          *dev;
276         struct cc_data          *cc;
277
278         /* v4l2_ioctl mutex */
279         struct mutex            mutex;
280         /* v4l2 buffers lock */
281         spinlock_t              slock;
282
283         /* Several counters */
284         unsigned long           jiffies;
285
286         struct cal_dmaqueue     vidq;
287
288         /* Input Number */
289         int                     input;
290
291         /* video capture */
292         const struct cal_fmt    *fmt;
293         /* Used to store current pixel format */
294         struct v4l2_format              v_fmt;
295         /* Used to store current mbus frame format */
296         struct v4l2_mbus_framefmt       m_fmt;
297
298         /* Current subdev enumerated format */
299         struct cal_fmt          *active_fmt[ARRAY_SIZE(cal_formats)];
300         int                     num_active_fmt;
301
302         struct v4l2_fract       timeperframe;
303         unsigned int            sequence;
304         unsigned int            external_rate;
305         struct vb2_queue        vb_vidq;
306         unsigned int            seq_count;
307         unsigned int            csi2_port;
308         unsigned int            virtual_channel;
309
310         /* Pointer pointing to current v4l2_buffer */
311         struct cal_buffer       *cur_frm;
312         /* Pointer pointing to next v4l2_buffer */
313         struct cal_buffer       *next_frm;
314 };
315
316 static const struct cal_fmt *find_format_by_pix(struct cal_ctx *ctx,
317                                                 u32 pixelformat)
318 {
319         const struct cal_fmt *fmt;
320         unsigned int k;
321
322         for (k = 0; k < ctx->num_active_fmt; k++) {
323                 fmt = ctx->active_fmt[k];
324                 if (fmt->fourcc == pixelformat)
325                         return fmt;
326         }
327
328         return NULL;
329 }
330
331 static const struct cal_fmt *find_format_by_code(struct cal_ctx *ctx,
332                                                  u32 code)
333 {
334         const struct cal_fmt *fmt;
335         unsigned int k;
336
337         for (k = 0; k < ctx->num_active_fmt; k++) {
338                 fmt = ctx->active_fmt[k];
339                 if (fmt->code == code)
340                         return fmt;
341         }
342
343         return NULL;
344 }
345
346 static inline struct cal_ctx *notifier_to_ctx(struct v4l2_async_notifier *n)
347 {
348         return container_of(n, struct cal_ctx, notifier);
349 }
350
351 static inline int get_field(u32 value, u32 mask)
352 {
353         return (value & mask) >> __ffs(mask);
354 }
355
356 static inline void set_field(u32 *valp, u32 field, u32 mask)
357 {
358         u32 val = *valp;
359
360         val &= ~mask;
361         val |= (field << __ffs(mask)) & mask;
362         *valp = val;
363 }
364
365 /*
366  * Control Module block access
367  */
368 static struct cm_data *cm_create(struct cal_dev *dev)
369 {
370         struct platform_device *pdev = dev->pdev;
371         struct cm_data *cm;
372
373         cm = devm_kzalloc(&pdev->dev, sizeof(*cm), GFP_KERNEL);
374         if (!cm)
375                 return ERR_PTR(-ENOMEM);
376
377         cm->res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
378                                                 "camerrx_control");
379         cm->base = devm_ioremap_resource(&pdev->dev, cm->res);
380         if (IS_ERR(cm->base)) {
381                 cal_err(dev, "failed to ioremap\n");
382                 return ERR_CAST(cm->base);
383         }
384
385         cal_dbg(1, dev, "ioresource %s at %pa - %pa\n",
386                 cm->res->name, &cm->res->start, &cm->res->end);
387
388         return cm;
389 }
390
391 static void camerarx_phy_enable(struct cal_ctx *ctx)
392 {
393         u32 val;
394
395         if (!ctx->dev->cm->base) {
396                 ctx_err(ctx, "cm not mapped\n");
397                 return;
398         }
399
400         val = reg_read(ctx->dev->cm, CM_CTRL_CORE_CAMERRX_CONTROL);
401         if (ctx->csi2_port == 1) {
402                 set_field(&val, 1, CM_CAMERRX_CTRL_CSI0_CTRLCLKEN_MASK);
403                 set_field(&val, 0, CM_CAMERRX_CTRL_CSI0_CAMMODE_MASK);
404                 /* enable all lanes by default */
405                 set_field(&val, 0xf, CM_CAMERRX_CTRL_CSI0_LANEENABLE_MASK);
406                 set_field(&val, 1, CM_CAMERRX_CTRL_CSI0_MODE_MASK);
407         } else if (ctx->csi2_port == 2) {
408                 set_field(&val, 1, CM_CAMERRX_CTRL_CSI1_CTRLCLKEN_MASK);
409                 set_field(&val, 0, CM_CAMERRX_CTRL_CSI1_CAMMODE_MASK);
410                 /* enable all lanes by default */
411                 set_field(&val, 0x3, CM_CAMERRX_CTRL_CSI1_LANEENABLE_MASK);
412                 set_field(&val, 1, CM_CAMERRX_CTRL_CSI1_MODE_MASK);
413         }
414         reg_write(ctx->dev->cm, CM_CTRL_CORE_CAMERRX_CONTROL, val);
415 }
416
417 static void camerarx_phy_disable(struct cal_ctx *ctx)
418 {
419         u32 val;
420
421         if (!ctx->dev->cm->base) {
422                 ctx_err(ctx, "cm not mapped\n");
423                 return;
424         }
425
426         val = reg_read(ctx->dev->cm, CM_CTRL_CORE_CAMERRX_CONTROL);
427         if (ctx->csi2_port == 1)
428                 set_field(&val, 0x0, CM_CAMERRX_CTRL_CSI0_CTRLCLKEN_MASK);
429         else if (ctx->csi2_port == 2)
430                 set_field(&val, 0x0, CM_CAMERRX_CTRL_CSI1_CTRLCLKEN_MASK);
431         reg_write(ctx->dev->cm, CM_CTRL_CORE_CAMERRX_CONTROL, val);
432 }
433
434 /*
435  * Camera Instance access block
436  */
437 static struct cc_data *cc_create(struct cal_dev *dev, unsigned int core)
438 {
439         struct platform_device *pdev = dev->pdev;
440         struct cc_data *cc;
441
442         cc = devm_kzalloc(&pdev->dev, sizeof(*cc), GFP_KERNEL);
443         if (!cc)
444                 return ERR_PTR(-ENOMEM);
445
446         cc->res = platform_get_resource_byname(pdev,
447                                                IORESOURCE_MEM,
448                                                (core == 0) ?
449                                                 "cal_rx_core0" :
450                                                 "cal_rx_core1");
451         cc->base = devm_ioremap_resource(&pdev->dev, cc->res);
452         if (IS_ERR(cc->base)) {
453                 cal_err(dev, "failed to ioremap\n");
454                 return ERR_CAST(cc->base);
455         }
456
457         cal_dbg(1, dev, "ioresource %s at %pa - %pa\n",
458                 cc->res->name, &cc->res->start, &cc->res->end);
459
460         return cc;
461 }
462
463 /*
464  * Get Revision and HW info
465  */
466 static void cal_get_hwinfo(struct cal_dev *dev)
467 {
468         u32 revision = 0;
469         u32 hwinfo = 0;
470
471         revision = reg_read(dev, CAL_HL_REVISION);
472         cal_dbg(3, dev, "CAL_HL_REVISION = 0x%08x (expecting 0x40000200)\n",
473                 revision);
474
475         hwinfo = reg_read(dev, CAL_HL_HWINFO);
476         cal_dbg(3, dev, "CAL_HL_HWINFO = 0x%08x (expecting 0xA3C90469)\n",
477                 hwinfo);
478 }
479
480 static inline int cal_runtime_get(struct cal_dev *dev)
481 {
482         return pm_runtime_get_sync(&dev->pdev->dev);
483 }
484
485 static inline void cal_runtime_put(struct cal_dev *dev)
486 {
487         pm_runtime_put_sync(&dev->pdev->dev);
488 }
489
490 static void cal_quickdump_regs(struct cal_dev *dev)
491 {
492         cal_info(dev, "CAL Registers @ 0x%pa:\n", &dev->res->start);
493         print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET, 16, 4,
494                        (__force const void *)dev->base,
495                        resource_size(dev->res), false);
496
497         if (dev->ctx[0]) {
498                 cal_info(dev, "CSI2 Core 0 Registers @ %pa:\n",
499                          &dev->ctx[0]->cc->res->start);
500                 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET, 16, 4,
501                                (__force const void *)dev->ctx[0]->cc->base,
502                                resource_size(dev->ctx[0]->cc->res),
503                                false);
504         }
505
506         if (dev->ctx[1]) {
507                 cal_info(dev, "CSI2 Core 1 Registers @ %pa:\n",
508                          &dev->ctx[1]->cc->res->start);
509                 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET, 16, 4,
510                                (__force const void *)dev->ctx[1]->cc->base,
511                                resource_size(dev->ctx[1]->cc->res),
512                                false);
513         }
514
515         cal_info(dev, "CAMERRX_Control Registers @ %pa:\n",
516                  &dev->cm->res->start);
517         print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET, 16, 4,
518                        (__force const void *)dev->cm->base,
519                        resource_size(dev->cm->res), false);
520 }
521
522 /*
523  * Enable the expected IRQ sources
524  */
525 static void enable_irqs(struct cal_ctx *ctx)
526 {
527         /* Enable IRQ_WDMA_END 0/1 */
528         reg_write_field(ctx->dev,
529                         CAL_HL_IRQENABLE_SET(2),
530                         CAL_HL_IRQ_ENABLE,
531                         CAL_HL_IRQ_MASK(ctx->csi2_port));
532         /* Enable IRQ_WDMA_START 0/1 */
533         reg_write_field(ctx->dev,
534                         CAL_HL_IRQENABLE_SET(3),
535                         CAL_HL_IRQ_ENABLE,
536                         CAL_HL_IRQ_MASK(ctx->csi2_port));
537         /* Todo: Add VC_IRQ and CSI2_COMPLEXIO_IRQ handling */
538         reg_write(ctx->dev, CAL_CSI2_VC_IRQENABLE(1), 0xFF000000);
539 }
540
541 static void disable_irqs(struct cal_ctx *ctx)
542 {
543         /* Disable IRQ_WDMA_END 0/1 */
544         reg_write_field(ctx->dev,
545                         CAL_HL_IRQENABLE_CLR(2),
546                         CAL_HL_IRQ_CLEAR,
547                         CAL_HL_IRQ_MASK(ctx->csi2_port));
548         /* Disable IRQ_WDMA_START 0/1 */
549         reg_write_field(ctx->dev,
550                         CAL_HL_IRQENABLE_CLR(3),
551                         CAL_HL_IRQ_CLEAR,
552                         CAL_HL_IRQ_MASK(ctx->csi2_port));
553         /* Todo: Add VC_IRQ and CSI2_COMPLEXIO_IRQ handling */
554         reg_write(ctx->dev, CAL_CSI2_VC_IRQENABLE(1), 0);
555 }
556
557 static void csi2_init(struct cal_ctx *ctx)
558 {
559         int i;
560         u32 val;
561
562         val = reg_read(ctx->dev, CAL_CSI2_TIMING(ctx->csi2_port));
563         set_field(&val, CAL_GEN_ENABLE,
564                   CAL_CSI2_TIMING_FORCE_RX_MODE_IO1_MASK);
565         set_field(&val, CAL_GEN_ENABLE,
566                   CAL_CSI2_TIMING_STOP_STATE_X16_IO1_MASK);
567         set_field(&val, CAL_GEN_DISABLE,
568                   CAL_CSI2_TIMING_STOP_STATE_X4_IO1_MASK);
569         set_field(&val, 407, CAL_CSI2_TIMING_STOP_STATE_COUNTER_IO1_MASK);
570         reg_write(ctx->dev, CAL_CSI2_TIMING(ctx->csi2_port), val);
571         ctx_dbg(3, ctx, "CAL_CSI2_TIMING(%d) = 0x%08x\n", ctx->csi2_port,
572                 reg_read(ctx->dev, CAL_CSI2_TIMING(ctx->csi2_port)));
573
574         val = reg_read(ctx->dev, CAL_CSI2_COMPLEXIO_CFG(ctx->csi2_port));
575         set_field(&val, CAL_CSI2_COMPLEXIO_CFG_RESET_CTRL_OPERATIONAL,
576                   CAL_CSI2_COMPLEXIO_CFG_RESET_CTRL_MASK);
577         set_field(&val, CAL_CSI2_COMPLEXIO_CFG_PWR_CMD_STATE_ON,
578                   CAL_CSI2_COMPLEXIO_CFG_PWR_CMD_MASK);
579         reg_write(ctx->dev, CAL_CSI2_COMPLEXIO_CFG(ctx->csi2_port), val);
580         for (i = 0; i < 10; i++) {
581                 if (reg_read_field(ctx->dev,
582                                    CAL_CSI2_COMPLEXIO_CFG(ctx->csi2_port),
583                                    CAL_CSI2_COMPLEXIO_CFG_PWR_STATUS_MASK) ==
584                     CAL_CSI2_COMPLEXIO_CFG_PWR_STATUS_STATE_ON)
585                         break;
586                 usleep_range(1000, 1100);
587         }
588         ctx_dbg(3, ctx, "CAL_CSI2_COMPLEXIO_CFG(%d) = 0x%08x\n", ctx->csi2_port,
589                 reg_read(ctx->dev, CAL_CSI2_COMPLEXIO_CFG(ctx->csi2_port)));
590
591         val = reg_read(ctx->dev, CAL_CTRL);
592         set_field(&val, CAL_CTRL_BURSTSIZE_BURST128, CAL_CTRL_BURSTSIZE_MASK);
593         set_field(&val, 0xF, CAL_CTRL_TAGCNT_MASK);
594         set_field(&val, CAL_CTRL_POSTED_WRITES_NONPOSTED,
595                   CAL_CTRL_POSTED_WRITES_MASK);
596         set_field(&val, 0xFF, CAL_CTRL_MFLAGL_MASK);
597         set_field(&val, 0xFF, CAL_CTRL_MFLAGH_MASK);
598         reg_write(ctx->dev, CAL_CTRL, val);
599         ctx_dbg(3, ctx, "CAL_CTRL = 0x%08x\n", reg_read(ctx->dev, CAL_CTRL));
600 }
601
602 static void csi2_lane_config(struct cal_ctx *ctx)
603 {
604         u32 val = reg_read(ctx->dev, CAL_CSI2_COMPLEXIO_CFG(ctx->csi2_port));
605         u32 lane_mask = CAL_CSI2_COMPLEXIO_CFG_CLOCK_POSITION_MASK;
606         u32 polarity_mask = CAL_CSI2_COMPLEXIO_CFG_CLOCK_POL_MASK;
607         struct v4l2_fwnode_bus_mipi_csi2 *mipi_csi2 =
608                 &ctx->endpoint.bus.mipi_csi2;
609         int lane;
610
611         set_field(&val, mipi_csi2->clock_lane + 1, lane_mask);
612         set_field(&val, mipi_csi2->lane_polarities[0], polarity_mask);
613         for (lane = 0; lane < mipi_csi2->num_data_lanes; lane++) {
614                 /*
615                  * Every lane are one nibble apart starting with the
616                  * clock followed by the data lanes so shift masks by 4.
617                  */
618                 lane_mask <<= 4;
619                 polarity_mask <<= 4;
620                 set_field(&val, mipi_csi2->data_lanes[lane] + 1, lane_mask);
621                 set_field(&val, mipi_csi2->lane_polarities[lane + 1],
622                           polarity_mask);
623         }
624
625         reg_write(ctx->dev, CAL_CSI2_COMPLEXIO_CFG(ctx->csi2_port), val);
626         ctx_dbg(3, ctx, "CAL_CSI2_COMPLEXIO_CFG(%d) = 0x%08x\n",
627                 ctx->csi2_port, val);
628 }
629
630 static void csi2_ppi_enable(struct cal_ctx *ctx)
631 {
632         reg_write_field(ctx->dev, CAL_CSI2_PPI_CTRL(ctx->csi2_port),
633                         CAL_GEN_ENABLE, CAL_CSI2_PPI_CTRL_IF_EN_MASK);
634 }
635
636 static void csi2_ppi_disable(struct cal_ctx *ctx)
637 {
638         reg_write_field(ctx->dev, CAL_CSI2_PPI_CTRL(ctx->csi2_port),
639                         CAL_GEN_DISABLE, CAL_CSI2_PPI_CTRL_IF_EN_MASK);
640 }
641
642 static void csi2_ctx_config(struct cal_ctx *ctx)
643 {
644         u32 val;
645
646         val = reg_read(ctx->dev, CAL_CSI2_CTX0(ctx->csi2_port));
647         set_field(&val, ctx->csi2_port, CAL_CSI2_CTX_CPORT_MASK);
648         /*
649          * DT type: MIPI CSI-2 Specs
650          *   0x1: All - DT filter is disabled
651          *  0x24: RGB888 1 pixel  = 3 bytes
652          *  0x2B: RAW10  4 pixels = 5 bytes
653          *  0x2A: RAW8   1 pixel  = 1 byte
654          *  0x1E: YUV422 2 pixels = 4 bytes
655          */
656         set_field(&val, 0x1, CAL_CSI2_CTX_DT_MASK);
657         /* Virtual Channel from the CSI2 sensor usually 0! */
658         set_field(&val, ctx->virtual_channel, CAL_CSI2_CTX_VC_MASK);
659         /* NUM_LINES_PER_FRAME => 0 means auto detect */
660         set_field(&val, 0, CAL_CSI2_CTX_LINES_MASK);
661         set_field(&val, CAL_CSI2_CTX_ATT_PIX, CAL_CSI2_CTX_ATT_MASK);
662         set_field(&val, CAL_CSI2_CTX_PACK_MODE_LINE,
663                   CAL_CSI2_CTX_PACK_MODE_MASK);
664         reg_write(ctx->dev, CAL_CSI2_CTX0(ctx->csi2_port), val);
665         ctx_dbg(3, ctx, "CAL_CSI2_CTX0(%d) = 0x%08x\n", ctx->csi2_port,
666                 reg_read(ctx->dev, CAL_CSI2_CTX0(ctx->csi2_port)));
667 }
668
669 static void pix_proc_config(struct cal_ctx *ctx)
670 {
671         u32 val;
672
673         val = reg_read(ctx->dev, CAL_PIX_PROC(ctx->csi2_port));
674         set_field(&val, CAL_PIX_PROC_EXTRACT_B8, CAL_PIX_PROC_EXTRACT_MASK);
675         set_field(&val, CAL_PIX_PROC_DPCMD_BYPASS, CAL_PIX_PROC_DPCMD_MASK);
676         set_field(&val, CAL_PIX_PROC_DPCME_BYPASS, CAL_PIX_PROC_DPCME_MASK);
677         set_field(&val, CAL_PIX_PROC_PACK_B8, CAL_PIX_PROC_PACK_MASK);
678         set_field(&val, ctx->csi2_port, CAL_PIX_PROC_CPORT_MASK);
679         set_field(&val, CAL_GEN_ENABLE, CAL_PIX_PROC_EN_MASK);
680         reg_write(ctx->dev, CAL_PIX_PROC(ctx->csi2_port), val);
681         ctx_dbg(3, ctx, "CAL_PIX_PROC(%d) = 0x%08x\n", ctx->csi2_port,
682                 reg_read(ctx->dev, CAL_PIX_PROC(ctx->csi2_port)));
683 }
684
685 static void cal_wr_dma_config(struct cal_ctx *ctx,
686                               unsigned int width)
687 {
688         u32 val;
689
690         val = reg_read(ctx->dev, CAL_WR_DMA_CTRL(ctx->csi2_port));
691         set_field(&val, ctx->csi2_port, CAL_WR_DMA_CTRL_CPORT_MASK);
692         set_field(&val, CAL_WR_DMA_CTRL_DTAG_PIX_DAT,
693                   CAL_WR_DMA_CTRL_DTAG_MASK);
694         set_field(&val, CAL_WR_DMA_CTRL_MODE_CONST,
695                   CAL_WR_DMA_CTRL_MODE_MASK);
696         set_field(&val, CAL_WR_DMA_CTRL_PATTERN_LINEAR,
697                   CAL_WR_DMA_CTRL_PATTERN_MASK);
698         set_field(&val, CAL_GEN_ENABLE, CAL_WR_DMA_CTRL_STALL_RD_MASK);
699         reg_write(ctx->dev, CAL_WR_DMA_CTRL(ctx->csi2_port), val);
700         ctx_dbg(3, ctx, "CAL_WR_DMA_CTRL(%d) = 0x%08x\n", ctx->csi2_port,
701                 reg_read(ctx->dev, CAL_WR_DMA_CTRL(ctx->csi2_port)));
702
703         /*
704          * width/16 not sure but giving it a whirl.
705          * zero does not work right
706          */
707         reg_write_field(ctx->dev,
708                         CAL_WR_DMA_OFST(ctx->csi2_port),
709                         (width / 16),
710                         CAL_WR_DMA_OFST_MASK);
711         ctx_dbg(3, ctx, "CAL_WR_DMA_OFST(%d) = 0x%08x\n", ctx->csi2_port,
712                 reg_read(ctx->dev, CAL_WR_DMA_OFST(ctx->csi2_port)));
713
714         val = reg_read(ctx->dev, CAL_WR_DMA_XSIZE(ctx->csi2_port));
715         /* 64 bit word means no skipping */
716         set_field(&val, 0, CAL_WR_DMA_XSIZE_XSKIP_MASK);
717         /*
718          * (width*8)/64 this should be size of an entire line
719          * in 64bit word but 0 means all data until the end
720          * is detected automagically
721          */
722         set_field(&val, (width / 8), CAL_WR_DMA_XSIZE_MASK);
723         reg_write(ctx->dev, CAL_WR_DMA_XSIZE(ctx->csi2_port), val);
724         ctx_dbg(3, ctx, "CAL_WR_DMA_XSIZE(%d) = 0x%08x\n", ctx->csi2_port,
725                 reg_read(ctx->dev, CAL_WR_DMA_XSIZE(ctx->csi2_port)));
726 }
727
728 static void cal_wr_dma_addr(struct cal_ctx *ctx, unsigned int dmaaddr)
729 {
730         reg_write(ctx->dev, CAL_WR_DMA_ADDR(ctx->csi2_port), dmaaddr);
731 }
732
733 /*
734  * TCLK values are OK at their reset values
735  */
736 #define TCLK_TERM       0
737 #define TCLK_MISS       1
738 #define TCLK_SETTLE     14
739 #define THS_SETTLE      15
740
741 static void csi2_phy_config(struct cal_ctx *ctx)
742 {
743         unsigned int reg0, reg1;
744         unsigned int ths_term, ths_settle;
745         unsigned int ddrclkperiod_us;
746
747         /*
748          * THS_TERM: Programmed value = floor(20 ns/DDRClk period) - 2.
749          */
750         ddrclkperiod_us = ctx->external_rate / 2000000;
751         ddrclkperiod_us = 1000000 / ddrclkperiod_us;
752         ctx_dbg(1, ctx, "ddrclkperiod_us: %d\n", ddrclkperiod_us);
753
754         ths_term = 20000 / ddrclkperiod_us;
755         ths_term = (ths_term >= 2) ? ths_term - 2 : ths_term;
756         ctx_dbg(1, ctx, "ths_term: %d (0x%02x)\n", ths_term, ths_term);
757
758         /*
759          * THS_SETTLE: Programmed value = floor(176.3 ns/CtrlClk period) - 1.
760          *      Since CtrlClk is fixed at 96Mhz then we get
761          *      ths_settle = floor(176.3 / 10.416) - 1 = 15
762          * If we ever switch to a dynamic clock then this code might be useful
763          *
764          * unsigned int ctrlclkperiod_us;
765          * ctrlclkperiod_us = 96000000 / 1000000;
766          * ctrlclkperiod_us = 1000000 / ctrlclkperiod_us;
767          * ctx_dbg(1, ctx, "ctrlclkperiod_us: %d\n", ctrlclkperiod_us);
768
769          * ths_settle = 176300  / ctrlclkperiod_us;
770          * ths_settle = (ths_settle > 1) ? ths_settle - 1 : ths_settle;
771          */
772
773         ths_settle = THS_SETTLE;
774         ctx_dbg(1, ctx, "ths_settle: %d (0x%02x)\n", ths_settle, ths_settle);
775
776         reg0 = reg_read(ctx->cc, CAL_CSI2_PHY_REG0);
777         set_field(&reg0, CAL_CSI2_PHY_REG0_HSCLOCKCONFIG_DISABLE,
778                   CAL_CSI2_PHY_REG0_HSCLOCKCONFIG_MASK);
779         set_field(&reg0, ths_term, CAL_CSI2_PHY_REG0_THS_TERM_MASK);
780         set_field(&reg0, ths_settle, CAL_CSI2_PHY_REG0_THS_SETTLE_MASK);
781
782         ctx_dbg(1, ctx, "CSI2_%d_REG0 = 0x%08x\n", (ctx->csi2_port - 1), reg0);
783         reg_write(ctx->cc, CAL_CSI2_PHY_REG0, reg0);
784
785         reg1 = reg_read(ctx->cc, CAL_CSI2_PHY_REG1);
786         set_field(&reg1, TCLK_TERM, CAL_CSI2_PHY_REG1_TCLK_TERM_MASK);
787         set_field(&reg1, 0xb8, CAL_CSI2_PHY_REG1_DPHY_HS_SYNC_PATTERN_MASK);
788         set_field(&reg1, TCLK_MISS, CAL_CSI2_PHY_REG1_CTRLCLK_DIV_FACTOR_MASK);
789         set_field(&reg1, TCLK_SETTLE, CAL_CSI2_PHY_REG1_TCLK_SETTLE_MASK);
790
791         ctx_dbg(1, ctx, "CSI2_%d_REG1 = 0x%08x\n", (ctx->csi2_port - 1), reg1);
792         reg_write(ctx->cc, CAL_CSI2_PHY_REG1, reg1);
793 }
794
795 static int cal_get_external_info(struct cal_ctx *ctx)
796 {
797         struct v4l2_ctrl *ctrl;
798
799         if (!ctx->sensor)
800                 return -ENODEV;
801
802         ctrl = v4l2_ctrl_find(ctx->sensor->ctrl_handler, V4L2_CID_PIXEL_RATE);
803         if (!ctrl) {
804                 ctx_err(ctx, "no pixel rate control in subdev: %s\n",
805                         ctx->sensor->name);
806                 return -EPIPE;
807         }
808
809         ctx->external_rate = v4l2_ctrl_g_ctrl_int64(ctrl);
810         ctx_dbg(3, ctx, "sensor Pixel Rate: %d\n", ctx->external_rate);
811
812         return 0;
813 }
814
815 static inline void cal_schedule_next_buffer(struct cal_ctx *ctx)
816 {
817         struct cal_dmaqueue *dma_q = &ctx->vidq;
818         struct cal_buffer *buf;
819         unsigned long addr;
820
821         buf = list_entry(dma_q->active.next, struct cal_buffer, list);
822         ctx->next_frm = buf;
823         list_del(&buf->list);
824
825         addr = vb2_dma_contig_plane_dma_addr(&buf->vb.vb2_buf, 0);
826         cal_wr_dma_addr(ctx, addr);
827 }
828
829 static inline void cal_process_buffer_complete(struct cal_ctx *ctx)
830 {
831         ctx->cur_frm->vb.vb2_buf.timestamp = ktime_get_ns();
832         ctx->cur_frm->vb.field = ctx->m_fmt.field;
833         ctx->cur_frm->vb.sequence = ctx->sequence++;
834
835         vb2_buffer_done(&ctx->cur_frm->vb.vb2_buf, VB2_BUF_STATE_DONE);
836         ctx->cur_frm = ctx->next_frm;
837 }
838
839 #define isvcirqset(irq, vc, ff) (irq & \
840         (CAL_CSI2_VC_IRQENABLE_ ##ff ##_IRQ_##vc ##_MASK))
841
842 #define isportirqset(irq, port) (irq & CAL_HL_IRQ_MASK(port))
843
844 static irqreturn_t cal_irq(int irq_cal, void *data)
845 {
846         struct cal_dev *dev = (struct cal_dev *)data;
847         struct cal_ctx *ctx;
848         struct cal_dmaqueue *dma_q;
849         u32 irqst2, irqst3;
850
851         /* Check which DMA just finished */
852         irqst2 = reg_read(dev, CAL_HL_IRQSTATUS(2));
853         if (irqst2) {
854                 /* Clear Interrupt status */
855                 reg_write(dev, CAL_HL_IRQSTATUS(2), irqst2);
856
857                 /* Need to check both port */
858                 if (isportirqset(irqst2, 1)) {
859                         ctx = dev->ctx[0];
860
861                         if (ctx->cur_frm != ctx->next_frm)
862                                 cal_process_buffer_complete(ctx);
863                 }
864
865                 if (isportirqset(irqst2, 2)) {
866                         ctx = dev->ctx[1];
867
868                         if (ctx->cur_frm != ctx->next_frm)
869                                 cal_process_buffer_complete(ctx);
870                 }
871         }
872
873         /* Check which DMA just started */
874         irqst3 = reg_read(dev, CAL_HL_IRQSTATUS(3));
875         if (irqst3) {
876                 /* Clear Interrupt status */
877                 reg_write(dev, CAL_HL_IRQSTATUS(3), irqst3);
878
879                 /* Need to check both port */
880                 if (isportirqset(irqst3, 1)) {
881                         ctx = dev->ctx[0];
882                         dma_q = &ctx->vidq;
883
884                         spin_lock(&ctx->slock);
885                         if (!list_empty(&dma_q->active) &&
886                             ctx->cur_frm == ctx->next_frm)
887                                 cal_schedule_next_buffer(ctx);
888                         spin_unlock(&ctx->slock);
889                 }
890
891                 if (isportirqset(irqst3, 2)) {
892                         ctx = dev->ctx[1];
893                         dma_q = &ctx->vidq;
894
895                         spin_lock(&ctx->slock);
896                         if (!list_empty(&dma_q->active) &&
897                             ctx->cur_frm == ctx->next_frm)
898                                 cal_schedule_next_buffer(ctx);
899                         spin_unlock(&ctx->slock);
900                 }
901         }
902
903         return IRQ_HANDLED;
904 }
905
906 /*
907  * video ioctls
908  */
909 static int cal_querycap(struct file *file, void *priv,
910                         struct v4l2_capability *cap)
911 {
912         struct cal_ctx *ctx = video_drvdata(file);
913
914         strscpy(cap->driver, CAL_MODULE_NAME, sizeof(cap->driver));
915         strscpy(cap->card, CAL_MODULE_NAME, sizeof(cap->card));
916
917         snprintf(cap->bus_info, sizeof(cap->bus_info),
918                  "platform:%s", ctx->v4l2_dev.name);
919         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
920                             V4L2_CAP_READWRITE;
921         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
922         return 0;
923 }
924
925 static int cal_enum_fmt_vid_cap(struct file *file, void  *priv,
926                                 struct v4l2_fmtdesc *f)
927 {
928         struct cal_ctx *ctx = video_drvdata(file);
929         const struct cal_fmt *fmt = NULL;
930
931         if (f->index >= ctx->num_active_fmt)
932                 return -EINVAL;
933
934         fmt = ctx->active_fmt[f->index];
935
936         f->pixelformat = fmt->fourcc;
937         f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
938         return 0;
939 }
940
941 static int __subdev_get_format(struct cal_ctx *ctx,
942                                struct v4l2_mbus_framefmt *fmt)
943 {
944         struct v4l2_subdev_format sd_fmt;
945         struct v4l2_mbus_framefmt *mbus_fmt = &sd_fmt.format;
946         int ret;
947
948         sd_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
949         sd_fmt.pad = 0;
950
951         ret = v4l2_subdev_call(ctx->sensor, pad, get_fmt, NULL, &sd_fmt);
952         if (ret)
953                 return ret;
954
955         *fmt = *mbus_fmt;
956
957         ctx_dbg(1, ctx, "%s %dx%d code:%04X\n", __func__,
958                 fmt->width, fmt->height, fmt->code);
959
960         return 0;
961 }
962
963 static int __subdev_set_format(struct cal_ctx *ctx,
964                                struct v4l2_mbus_framefmt *fmt)
965 {
966         struct v4l2_subdev_format sd_fmt;
967         struct v4l2_mbus_framefmt *mbus_fmt = &sd_fmt.format;
968         int ret;
969
970         sd_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
971         sd_fmt.pad = 0;
972         *mbus_fmt = *fmt;
973
974         ret = v4l2_subdev_call(ctx->sensor, pad, set_fmt, NULL, &sd_fmt);
975         if (ret)
976                 return ret;
977
978         ctx_dbg(1, ctx, "%s %dx%d code:%04X\n", __func__,
979                 fmt->width, fmt->height, fmt->code);
980
981         return 0;
982 }
983
984 static int cal_calc_format_size(struct cal_ctx *ctx,
985                                 const struct cal_fmt *fmt,
986                                 struct v4l2_format *f)
987 {
988         if (!fmt) {
989                 ctx_dbg(3, ctx, "No cal_fmt provided!\n");
990                 return -EINVAL;
991         }
992
993         v4l_bound_align_image(&f->fmt.pix.width, 48, MAX_WIDTH, 2,
994                               &f->fmt.pix.height, 32, MAX_HEIGHT, 0, 0);
995         f->fmt.pix.bytesperline = bytes_per_line(f->fmt.pix.width,
996                                                  fmt->depth >> 3);
997         f->fmt.pix.sizeimage = f->fmt.pix.height *
998                                f->fmt.pix.bytesperline;
999
1000         ctx_dbg(3, ctx, "%s: fourcc: %s size: %dx%d bpl:%d img_size:%d\n",
1001                 __func__, fourcc_to_str(f->fmt.pix.pixelformat),
1002                 f->fmt.pix.width, f->fmt.pix.height,
1003                 f->fmt.pix.bytesperline, f->fmt.pix.sizeimage);
1004
1005         return 0;
1006 }
1007
1008 static int cal_g_fmt_vid_cap(struct file *file, void *priv,
1009                              struct v4l2_format *f)
1010 {
1011         struct cal_ctx *ctx = video_drvdata(file);
1012
1013         *f = ctx->v_fmt;
1014
1015         return 0;
1016 }
1017
1018 static int cal_try_fmt_vid_cap(struct file *file, void *priv,
1019                                struct v4l2_format *f)
1020 {
1021         struct cal_ctx *ctx = video_drvdata(file);
1022         const struct cal_fmt *fmt;
1023         struct v4l2_subdev_frame_size_enum fse;
1024         int ret, found;
1025
1026         fmt = find_format_by_pix(ctx, f->fmt.pix.pixelformat);
1027         if (!fmt) {
1028                 ctx_dbg(3, ctx, "Fourcc format (0x%08x) not found.\n",
1029                         f->fmt.pix.pixelformat);
1030
1031                 /* Just get the first one enumerated */
1032                 fmt = ctx->active_fmt[0];
1033                 f->fmt.pix.pixelformat = fmt->fourcc;
1034         }
1035
1036         f->fmt.pix.field = ctx->v_fmt.fmt.pix.field;
1037
1038         /* check for/find a valid width/height */
1039         ret = 0;
1040         found = false;
1041         fse.pad = 0;
1042         fse.code = fmt->code;
1043         fse.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1044         for (fse.index = 0; ; fse.index++) {
1045                 ret = v4l2_subdev_call(ctx->sensor, pad, enum_frame_size,
1046                                        NULL, &fse);
1047                 if (ret)
1048                         break;
1049
1050                 if ((f->fmt.pix.width == fse.max_width) &&
1051                     (f->fmt.pix.height == fse.max_height)) {
1052                         found = true;
1053                         break;
1054                 } else if ((f->fmt.pix.width >= fse.min_width) &&
1055                          (f->fmt.pix.width <= fse.max_width) &&
1056                          (f->fmt.pix.height >= fse.min_height) &&
1057                          (f->fmt.pix.height <= fse.max_height)) {
1058                         found = true;
1059                         break;
1060                 }
1061         }
1062
1063         if (!found) {
1064                 /* use existing values as default */
1065                 f->fmt.pix.width = ctx->v_fmt.fmt.pix.width;
1066                 f->fmt.pix.height =  ctx->v_fmt.fmt.pix.height;
1067         }
1068
1069         /*
1070          * Use current colorspace for now, it will get
1071          * updated properly during s_fmt
1072          */
1073         f->fmt.pix.colorspace = ctx->v_fmt.fmt.pix.colorspace;
1074         return cal_calc_format_size(ctx, fmt, f);
1075 }
1076
1077 static int cal_s_fmt_vid_cap(struct file *file, void *priv,
1078                              struct v4l2_format *f)
1079 {
1080         struct cal_ctx *ctx = video_drvdata(file);
1081         struct vb2_queue *q = &ctx->vb_vidq;
1082         const struct cal_fmt *fmt;
1083         struct v4l2_mbus_framefmt mbus_fmt;
1084         int ret;
1085
1086         if (vb2_is_busy(q)) {
1087                 ctx_dbg(3, ctx, "%s device busy\n", __func__);
1088                 return -EBUSY;
1089         }
1090
1091         ret = cal_try_fmt_vid_cap(file, priv, f);
1092         if (ret < 0)
1093                 return ret;
1094
1095         fmt = find_format_by_pix(ctx, f->fmt.pix.pixelformat);
1096
1097         v4l2_fill_mbus_format(&mbus_fmt, &f->fmt.pix, fmt->code);
1098
1099         ret = __subdev_set_format(ctx, &mbus_fmt);
1100         if (ret)
1101                 return ret;
1102
1103         /* Just double check nothing has gone wrong */
1104         if (mbus_fmt.code != fmt->code) {
1105                 ctx_dbg(3, ctx,
1106                         "%s subdev changed format on us, this should not happen\n",
1107                         __func__);
1108                 return -EINVAL;
1109         }
1110
1111         v4l2_fill_pix_format(&ctx->v_fmt.fmt.pix, &mbus_fmt);
1112         ctx->v_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1113         ctx->v_fmt.fmt.pix.pixelformat  = fmt->fourcc;
1114         cal_calc_format_size(ctx, fmt, &ctx->v_fmt);
1115         ctx->fmt = fmt;
1116         ctx->m_fmt = mbus_fmt;
1117         *f = ctx->v_fmt;
1118
1119         return 0;
1120 }
1121
1122 static int cal_enum_framesizes(struct file *file, void *fh,
1123                                struct v4l2_frmsizeenum *fsize)
1124 {
1125         struct cal_ctx *ctx = video_drvdata(file);
1126         const struct cal_fmt *fmt;
1127         struct v4l2_subdev_frame_size_enum fse;
1128         int ret;
1129
1130         /* check for valid format */
1131         fmt = find_format_by_pix(ctx, fsize->pixel_format);
1132         if (!fmt) {
1133                 ctx_dbg(3, ctx, "Invalid pixel code: %x\n",
1134                         fsize->pixel_format);
1135                 return -EINVAL;
1136         }
1137
1138         fse.index = fsize->index;
1139         fse.pad = 0;
1140         fse.code = fmt->code;
1141
1142         ret = v4l2_subdev_call(ctx->sensor, pad, enum_frame_size, NULL, &fse);
1143         if (ret)
1144                 return ret;
1145
1146         ctx_dbg(1, ctx, "%s: index: %d code: %x W:[%d,%d] H:[%d,%d]\n",
1147                 __func__, fse.index, fse.code, fse.min_width, fse.max_width,
1148                 fse.min_height, fse.max_height);
1149
1150         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1151         fsize->discrete.width = fse.max_width;
1152         fsize->discrete.height = fse.max_height;
1153
1154         return 0;
1155 }
1156
1157 static int cal_enum_input(struct file *file, void *priv,
1158                           struct v4l2_input *inp)
1159 {
1160         if (inp->index >= CAL_NUM_INPUT)
1161                 return -EINVAL;
1162
1163         inp->type = V4L2_INPUT_TYPE_CAMERA;
1164         sprintf(inp->name, "Camera %u", inp->index);
1165         return 0;
1166 }
1167
1168 static int cal_g_input(struct file *file, void *priv, unsigned int *i)
1169 {
1170         struct cal_ctx *ctx = video_drvdata(file);
1171
1172         *i = ctx->input;
1173         return 0;
1174 }
1175
1176 static int cal_s_input(struct file *file, void *priv, unsigned int i)
1177 {
1178         struct cal_ctx *ctx = video_drvdata(file);
1179
1180         if (i >= CAL_NUM_INPUT)
1181                 return -EINVAL;
1182
1183         ctx->input = i;
1184         return 0;
1185 }
1186
1187 /* timeperframe is arbitrary and continuous */
1188 static int cal_enum_frameintervals(struct file *file, void *priv,
1189                                    struct v4l2_frmivalenum *fival)
1190 {
1191         struct cal_ctx *ctx = video_drvdata(file);
1192         const struct cal_fmt *fmt;
1193         struct v4l2_subdev_frame_interval_enum fie = {
1194                 .index = fival->index,
1195                 .width = fival->width,
1196                 .height = fival->height,
1197                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1198         };
1199         int ret;
1200
1201         fmt = find_format_by_pix(ctx, fival->pixel_format);
1202         if (!fmt)
1203                 return -EINVAL;
1204
1205         fie.code = fmt->code;
1206         ret = v4l2_subdev_call(ctx->sensor, pad, enum_frame_interval,
1207                                NULL, &fie);
1208         if (ret)
1209                 return ret;
1210         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1211         fival->discrete = fie.interval;
1212
1213         return 0;
1214 }
1215
1216 /*
1217  * Videobuf operations
1218  */
1219 static int cal_queue_setup(struct vb2_queue *vq,
1220                            unsigned int *nbuffers, unsigned int *nplanes,
1221                            unsigned int sizes[], struct device *alloc_devs[])
1222 {
1223         struct cal_ctx *ctx = vb2_get_drv_priv(vq);
1224         unsigned size = ctx->v_fmt.fmt.pix.sizeimage;
1225
1226         if (vq->num_buffers + *nbuffers < 3)
1227                 *nbuffers = 3 - vq->num_buffers;
1228
1229         if (*nplanes) {
1230                 if (sizes[0] < size)
1231                         return -EINVAL;
1232                 size = sizes[0];
1233         }
1234
1235         *nplanes = 1;
1236         sizes[0] = size;
1237
1238         ctx_dbg(3, ctx, "nbuffers=%d, size=%d\n", *nbuffers, sizes[0]);
1239
1240         return 0;
1241 }
1242
1243 static int cal_buffer_prepare(struct vb2_buffer *vb)
1244 {
1245         struct cal_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1246         struct cal_buffer *buf = container_of(vb, struct cal_buffer,
1247                                               vb.vb2_buf);
1248         unsigned long size;
1249
1250         if (WARN_ON(!ctx->fmt))
1251                 return -EINVAL;
1252
1253         size = ctx->v_fmt.fmt.pix.sizeimage;
1254         if (vb2_plane_size(vb, 0) < size) {
1255                 ctx_err(ctx,
1256                         "data will not fit into plane (%lu < %lu)\n",
1257                         vb2_plane_size(vb, 0), size);
1258                 return -EINVAL;
1259         }
1260
1261         vb2_set_plane_payload(&buf->vb.vb2_buf, 0, size);
1262         return 0;
1263 }
1264
1265 static void cal_buffer_queue(struct vb2_buffer *vb)
1266 {
1267         struct cal_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1268         struct cal_buffer *buf = container_of(vb, struct cal_buffer,
1269                                               vb.vb2_buf);
1270         struct cal_dmaqueue *vidq = &ctx->vidq;
1271         unsigned long flags = 0;
1272
1273         /* recheck locking */
1274         spin_lock_irqsave(&ctx->slock, flags);
1275         list_add_tail(&buf->list, &vidq->active);
1276         spin_unlock_irqrestore(&ctx->slock, flags);
1277 }
1278
1279 static int cal_start_streaming(struct vb2_queue *vq, unsigned int count)
1280 {
1281         struct cal_ctx *ctx = vb2_get_drv_priv(vq);
1282         struct cal_dmaqueue *dma_q = &ctx->vidq;
1283         struct cal_buffer *buf, *tmp;
1284         unsigned long addr = 0;
1285         unsigned long flags;
1286         int ret;
1287
1288         spin_lock_irqsave(&ctx->slock, flags);
1289         if (list_empty(&dma_q->active)) {
1290                 spin_unlock_irqrestore(&ctx->slock, flags);
1291                 ctx_dbg(3, ctx, "buffer queue is empty\n");
1292                 return -EIO;
1293         }
1294
1295         buf = list_entry(dma_q->active.next, struct cal_buffer, list);
1296         ctx->cur_frm = buf;
1297         ctx->next_frm = buf;
1298         list_del(&buf->list);
1299         spin_unlock_irqrestore(&ctx->slock, flags);
1300
1301         addr = vb2_dma_contig_plane_dma_addr(&ctx->cur_frm->vb.vb2_buf, 0);
1302         ctx->sequence = 0;
1303
1304         ret = cal_get_external_info(ctx);
1305         if (ret < 0)
1306                 goto err;
1307
1308         cal_runtime_get(ctx->dev);
1309
1310         enable_irqs(ctx);
1311         camerarx_phy_enable(ctx);
1312         csi2_init(ctx);
1313         csi2_phy_config(ctx);
1314         csi2_lane_config(ctx);
1315         csi2_ctx_config(ctx);
1316         pix_proc_config(ctx);
1317         cal_wr_dma_config(ctx, ctx->v_fmt.fmt.pix.bytesperline);
1318         cal_wr_dma_addr(ctx, addr);
1319         csi2_ppi_enable(ctx);
1320
1321         ret = v4l2_subdev_call(ctx->sensor, video, s_stream, 1);
1322         if (ret) {
1323                 ctx_err(ctx, "stream on failed in subdev\n");
1324                 cal_runtime_put(ctx->dev);
1325                 goto err;
1326         }
1327
1328         if (debug >= 4)
1329                 cal_quickdump_regs(ctx->dev);
1330
1331         return 0;
1332
1333 err:
1334         list_for_each_entry_safe(buf, tmp, &dma_q->active, list) {
1335                 list_del(&buf->list);
1336                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED);
1337         }
1338         return ret;
1339 }
1340
1341 static void cal_stop_streaming(struct vb2_queue *vq)
1342 {
1343         struct cal_ctx *ctx = vb2_get_drv_priv(vq);
1344         struct cal_dmaqueue *dma_q = &ctx->vidq;
1345         struct cal_buffer *buf, *tmp;
1346         unsigned long flags;
1347
1348         if (v4l2_subdev_call(ctx->sensor, video, s_stream, 0))
1349                 ctx_err(ctx, "stream off failed in subdev\n");
1350
1351         csi2_ppi_disable(ctx);
1352         disable_irqs(ctx);
1353
1354         /* Release all active buffers */
1355         spin_lock_irqsave(&ctx->slock, flags);
1356         list_for_each_entry_safe(buf, tmp, &dma_q->active, list) {
1357                 list_del(&buf->list);
1358                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1359         }
1360
1361         if (ctx->cur_frm == ctx->next_frm) {
1362                 vb2_buffer_done(&ctx->cur_frm->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1363         } else {
1364                 vb2_buffer_done(&ctx->cur_frm->vb.vb2_buf, VB2_BUF_STATE_ERROR);
1365                 vb2_buffer_done(&ctx->next_frm->vb.vb2_buf,
1366                                 VB2_BUF_STATE_ERROR);
1367         }
1368         ctx->cur_frm = NULL;
1369         ctx->next_frm = NULL;
1370         spin_unlock_irqrestore(&ctx->slock, flags);
1371
1372         cal_runtime_put(ctx->dev);
1373 }
1374
1375 static const struct vb2_ops cal_video_qops = {
1376         .queue_setup            = cal_queue_setup,
1377         .buf_prepare            = cal_buffer_prepare,
1378         .buf_queue              = cal_buffer_queue,
1379         .start_streaming        = cal_start_streaming,
1380         .stop_streaming         = cal_stop_streaming,
1381         .wait_prepare           = vb2_ops_wait_prepare,
1382         .wait_finish            = vb2_ops_wait_finish,
1383 };
1384
1385 static const struct v4l2_file_operations cal_fops = {
1386         .owner          = THIS_MODULE,
1387         .open           = v4l2_fh_open,
1388         .release        = vb2_fop_release,
1389         .read           = vb2_fop_read,
1390         .poll           = vb2_fop_poll,
1391         .unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
1392         .mmap           = vb2_fop_mmap,
1393 };
1394
1395 static const struct v4l2_ioctl_ops cal_ioctl_ops = {
1396         .vidioc_querycap      = cal_querycap,
1397         .vidioc_enum_fmt_vid_cap  = cal_enum_fmt_vid_cap,
1398         .vidioc_g_fmt_vid_cap     = cal_g_fmt_vid_cap,
1399         .vidioc_try_fmt_vid_cap   = cal_try_fmt_vid_cap,
1400         .vidioc_s_fmt_vid_cap     = cal_s_fmt_vid_cap,
1401         .vidioc_enum_framesizes   = cal_enum_framesizes,
1402         .vidioc_reqbufs       = vb2_ioctl_reqbufs,
1403         .vidioc_create_bufs   = vb2_ioctl_create_bufs,
1404         .vidioc_prepare_buf   = vb2_ioctl_prepare_buf,
1405         .vidioc_querybuf      = vb2_ioctl_querybuf,
1406         .vidioc_qbuf          = vb2_ioctl_qbuf,
1407         .vidioc_dqbuf         = vb2_ioctl_dqbuf,
1408         .vidioc_enum_input    = cal_enum_input,
1409         .vidioc_g_input       = cal_g_input,
1410         .vidioc_s_input       = cal_s_input,
1411         .vidioc_enum_frameintervals = cal_enum_frameintervals,
1412         .vidioc_streamon      = vb2_ioctl_streamon,
1413         .vidioc_streamoff     = vb2_ioctl_streamoff,
1414         .vidioc_log_status    = v4l2_ctrl_log_status,
1415         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1416         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1417 };
1418
1419 static const struct video_device cal_videodev = {
1420         .name           = CAL_MODULE_NAME,
1421         .fops           = &cal_fops,
1422         .ioctl_ops      = &cal_ioctl_ops,
1423         .minor          = -1,
1424         .release        = video_device_release_empty,
1425 };
1426
1427 /* -----------------------------------------------------------------
1428  *      Initialization and module stuff
1429  * ------------------------------------------------------------------
1430  */
1431 static int cal_complete_ctx(struct cal_ctx *ctx);
1432
1433 static int cal_async_bound(struct v4l2_async_notifier *notifier,
1434                            struct v4l2_subdev *subdev,
1435                            struct v4l2_async_subdev *asd)
1436 {
1437         struct cal_ctx *ctx = notifier_to_ctx(notifier);
1438         struct v4l2_subdev_mbus_code_enum mbus_code;
1439         int ret = 0;
1440         int i, j, k;
1441
1442         if (ctx->sensor) {
1443                 ctx_info(ctx, "Rejecting subdev %s (Already set!!)",
1444                          subdev->name);
1445                 return 0;
1446         }
1447
1448         ctx->sensor = subdev;
1449         ctx_dbg(1, ctx, "Using sensor %s for capture\n", subdev->name);
1450
1451         /* Enumerate sub device formats and enable all matching local formats */
1452         ctx->num_active_fmt = 0;
1453         for (j = 0, i = 0; ret != -EINVAL; ++j) {
1454                 struct cal_fmt *fmt;
1455
1456                 memset(&mbus_code, 0, sizeof(mbus_code));
1457                 mbus_code.index = j;
1458                 ret = v4l2_subdev_call(subdev, pad, enum_mbus_code,
1459                                        NULL, &mbus_code);
1460                 if (ret)
1461                         continue;
1462
1463                 ctx_dbg(2, ctx,
1464                         "subdev %s: code: %04x idx: %d\n",
1465                         subdev->name, mbus_code.code, j);
1466
1467                 for (k = 0; k < ARRAY_SIZE(cal_formats); k++) {
1468                         fmt = &cal_formats[k];
1469
1470                         if (mbus_code.code == fmt->code) {
1471                                 ctx->active_fmt[i] = fmt;
1472                                 ctx_dbg(2, ctx,
1473                                         "matched fourcc: %s: code: %04x idx: %d\n",
1474                                         fourcc_to_str(fmt->fourcc),
1475                                         fmt->code, i);
1476                                 ctx->num_active_fmt = ++i;
1477                         }
1478                 }
1479         }
1480
1481         if (i == 0) {
1482                 ctx_err(ctx, "No suitable format reported by subdev %s\n",
1483                         subdev->name);
1484                 return -EINVAL;
1485         }
1486
1487         cal_complete_ctx(ctx);
1488
1489         return 0;
1490 }
1491
1492 static int cal_async_complete(struct v4l2_async_notifier *notifier)
1493 {
1494         struct cal_ctx *ctx = notifier_to_ctx(notifier);
1495         const struct cal_fmt *fmt;
1496         struct v4l2_mbus_framefmt mbus_fmt;
1497         int ret;
1498
1499         ret = __subdev_get_format(ctx, &mbus_fmt);
1500         if (ret)
1501                 return ret;
1502
1503         fmt = find_format_by_code(ctx, mbus_fmt.code);
1504         if (!fmt) {
1505                 ctx_dbg(3, ctx, "mbus code format (0x%08x) not found.\n",
1506                         mbus_fmt.code);
1507                 return -EINVAL;
1508         }
1509
1510         /* Save current subdev format */
1511         v4l2_fill_pix_format(&ctx->v_fmt.fmt.pix, &mbus_fmt);
1512         ctx->v_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1513         ctx->v_fmt.fmt.pix.pixelformat  = fmt->fourcc;
1514         cal_calc_format_size(ctx, fmt, &ctx->v_fmt);
1515         ctx->fmt = fmt;
1516         ctx->m_fmt = mbus_fmt;
1517
1518         return 0;
1519 }
1520
1521 static const struct v4l2_async_notifier_operations cal_async_ops = {
1522         .bound = cal_async_bound,
1523         .complete = cal_async_complete,
1524 };
1525
1526 static int cal_complete_ctx(struct cal_ctx *ctx)
1527 {
1528         struct video_device *vfd;
1529         struct vb2_queue *q;
1530         int ret;
1531
1532         ctx->timeperframe = tpf_default;
1533         ctx->external_rate = 192000000;
1534
1535         /* initialize locks */
1536         spin_lock_init(&ctx->slock);
1537         mutex_init(&ctx->mutex);
1538
1539         /* initialize queue */
1540         q = &ctx->vb_vidq;
1541         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1542         q->io_modes = VB2_MMAP | VB2_DMABUF | VB2_READ;
1543         q->drv_priv = ctx;
1544         q->buf_struct_size = sizeof(struct cal_buffer);
1545         q->ops = &cal_video_qops;
1546         q->mem_ops = &vb2_dma_contig_memops;
1547         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1548         q->lock = &ctx->mutex;
1549         q->min_buffers_needed = 3;
1550         q->dev = ctx->v4l2_dev.dev;
1551
1552         ret = vb2_queue_init(q);
1553         if (ret)
1554                 return ret;
1555
1556         /* init video dma queues */
1557         INIT_LIST_HEAD(&ctx->vidq.active);
1558
1559         vfd = &ctx->vdev;
1560         *vfd = cal_videodev;
1561         vfd->v4l2_dev = &ctx->v4l2_dev;
1562         vfd->queue = q;
1563
1564         /*
1565          * Provide a mutex to v4l2 core. It will be used to protect
1566          * all fops and v4l2 ioctls.
1567          */
1568         vfd->lock = &ctx->mutex;
1569         video_set_drvdata(vfd, ctx);
1570
1571         ret = video_register_device(vfd, VFL_TYPE_GRABBER, video_nr);
1572         if (ret < 0)
1573                 return ret;
1574
1575         v4l2_info(&ctx->v4l2_dev, "V4L2 device registered as %s\n",
1576                   video_device_node_name(vfd));
1577
1578         return 0;
1579 }
1580
1581 static struct device_node *
1582 of_get_next_port(const struct device_node *parent,
1583                  struct device_node *prev)
1584 {
1585         struct device_node *port = NULL;
1586
1587         if (!parent)
1588                 return NULL;
1589
1590         if (!prev) {
1591                 struct device_node *ports;
1592                 /*
1593                  * It's the first call, we have to find a port subnode
1594                  * within this node or within an optional 'ports' node.
1595                  */
1596                 ports = of_get_child_by_name(parent, "ports");
1597                 if (ports)
1598                         parent = ports;
1599
1600                 port = of_get_child_by_name(parent, "port");
1601
1602                 /* release the 'ports' node */
1603                 of_node_put(ports);
1604         } else {
1605                 struct device_node *ports;
1606
1607                 ports = of_get_parent(prev);
1608                 if (!ports)
1609                         return NULL;
1610
1611                 do {
1612                         port = of_get_next_child(ports, prev);
1613                         if (!port) {
1614                                 of_node_put(ports);
1615                                 return NULL;
1616                         }
1617                         prev = port;
1618                 } while (!of_node_name_eq(port, "port"));
1619         }
1620
1621         return port;
1622 }
1623
1624 static struct device_node *
1625 of_get_next_endpoint(const struct device_node *parent,
1626                      struct device_node *prev)
1627 {
1628         struct device_node *ep = NULL;
1629
1630         if (!parent)
1631                 return NULL;
1632
1633         do {
1634                 ep = of_get_next_child(parent, prev);
1635                 if (!ep)
1636                         return NULL;
1637                 prev = ep;
1638         } while (!of_node_name_eq(ep, "endpoint"));
1639
1640         return ep;
1641 }
1642
1643 static int of_cal_create_instance(struct cal_ctx *ctx, int inst)
1644 {
1645         struct platform_device *pdev = ctx->dev->pdev;
1646         struct device_node *ep_node, *port, *sensor_node, *parent;
1647         struct v4l2_fwnode_endpoint *endpoint;
1648         struct v4l2_async_subdev *asd;
1649         u32 regval = 0;
1650         int ret, index, found_port = 0, lane;
1651
1652         parent = pdev->dev.of_node;
1653
1654         asd = &ctx->asd;
1655         endpoint = &ctx->endpoint;
1656
1657         ep_node = NULL;
1658         port = NULL;
1659         sensor_node = NULL;
1660         ret = -EINVAL;
1661
1662         ctx_dbg(3, ctx, "Scanning Port node for csi2 port: %d\n", inst);
1663         for (index = 0; index < CAL_NUM_CSI2_PORTS; index++) {
1664                 port = of_get_next_port(parent, port);
1665                 if (!port) {
1666                         ctx_dbg(1, ctx, "No port node found for csi2 port:%d\n",
1667                                 index);
1668                         goto cleanup_exit;
1669                 }
1670
1671                 /* Match the slice number with <REG> */
1672                 of_property_read_u32(port, "reg", &regval);
1673                 ctx_dbg(3, ctx, "port:%d inst:%d <reg>:%d\n",
1674                         index, inst, regval);
1675                 if ((regval == inst) && (index == inst)) {
1676                         found_port = 1;
1677                         break;
1678                 }
1679         }
1680
1681         if (!found_port) {
1682                 ctx_dbg(1, ctx, "No port node matches csi2 port:%d\n",
1683                         inst);
1684                 goto cleanup_exit;
1685         }
1686
1687         ctx_dbg(3, ctx, "Scanning sub-device for csi2 port: %d\n",
1688                 inst);
1689
1690         ep_node = of_get_next_endpoint(port, ep_node);
1691         if (!ep_node) {
1692                 ctx_dbg(3, ctx, "can't get next endpoint\n");
1693                 goto cleanup_exit;
1694         }
1695
1696         sensor_node = of_graph_get_remote_port_parent(ep_node);
1697         if (!sensor_node) {
1698                 ctx_dbg(3, ctx, "can't get remote parent\n");
1699                 goto cleanup_exit;
1700         }
1701         asd->match_type = V4L2_ASYNC_MATCH_FWNODE;
1702         asd->match.fwnode = of_fwnode_handle(sensor_node);
1703
1704         v4l2_fwnode_endpoint_parse(of_fwnode_handle(ep_node), endpoint);
1705
1706         if (endpoint->bus_type != V4L2_MBUS_CSI2_DPHY) {
1707                 ctx_err(ctx, "Port:%d sub-device %pOFn is not a CSI2 device\n",
1708                         inst, sensor_node);
1709                 goto cleanup_exit;
1710         }
1711
1712         /* Store Virtual Channel number */
1713         ctx->virtual_channel = endpoint->base.id;
1714
1715         ctx_dbg(3, ctx, "Port:%d v4l2-endpoint: CSI2\n", inst);
1716         ctx_dbg(3, ctx, "Virtual Channel=%d\n", ctx->virtual_channel);
1717         ctx_dbg(3, ctx, "flags=0x%08x\n", endpoint->bus.mipi_csi2.flags);
1718         ctx_dbg(3, ctx, "clock_lane=%d\n", endpoint->bus.mipi_csi2.clock_lane);
1719         ctx_dbg(3, ctx, "num_data_lanes=%d\n",
1720                 endpoint->bus.mipi_csi2.num_data_lanes);
1721         ctx_dbg(3, ctx, "data_lanes= <\n");
1722         for (lane = 0; lane < endpoint->bus.mipi_csi2.num_data_lanes; lane++)
1723                 ctx_dbg(3, ctx, "\t%d\n",
1724                         endpoint->bus.mipi_csi2.data_lanes[lane]);
1725         ctx_dbg(3, ctx, "\t>\n");
1726
1727         ctx_dbg(1, ctx, "Port: %d found sub-device %pOFn\n",
1728                 inst, sensor_node);
1729
1730         v4l2_async_notifier_init(&ctx->notifier);
1731
1732         ret = v4l2_async_notifier_add_subdev(&ctx->notifier, asd);
1733         if (ret) {
1734                 ctx_err(ctx, "Error adding asd\n");
1735                 goto cleanup_exit;
1736         }
1737
1738         ctx->notifier.ops = &cal_async_ops;
1739         ret = v4l2_async_notifier_register(&ctx->v4l2_dev,
1740                                            &ctx->notifier);
1741         if (ret) {
1742                 ctx_err(ctx, "Error registering async notifier\n");
1743                 v4l2_async_notifier_cleanup(&ctx->notifier);
1744                 ret = -EINVAL;
1745         }
1746
1747         /*
1748          * On success we need to keep reference on sensor_node, or
1749          * if notifier_cleanup was called above, sensor_node was
1750          * already put.
1751          */
1752         sensor_node = NULL;
1753
1754 cleanup_exit:
1755         of_node_put(sensor_node);
1756         of_node_put(ep_node);
1757         of_node_put(port);
1758
1759         return ret;
1760 }
1761
1762 static struct cal_ctx *cal_create_instance(struct cal_dev *dev, int inst)
1763 {
1764         struct cal_ctx *ctx;
1765         struct v4l2_ctrl_handler *hdl;
1766         int ret;
1767
1768         ctx = devm_kzalloc(&dev->pdev->dev, sizeof(*ctx), GFP_KERNEL);
1769         if (!ctx)
1770                 return NULL;
1771
1772         /* save the cal_dev * for future ref */
1773         ctx->dev = dev;
1774
1775         snprintf(ctx->v4l2_dev.name, sizeof(ctx->v4l2_dev.name),
1776                  "%s-%03d", CAL_MODULE_NAME, inst);
1777         ret = v4l2_device_register(&dev->pdev->dev, &ctx->v4l2_dev);
1778         if (ret)
1779                 goto err_exit;
1780
1781         hdl = &ctx->ctrl_handler;
1782         ret = v4l2_ctrl_handler_init(hdl, 11);
1783         if (ret) {
1784                 ctx_err(ctx, "Failed to init ctrl handler\n");
1785                 goto unreg_dev;
1786         }
1787         ctx->v4l2_dev.ctrl_handler = hdl;
1788
1789         /* Make sure Camera Core H/W register area is available */
1790         ctx->cc = dev->cc[inst];
1791
1792         /* Store the instance id */
1793         ctx->csi2_port = inst + 1;
1794
1795         ret = of_cal_create_instance(ctx, inst);
1796         if (ret) {
1797                 ret = -EINVAL;
1798                 goto free_hdl;
1799         }
1800         return ctx;
1801
1802 free_hdl:
1803         v4l2_ctrl_handler_free(hdl);
1804 unreg_dev:
1805         v4l2_device_unregister(&ctx->v4l2_dev);
1806 err_exit:
1807         return NULL;
1808 }
1809
1810 static int cal_probe(struct platform_device *pdev)
1811 {
1812         struct cal_dev *dev;
1813         struct cal_ctx *ctx;
1814         int ret;
1815         int irq;
1816         int i;
1817
1818         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
1819         if (!dev)
1820                 return -ENOMEM;
1821
1822         /* set pseudo v4l2 device name so we can use v4l2_printk */
1823         strscpy(dev->v4l2_dev.name, CAL_MODULE_NAME,
1824                 sizeof(dev->v4l2_dev.name));
1825
1826         /* save pdev pointer */
1827         dev->pdev = pdev;
1828
1829         dev->res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
1830                                                 "cal_top");
1831         dev->base = devm_ioremap_resource(&pdev->dev, dev->res);
1832         if (IS_ERR(dev->base))
1833                 return PTR_ERR(dev->base);
1834
1835         cal_dbg(1, dev, "ioresource %s at %pa - %pa\n",
1836                 dev->res->name, &dev->res->start, &dev->res->end);
1837
1838         irq = platform_get_irq(pdev, 0);
1839         cal_dbg(1, dev, "got irq# %d\n", irq);
1840         ret = devm_request_irq(&pdev->dev, irq, cal_irq, 0, CAL_MODULE_NAME,
1841                                dev);
1842         if (ret)
1843                 return ret;
1844
1845         platform_set_drvdata(pdev, dev);
1846
1847         dev->cm = cm_create(dev);
1848         if (IS_ERR(dev->cm))
1849                 return PTR_ERR(dev->cm);
1850
1851         dev->cc[0] = cc_create(dev, 0);
1852         if (IS_ERR(dev->cc[0]))
1853                 return PTR_ERR(dev->cc[0]);
1854
1855         dev->cc[1] = cc_create(dev, 1);
1856         if (IS_ERR(dev->cc[1]))
1857                 return PTR_ERR(dev->cc[1]);
1858
1859         dev->ctx[0] = NULL;
1860         dev->ctx[1] = NULL;
1861
1862         dev->ctx[0] = cal_create_instance(dev, 0);
1863         dev->ctx[1] = cal_create_instance(dev, 1);
1864         if (!dev->ctx[0] && !dev->ctx[1]) {
1865                 cal_err(dev, "Neither port is configured, no point in staying up\n");
1866                 return -ENODEV;
1867         }
1868
1869         pm_runtime_enable(&pdev->dev);
1870
1871         ret = cal_runtime_get(dev);
1872         if (ret)
1873                 goto runtime_disable;
1874
1875         /* Just check we can actually access the module */
1876         cal_get_hwinfo(dev);
1877
1878         cal_runtime_put(dev);
1879
1880         return 0;
1881
1882 runtime_disable:
1883         pm_runtime_disable(&pdev->dev);
1884         for (i = 0; i < CAL_NUM_CONTEXT; i++) {
1885                 ctx = dev->ctx[i];
1886                 if (ctx) {
1887                         v4l2_async_notifier_unregister(&ctx->notifier);
1888                         v4l2_async_notifier_cleanup(&ctx->notifier);
1889                         v4l2_ctrl_handler_free(&ctx->ctrl_handler);
1890                         v4l2_device_unregister(&ctx->v4l2_dev);
1891                 }
1892         }
1893
1894         return ret;
1895 }
1896
1897 static int cal_remove(struct platform_device *pdev)
1898 {
1899         struct cal_dev *dev =
1900                 (struct cal_dev *)platform_get_drvdata(pdev);
1901         struct cal_ctx *ctx;
1902         int i;
1903
1904         cal_dbg(1, dev, "Removing %s\n", CAL_MODULE_NAME);
1905
1906         cal_runtime_get(dev);
1907
1908         for (i = 0; i < CAL_NUM_CONTEXT; i++) {
1909                 ctx = dev->ctx[i];
1910                 if (ctx) {
1911                         ctx_dbg(1, ctx, "unregistering %s\n",
1912                                 video_device_node_name(&ctx->vdev));
1913                         camerarx_phy_disable(ctx);
1914                         v4l2_async_notifier_unregister(&ctx->notifier);
1915                         v4l2_async_notifier_cleanup(&ctx->notifier);
1916                         v4l2_ctrl_handler_free(&ctx->ctrl_handler);
1917                         v4l2_device_unregister(&ctx->v4l2_dev);
1918                         video_unregister_device(&ctx->vdev);
1919                 }
1920         }
1921
1922         cal_runtime_put(dev);
1923         pm_runtime_disable(&pdev->dev);
1924
1925         return 0;
1926 }
1927
1928 #if defined(CONFIG_OF)
1929 static const struct of_device_id cal_of_match[] = {
1930         { .compatible = "ti,dra72-cal", },
1931         {},
1932 };
1933 MODULE_DEVICE_TABLE(of, cal_of_match);
1934 #endif
1935
1936 static struct platform_driver cal_pdrv = {
1937         .probe          = cal_probe,
1938         .remove         = cal_remove,
1939         .driver         = {
1940                 .name   = CAL_MODULE_NAME,
1941                 .of_match_table = of_match_ptr(cal_of_match),
1942         },
1943 };
1944
1945 module_platform_driver(cal_pdrv);