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