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