8ed8b8a4840cfa94947331297d2b494bab674480
[platform/kernel/linux-starfive.git] / drivers / media / platform / atmel / atmel-isc-base.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Microchip Image Sensor Controller (ISC) common driver base
4  *
5  * Copyright (C) 2016-2019 Microchip Technology, Inc.
6  *
7  * Author: Songjun Wu
8  * Author: Eugen Hristev <eugen.hristev@microchip.com>
9  *
10  */
11
12 #include <linux/clk.h>
13 #include <linux/clkdev.h>
14 #include <linux/clk-provider.h>
15 #include <linux/delay.h>
16 #include <linux/interrupt.h>
17 #include <linux/math64.h>
18 #include <linux/module.h>
19 #include <linux/of.h>
20 #include <linux/of_graph.h>
21 #include <linux/platform_device.h>
22 #include <linux/pm_runtime.h>
23 #include <linux/regmap.h>
24 #include <linux/videodev2.h>
25 #include <linux/atmel-isc-media.h>
26
27 #include <media/v4l2-ctrls.h>
28 #include <media/v4l2-device.h>
29 #include <media/v4l2-event.h>
30 #include <media/v4l2-image-sizes.h>
31 #include <media/v4l2-ioctl.h>
32 #include <media/v4l2-fwnode.h>
33 #include <media/v4l2-subdev.h>
34 #include <media/videobuf2-dma-contig.h>
35
36 #include "atmel-isc-regs.h"
37 #include "atmel-isc.h"
38
39 static unsigned int debug;
40 module_param(debug, int, 0644);
41 MODULE_PARM_DESC(debug, "debug level (0-2)");
42
43 static unsigned int sensor_preferred = 1;
44 module_param(sensor_preferred, uint, 0644);
45 MODULE_PARM_DESC(sensor_preferred,
46                  "Sensor is preferred to output the specified format (1-on 0-off), default 1");
47
48 /* This is a list of the formats that the ISC can *output* */
49 const struct isc_format controller_formats[] = {
50         {
51                 .fourcc         = V4L2_PIX_FMT_ARGB444,
52         },
53         {
54                 .fourcc         = V4L2_PIX_FMT_ARGB555,
55         },
56         {
57                 .fourcc         = V4L2_PIX_FMT_RGB565,
58         },
59         {
60                 .fourcc         = V4L2_PIX_FMT_ABGR32,
61         },
62         {
63                 .fourcc         = V4L2_PIX_FMT_XBGR32,
64         },
65         {
66                 .fourcc         = V4L2_PIX_FMT_YUV420,
67         },
68         {
69                 .fourcc         = V4L2_PIX_FMT_YUYV,
70         },
71         {
72                 .fourcc         = V4L2_PIX_FMT_YUV422P,
73         },
74         {
75                 .fourcc         = V4L2_PIX_FMT_GREY,
76         },
77         {
78                 .fourcc         = V4L2_PIX_FMT_Y10,
79         },
80 };
81
82 /* This is a list of formats that the ISC can receive as *input* */
83 struct isc_format formats_list[] = {
84         {
85                 .fourcc         = V4L2_PIX_FMT_SBGGR8,
86                 .mbus_code      = MEDIA_BUS_FMT_SBGGR8_1X8,
87                 .pfe_cfg0_bps   = ISC_PFE_CFG0_BPS_EIGHT,
88                 .cfa_baycfg     = ISC_BAY_CFG_BGBG,
89         },
90         {
91                 .fourcc         = V4L2_PIX_FMT_SGBRG8,
92                 .mbus_code      = MEDIA_BUS_FMT_SGBRG8_1X8,
93                 .pfe_cfg0_bps   = ISC_PFE_CFG0_BPS_EIGHT,
94                 .cfa_baycfg     = ISC_BAY_CFG_GBGB,
95         },
96         {
97                 .fourcc         = V4L2_PIX_FMT_SGRBG8,
98                 .mbus_code      = MEDIA_BUS_FMT_SGRBG8_1X8,
99                 .pfe_cfg0_bps   = ISC_PFE_CFG0_BPS_EIGHT,
100                 .cfa_baycfg     = ISC_BAY_CFG_GRGR,
101         },
102         {
103                 .fourcc         = V4L2_PIX_FMT_SRGGB8,
104                 .mbus_code      = MEDIA_BUS_FMT_SRGGB8_1X8,
105                 .pfe_cfg0_bps   = ISC_PFE_CFG0_BPS_EIGHT,
106                 .cfa_baycfg     = ISC_BAY_CFG_RGRG,
107         },
108         {
109                 .fourcc         = V4L2_PIX_FMT_SBGGR10,
110                 .mbus_code      = MEDIA_BUS_FMT_SBGGR10_1X10,
111                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TEN,
112                 .cfa_baycfg     = ISC_BAY_CFG_RGRG,
113         },
114         {
115                 .fourcc         = V4L2_PIX_FMT_SGBRG10,
116                 .mbus_code      = MEDIA_BUS_FMT_SGBRG10_1X10,
117                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TEN,
118                 .cfa_baycfg     = ISC_BAY_CFG_GBGB,
119         },
120         {
121                 .fourcc         = V4L2_PIX_FMT_SGRBG10,
122                 .mbus_code      = MEDIA_BUS_FMT_SGRBG10_1X10,
123                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TEN,
124                 .cfa_baycfg     = ISC_BAY_CFG_GRGR,
125         },
126         {
127                 .fourcc         = V4L2_PIX_FMT_SRGGB10,
128                 .mbus_code      = MEDIA_BUS_FMT_SRGGB10_1X10,
129                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TEN,
130                 .cfa_baycfg     = ISC_BAY_CFG_RGRG,
131         },
132         {
133                 .fourcc         = V4L2_PIX_FMT_SBGGR12,
134                 .mbus_code      = MEDIA_BUS_FMT_SBGGR12_1X12,
135                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TWELVE,
136                 .cfa_baycfg     = ISC_BAY_CFG_BGBG,
137         },
138         {
139                 .fourcc         = V4L2_PIX_FMT_SGBRG12,
140                 .mbus_code      = MEDIA_BUS_FMT_SGBRG12_1X12,
141                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TWELVE,
142                 .cfa_baycfg     = ISC_BAY_CFG_GBGB,
143         },
144         {
145                 .fourcc         = V4L2_PIX_FMT_SGRBG12,
146                 .mbus_code      = MEDIA_BUS_FMT_SGRBG12_1X12,
147                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TWELVE,
148                 .cfa_baycfg     = ISC_BAY_CFG_GRGR,
149         },
150         {
151                 .fourcc         = V4L2_PIX_FMT_SRGGB12,
152                 .mbus_code      = MEDIA_BUS_FMT_SRGGB12_1X12,
153                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TWELVE,
154                 .cfa_baycfg     = ISC_BAY_CFG_RGRG,
155         },
156         {
157                 .fourcc         = V4L2_PIX_FMT_GREY,
158                 .mbus_code      = MEDIA_BUS_FMT_Y8_1X8,
159                 .pfe_cfg0_bps   = ISC_PFE_CFG0_BPS_EIGHT,
160         },
161         {
162                 .fourcc         = V4L2_PIX_FMT_YUYV,
163                 .mbus_code      = MEDIA_BUS_FMT_YUYV8_2X8,
164                 .pfe_cfg0_bps   = ISC_PFE_CFG0_BPS_EIGHT,
165         },
166         {
167                 .fourcc         = V4L2_PIX_FMT_RGB565,
168                 .mbus_code      = MEDIA_BUS_FMT_RGB565_2X8_LE,
169                 .pfe_cfg0_bps   = ISC_PFE_CFG0_BPS_EIGHT,
170         },
171         {
172                 .fourcc         = V4L2_PIX_FMT_Y10,
173                 .mbus_code      = MEDIA_BUS_FMT_Y10_1X10,
174                 .pfe_cfg0_bps   = ISC_PFG_CFG0_BPS_TEN,
175         },
176
177 };
178
179 #define ISC_IS_FORMAT_RAW(mbus_code) \
180         (((mbus_code) & 0xf000) == 0x3000)
181
182 #define ISC_IS_FORMAT_GREY(mbus_code) \
183         (((mbus_code) == MEDIA_BUS_FMT_Y10_1X10) | \
184         (((mbus_code) == MEDIA_BUS_FMT_Y8_1X8)))
185
186 static inline void isc_update_v4l2_ctrls(struct isc_device *isc)
187 {
188         struct isc_ctrls *ctrls = &isc->ctrls;
189
190         /* In here we set the v4l2 controls w.r.t. our pipeline config */
191         v4l2_ctrl_s_ctrl(isc->r_gain_ctrl, ctrls->gain[ISC_HIS_CFG_MODE_R]);
192         v4l2_ctrl_s_ctrl(isc->b_gain_ctrl, ctrls->gain[ISC_HIS_CFG_MODE_B]);
193         v4l2_ctrl_s_ctrl(isc->gr_gain_ctrl, ctrls->gain[ISC_HIS_CFG_MODE_GR]);
194         v4l2_ctrl_s_ctrl(isc->gb_gain_ctrl, ctrls->gain[ISC_HIS_CFG_MODE_GB]);
195
196         v4l2_ctrl_s_ctrl(isc->r_off_ctrl, ctrls->offset[ISC_HIS_CFG_MODE_R]);
197         v4l2_ctrl_s_ctrl(isc->b_off_ctrl, ctrls->offset[ISC_HIS_CFG_MODE_B]);
198         v4l2_ctrl_s_ctrl(isc->gr_off_ctrl, ctrls->offset[ISC_HIS_CFG_MODE_GR]);
199         v4l2_ctrl_s_ctrl(isc->gb_off_ctrl, ctrls->offset[ISC_HIS_CFG_MODE_GB]);
200 }
201
202 static inline void isc_update_awb_ctrls(struct isc_device *isc)
203 {
204         struct isc_ctrls *ctrls = &isc->ctrls;
205
206         /* In here we set our actual hw pipeline config */
207
208         regmap_write(isc->regmap, ISC_WB_O_RGR,
209                      ((ctrls->offset[ISC_HIS_CFG_MODE_R])) |
210                      ((ctrls->offset[ISC_HIS_CFG_MODE_GR]) << 16));
211         regmap_write(isc->regmap, ISC_WB_O_BGB,
212                      ((ctrls->offset[ISC_HIS_CFG_MODE_B])) |
213                      ((ctrls->offset[ISC_HIS_CFG_MODE_GB]) << 16));
214         regmap_write(isc->regmap, ISC_WB_G_RGR,
215                      ctrls->gain[ISC_HIS_CFG_MODE_R] |
216                      (ctrls->gain[ISC_HIS_CFG_MODE_GR] << 16));
217         regmap_write(isc->regmap, ISC_WB_G_BGB,
218                      ctrls->gain[ISC_HIS_CFG_MODE_B] |
219                      (ctrls->gain[ISC_HIS_CFG_MODE_GB] << 16));
220 }
221
222 static inline void isc_reset_awb_ctrls(struct isc_device *isc)
223 {
224         unsigned int c;
225
226         for (c = ISC_HIS_CFG_MODE_GR; c <= ISC_HIS_CFG_MODE_B; c++) {
227                 /* gains have a fixed point at 9 decimals */
228                 isc->ctrls.gain[c] = 1 << 9;
229                 /* offsets are in 2's complements */
230                 isc->ctrls.offset[c] = 0;
231         }
232 }
233
234 static int isc_wait_clk_stable(struct clk_hw *hw)
235 {
236         struct isc_clk *isc_clk = to_isc_clk(hw);
237         struct regmap *regmap = isc_clk->regmap;
238         unsigned long timeout = jiffies + usecs_to_jiffies(1000);
239         unsigned int status;
240
241         while (time_before(jiffies, timeout)) {
242                 regmap_read(regmap, ISC_CLKSR, &status);
243                 if (!(status & ISC_CLKSR_SIP))
244                         return 0;
245
246                 usleep_range(10, 250);
247         }
248
249         return -ETIMEDOUT;
250 }
251
252 static int isc_clk_prepare(struct clk_hw *hw)
253 {
254         struct isc_clk *isc_clk = to_isc_clk(hw);
255         int ret;
256
257         if (isc_clk->id == ISC_ISPCK) {
258                 ret = pm_runtime_resume_and_get(isc_clk->dev);
259                 if (ret < 0)
260                         return ret;
261         }
262
263         return isc_wait_clk_stable(hw);
264 }
265
266 static void isc_clk_unprepare(struct clk_hw *hw)
267 {
268         struct isc_clk *isc_clk = to_isc_clk(hw);
269
270         isc_wait_clk_stable(hw);
271
272         if (isc_clk->id == ISC_ISPCK)
273                 pm_runtime_put_sync(isc_clk->dev);
274 }
275
276 static int isc_clk_enable(struct clk_hw *hw)
277 {
278         struct isc_clk *isc_clk = to_isc_clk(hw);
279         u32 id = isc_clk->id;
280         struct regmap *regmap = isc_clk->regmap;
281         unsigned long flags;
282         unsigned int status;
283
284         dev_dbg(isc_clk->dev, "ISC CLK: %s, id = %d, div = %d, parent id = %d\n",
285                 __func__, id, isc_clk->div, isc_clk->parent_id);
286
287         spin_lock_irqsave(&isc_clk->lock, flags);
288         regmap_update_bits(regmap, ISC_CLKCFG,
289                            ISC_CLKCFG_DIV_MASK(id) | ISC_CLKCFG_SEL_MASK(id),
290                            (isc_clk->div << ISC_CLKCFG_DIV_SHIFT(id)) |
291                            (isc_clk->parent_id << ISC_CLKCFG_SEL_SHIFT(id)));
292
293         regmap_write(regmap, ISC_CLKEN, ISC_CLK(id));
294         spin_unlock_irqrestore(&isc_clk->lock, flags);
295
296         regmap_read(regmap, ISC_CLKSR, &status);
297         if (status & ISC_CLK(id))
298                 return 0;
299         else
300                 return -EINVAL;
301 }
302
303 static void isc_clk_disable(struct clk_hw *hw)
304 {
305         struct isc_clk *isc_clk = to_isc_clk(hw);
306         u32 id = isc_clk->id;
307         unsigned long flags;
308
309         spin_lock_irqsave(&isc_clk->lock, flags);
310         regmap_write(isc_clk->regmap, ISC_CLKDIS, ISC_CLK(id));
311         spin_unlock_irqrestore(&isc_clk->lock, flags);
312 }
313
314 static int isc_clk_is_enabled(struct clk_hw *hw)
315 {
316         struct isc_clk *isc_clk = to_isc_clk(hw);
317         u32 status;
318         int ret;
319
320         if (isc_clk->id == ISC_ISPCK) {
321                 ret = pm_runtime_resume_and_get(isc_clk->dev);
322                 if (ret < 0)
323                         return 0;
324         }
325
326         regmap_read(isc_clk->regmap, ISC_CLKSR, &status);
327
328         if (isc_clk->id == ISC_ISPCK)
329                 pm_runtime_put_sync(isc_clk->dev);
330
331         return status & ISC_CLK(isc_clk->id) ? 1 : 0;
332 }
333
334 static unsigned long
335 isc_clk_recalc_rate(struct clk_hw *hw, unsigned long parent_rate)
336 {
337         struct isc_clk *isc_clk = to_isc_clk(hw);
338
339         return DIV_ROUND_CLOSEST(parent_rate, isc_clk->div + 1);
340 }
341
342 static int isc_clk_determine_rate(struct clk_hw *hw,
343                                    struct clk_rate_request *req)
344 {
345         struct isc_clk *isc_clk = to_isc_clk(hw);
346         long best_rate = -EINVAL;
347         int best_diff = -1;
348         unsigned int i, div;
349
350         for (i = 0; i < clk_hw_get_num_parents(hw); i++) {
351                 struct clk_hw *parent;
352                 unsigned long parent_rate;
353
354                 parent = clk_hw_get_parent_by_index(hw, i);
355                 if (!parent)
356                         continue;
357
358                 parent_rate = clk_hw_get_rate(parent);
359                 if (!parent_rate)
360                         continue;
361
362                 for (div = 1; div < ISC_CLK_MAX_DIV + 2; div++) {
363                         unsigned long rate;
364                         int diff;
365
366                         rate = DIV_ROUND_CLOSEST(parent_rate, div);
367                         diff = abs(req->rate - rate);
368
369                         if (best_diff < 0 || best_diff > diff) {
370                                 best_rate = rate;
371                                 best_diff = diff;
372                                 req->best_parent_rate = parent_rate;
373                                 req->best_parent_hw = parent;
374                         }
375
376                         if (!best_diff || rate < req->rate)
377                                 break;
378                 }
379
380                 if (!best_diff)
381                         break;
382         }
383
384         dev_dbg(isc_clk->dev,
385                 "ISC CLK: %s, best_rate = %ld, parent clk: %s @ %ld\n",
386                 __func__, best_rate,
387                 __clk_get_name((req->best_parent_hw)->clk),
388                 req->best_parent_rate);
389
390         if (best_rate < 0)
391                 return best_rate;
392
393         req->rate = best_rate;
394
395         return 0;
396 }
397
398 static int isc_clk_set_parent(struct clk_hw *hw, u8 index)
399 {
400         struct isc_clk *isc_clk = to_isc_clk(hw);
401
402         if (index >= clk_hw_get_num_parents(hw))
403                 return -EINVAL;
404
405         isc_clk->parent_id = index;
406
407         return 0;
408 }
409
410 static u8 isc_clk_get_parent(struct clk_hw *hw)
411 {
412         struct isc_clk *isc_clk = to_isc_clk(hw);
413
414         return isc_clk->parent_id;
415 }
416
417 static int isc_clk_set_rate(struct clk_hw *hw,
418                              unsigned long rate,
419                              unsigned long parent_rate)
420 {
421         struct isc_clk *isc_clk = to_isc_clk(hw);
422         u32 div;
423
424         if (!rate)
425                 return -EINVAL;
426
427         div = DIV_ROUND_CLOSEST(parent_rate, rate);
428         if (div > (ISC_CLK_MAX_DIV + 1) || !div)
429                 return -EINVAL;
430
431         isc_clk->div = div - 1;
432
433         return 0;
434 }
435
436 static const struct clk_ops isc_clk_ops = {
437         .prepare        = isc_clk_prepare,
438         .unprepare      = isc_clk_unprepare,
439         .enable         = isc_clk_enable,
440         .disable        = isc_clk_disable,
441         .is_enabled     = isc_clk_is_enabled,
442         .recalc_rate    = isc_clk_recalc_rate,
443         .determine_rate = isc_clk_determine_rate,
444         .set_parent     = isc_clk_set_parent,
445         .get_parent     = isc_clk_get_parent,
446         .set_rate       = isc_clk_set_rate,
447 };
448
449 static int isc_clk_register(struct isc_device *isc, unsigned int id)
450 {
451         struct regmap *regmap = isc->regmap;
452         struct device_node *np = isc->dev->of_node;
453         struct isc_clk *isc_clk;
454         struct clk_init_data init;
455         const char *clk_name = np->name;
456         const char *parent_names[3];
457         int num_parents;
458
459         num_parents = of_clk_get_parent_count(np);
460         if (num_parents < 1 || num_parents > 3)
461                 return -EINVAL;
462
463         if (num_parents > 2 && id == ISC_ISPCK)
464                 num_parents = 2;
465
466         of_clk_parent_fill(np, parent_names, num_parents);
467
468         if (id == ISC_MCK)
469                 of_property_read_string(np, "clock-output-names", &clk_name);
470         else
471                 clk_name = "isc-ispck";
472
473         init.parent_names       = parent_names;
474         init.num_parents        = num_parents;
475         init.name               = clk_name;
476         init.ops                = &isc_clk_ops;
477         init.flags              = CLK_SET_RATE_GATE | CLK_SET_PARENT_GATE;
478
479         isc_clk = &isc->isc_clks[id];
480         isc_clk->hw.init        = &init;
481         isc_clk->regmap         = regmap;
482         isc_clk->id             = id;
483         isc_clk->dev            = isc->dev;
484         spin_lock_init(&isc_clk->lock);
485
486         isc_clk->clk = clk_register(isc->dev, &isc_clk->hw);
487         if (IS_ERR(isc_clk->clk)) {
488                 dev_err(isc->dev, "%s: clock register fail\n", clk_name);
489                 return PTR_ERR(isc_clk->clk);
490         } else if (id == ISC_MCK)
491                 of_clk_add_provider(np, of_clk_src_simple_get, isc_clk->clk);
492
493         return 0;
494 }
495
496 int isc_clk_init(struct isc_device *isc)
497 {
498         unsigned int i;
499         int ret;
500
501         for (i = 0; i < ARRAY_SIZE(isc->isc_clks); i++)
502                 isc->isc_clks[i].clk = ERR_PTR(-EINVAL);
503
504         for (i = 0; i < ARRAY_SIZE(isc->isc_clks); i++) {
505                 ret = isc_clk_register(isc, i);
506                 if (ret)
507                         return ret;
508         }
509
510         return 0;
511 }
512
513 void isc_clk_cleanup(struct isc_device *isc)
514 {
515         unsigned int i;
516
517         of_clk_del_provider(isc->dev->of_node);
518
519         for (i = 0; i < ARRAY_SIZE(isc->isc_clks); i++) {
520                 struct isc_clk *isc_clk = &isc->isc_clks[i];
521
522                 if (!IS_ERR(isc_clk->clk))
523                         clk_unregister(isc_clk->clk);
524         }
525 }
526
527 static int isc_queue_setup(struct vb2_queue *vq,
528                             unsigned int *nbuffers, unsigned int *nplanes,
529                             unsigned int sizes[], struct device *alloc_devs[])
530 {
531         struct isc_device *isc = vb2_get_drv_priv(vq);
532         unsigned int size = isc->fmt.fmt.pix.sizeimage;
533
534         if (*nplanes)
535                 return sizes[0] < size ? -EINVAL : 0;
536
537         *nplanes = 1;
538         sizes[0] = size;
539
540         return 0;
541 }
542
543 static int isc_buffer_prepare(struct vb2_buffer *vb)
544 {
545         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
546         struct isc_device *isc = vb2_get_drv_priv(vb->vb2_queue);
547         unsigned long size = isc->fmt.fmt.pix.sizeimage;
548
549         if (vb2_plane_size(vb, 0) < size) {
550                 v4l2_err(&isc->v4l2_dev, "buffer too small (%lu < %lu)\n",
551                          vb2_plane_size(vb, 0), size);
552                 return -EINVAL;
553         }
554
555         vb2_set_plane_payload(vb, 0, size);
556
557         vbuf->field = isc->fmt.fmt.pix.field;
558
559         return 0;
560 }
561
562 static void isc_start_dma(struct isc_device *isc)
563 {
564         struct regmap *regmap = isc->regmap;
565         u32 sizeimage = isc->fmt.fmt.pix.sizeimage;
566         u32 dctrl_dview;
567         dma_addr_t addr0;
568         u32 h, w;
569
570         h = isc->fmt.fmt.pix.height;
571         w = isc->fmt.fmt.pix.width;
572
573         /*
574          * In case the sensor is not RAW, it will output a pixel (12-16 bits)
575          * with two samples on the ISC Data bus (which is 8-12)
576          * ISC will count each sample, so, we need to multiply these values
577          * by two, to get the real number of samples for the required pixels.
578          */
579         if (!ISC_IS_FORMAT_RAW(isc->config.sd_format->mbus_code)) {
580                 h <<= 1;
581                 w <<= 1;
582         }
583
584         /*
585          * We limit the column/row count that the ISC will output according
586          * to the configured resolution that we want.
587          * This will avoid the situation where the sensor is misconfigured,
588          * sending more data, and the ISC will just take it and DMA to memory,
589          * causing corruption.
590          */
591         regmap_write(regmap, ISC_PFE_CFG1,
592                      (ISC_PFE_CFG1_COLMIN(0) & ISC_PFE_CFG1_COLMIN_MASK) |
593                      (ISC_PFE_CFG1_COLMAX(w - 1) & ISC_PFE_CFG1_COLMAX_MASK));
594
595         regmap_write(regmap, ISC_PFE_CFG2,
596                      (ISC_PFE_CFG2_ROWMIN(0) & ISC_PFE_CFG2_ROWMIN_MASK) |
597                      (ISC_PFE_CFG2_ROWMAX(h - 1) & ISC_PFE_CFG2_ROWMAX_MASK));
598
599         regmap_update_bits(regmap, ISC_PFE_CFG0,
600                            ISC_PFE_CFG0_COLEN | ISC_PFE_CFG0_ROWEN,
601                            ISC_PFE_CFG0_COLEN | ISC_PFE_CFG0_ROWEN);
602
603         addr0 = vb2_dma_contig_plane_dma_addr(&isc->cur_frm->vb.vb2_buf, 0);
604         regmap_write(regmap, ISC_DAD0 + isc->offsets.dma, addr0);
605
606         switch (isc->config.fourcc) {
607         case V4L2_PIX_FMT_YUV420:
608                 regmap_write(regmap, ISC_DAD1 + isc->offsets.dma,
609                              addr0 + (sizeimage * 2) / 3);
610                 regmap_write(regmap, ISC_DAD2 + isc->offsets.dma,
611                              addr0 + (sizeimage * 5) / 6);
612                 break;
613         case V4L2_PIX_FMT_YUV422P:
614                 regmap_write(regmap, ISC_DAD1 + isc->offsets.dma,
615                              addr0 + sizeimage / 2);
616                 regmap_write(regmap, ISC_DAD2 + isc->offsets.dma,
617                              addr0 + (sizeimage * 3) / 4);
618                 break;
619         default:
620                 break;
621         }
622
623         dctrl_dview = isc->config.dctrl_dview;
624
625         regmap_write(regmap, ISC_DCTRL + isc->offsets.dma,
626                      dctrl_dview | ISC_DCTRL_IE_IS);
627         spin_lock(&isc->awb_lock);
628         regmap_write(regmap, ISC_CTRLEN, ISC_CTRL_CAPTURE);
629         spin_unlock(&isc->awb_lock);
630 }
631
632 static void isc_set_pipeline(struct isc_device *isc, u32 pipeline)
633 {
634         struct regmap *regmap = isc->regmap;
635         struct isc_ctrls *ctrls = &isc->ctrls;
636         u32 val, bay_cfg;
637         const u32 *gamma;
638         unsigned int i;
639
640         /* WB-->CFA-->CC-->GAM-->CSC-->CBC-->SUB422-->SUB420 */
641         for (i = 0; i < ISC_PIPE_LINE_NODE_NUM; i++) {
642                 val = pipeline & BIT(i) ? 1 : 0;
643                 regmap_field_write(isc->pipeline[i], val);
644         }
645
646         if (!pipeline)
647                 return;
648
649         bay_cfg = isc->config.sd_format->cfa_baycfg;
650
651         regmap_write(regmap, ISC_WB_CFG, bay_cfg);
652         isc_update_awb_ctrls(isc);
653         isc_update_v4l2_ctrls(isc);
654
655         regmap_write(regmap, ISC_CFA_CFG, bay_cfg | ISC_CFA_CFG_EITPOL);
656
657         gamma = &isc->gamma_table[ctrls->gamma_index][0];
658         regmap_bulk_write(regmap, ISC_GAM_BENTRY, gamma, GAMMA_ENTRIES);
659         regmap_bulk_write(regmap, ISC_GAM_GENTRY, gamma, GAMMA_ENTRIES);
660         regmap_bulk_write(regmap, ISC_GAM_RENTRY, gamma, GAMMA_ENTRIES);
661
662         isc->config_csc(isc);
663         isc->config_cbc(isc);
664         isc->config_cc(isc);
665 }
666
667 static int isc_update_profile(struct isc_device *isc)
668 {
669         struct regmap *regmap = isc->regmap;
670         u32 sr;
671         int counter = 100;
672
673         regmap_write(regmap, ISC_CTRLEN, ISC_CTRL_UPPRO);
674
675         regmap_read(regmap, ISC_CTRLSR, &sr);
676         while ((sr & ISC_CTRL_UPPRO) && counter--) {
677                 usleep_range(1000, 2000);
678                 regmap_read(regmap, ISC_CTRLSR, &sr);
679         }
680
681         if (counter < 0) {
682                 v4l2_warn(&isc->v4l2_dev, "Time out to update profile\n");
683                 return -ETIMEDOUT;
684         }
685
686         return 0;
687 }
688
689 static void isc_set_histogram(struct isc_device *isc, bool enable)
690 {
691         struct regmap *regmap = isc->regmap;
692         struct isc_ctrls *ctrls = &isc->ctrls;
693
694         if (enable) {
695                 regmap_write(regmap, ISC_HIS_CFG + isc->offsets.his,
696                              ISC_HIS_CFG_MODE_GR |
697                              (isc->config.sd_format->cfa_baycfg
698                                         << ISC_HIS_CFG_BAYSEL_SHIFT) |
699                                         ISC_HIS_CFG_RAR);
700                 regmap_write(regmap, ISC_HIS_CTRL + isc->offsets.his,
701                              ISC_HIS_CTRL_EN);
702                 regmap_write(regmap, ISC_INTEN, ISC_INT_HISDONE);
703                 ctrls->hist_id = ISC_HIS_CFG_MODE_GR;
704                 isc_update_profile(isc);
705                 regmap_write(regmap, ISC_CTRLEN, ISC_CTRL_HISREQ);
706
707                 ctrls->hist_stat = HIST_ENABLED;
708         } else {
709                 regmap_write(regmap, ISC_INTDIS, ISC_INT_HISDONE);
710                 regmap_write(regmap, ISC_HIS_CTRL + isc->offsets.his,
711                              ISC_HIS_CTRL_DIS);
712
713                 ctrls->hist_stat = HIST_DISABLED;
714         }
715 }
716
717 static int isc_configure(struct isc_device *isc)
718 {
719         struct regmap *regmap = isc->regmap;
720         u32 pfe_cfg0, rlp_mode, dcfg, mask, pipeline;
721         struct isc_subdev_entity *subdev = isc->current_subdev;
722
723         pfe_cfg0 = isc->config.sd_format->pfe_cfg0_bps;
724         rlp_mode = isc->config.rlp_cfg_mode;
725         pipeline = isc->config.bits_pipeline;
726
727         dcfg = isc->config.dcfg_imode | isc->dcfg;
728
729         pfe_cfg0  |= subdev->pfe_cfg0 | ISC_PFE_CFG0_MODE_PROGRESSIVE;
730         mask = ISC_PFE_CFG0_BPS_MASK | ISC_PFE_CFG0_HPOL_LOW |
731                ISC_PFE_CFG0_VPOL_LOW | ISC_PFE_CFG0_PPOL_LOW |
732                ISC_PFE_CFG0_MODE_MASK | ISC_PFE_CFG0_CCIR_CRC |
733                    ISC_PFE_CFG0_CCIR656;
734
735         regmap_update_bits(regmap, ISC_PFE_CFG0, mask, pfe_cfg0);
736
737         regmap_update_bits(regmap, ISC_RLP_CFG + isc->offsets.rlp,
738                            ISC_RLP_CFG_MODE_MASK, rlp_mode);
739
740         regmap_write(regmap, ISC_DCFG + isc->offsets.dma, dcfg);
741
742         /* Set the pipeline */
743         isc_set_pipeline(isc, pipeline);
744
745         /*
746          * The current implemented histogram is available for RAW R, B, GB, GR
747          * channels. We need to check if sensor is outputting RAW BAYER
748          */
749         if (isc->ctrls.awb &&
750             ISC_IS_FORMAT_RAW(isc->config.sd_format->mbus_code))
751                 isc_set_histogram(isc, true);
752         else
753                 isc_set_histogram(isc, false);
754
755         /* Update profile */
756         return isc_update_profile(isc);
757 }
758
759 static int isc_start_streaming(struct vb2_queue *vq, unsigned int count)
760 {
761         struct isc_device *isc = vb2_get_drv_priv(vq);
762         struct regmap *regmap = isc->regmap;
763         struct isc_buffer *buf;
764         unsigned long flags;
765         int ret;
766
767         /* Enable stream on the sub device */
768         ret = v4l2_subdev_call(isc->current_subdev->sd, video, s_stream, 1);
769         if (ret && ret != -ENOIOCTLCMD) {
770                 v4l2_err(&isc->v4l2_dev, "stream on failed in subdev %d\n",
771                          ret);
772                 goto err_start_stream;
773         }
774
775         ret = pm_runtime_resume_and_get(isc->dev);
776         if (ret < 0) {
777                 v4l2_err(&isc->v4l2_dev, "RPM resume failed in subdev %d\n",
778                          ret);
779                 goto err_pm_get;
780         }
781
782         ret = isc_configure(isc);
783         if (unlikely(ret))
784                 goto err_configure;
785
786         /* Enable DMA interrupt */
787         regmap_write(regmap, ISC_INTEN, ISC_INT_DDONE);
788
789         spin_lock_irqsave(&isc->dma_queue_lock, flags);
790
791         isc->sequence = 0;
792         isc->stop = false;
793         reinit_completion(&isc->comp);
794
795         isc->cur_frm = list_first_entry(&isc->dma_queue,
796                                         struct isc_buffer, list);
797         list_del(&isc->cur_frm->list);
798
799         isc_start_dma(isc);
800
801         spin_unlock_irqrestore(&isc->dma_queue_lock, flags);
802
803         /* if we streaming from RAW, we can do one-shot white balance adj */
804         if (ISC_IS_FORMAT_RAW(isc->config.sd_format->mbus_code))
805                 v4l2_ctrl_activate(isc->do_wb_ctrl, true);
806
807         return 0;
808
809 err_configure:
810         pm_runtime_put_sync(isc->dev);
811 err_pm_get:
812         v4l2_subdev_call(isc->current_subdev->sd, video, s_stream, 0);
813
814 err_start_stream:
815         spin_lock_irqsave(&isc->dma_queue_lock, flags);
816         list_for_each_entry(buf, &isc->dma_queue, list)
817                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED);
818         INIT_LIST_HEAD(&isc->dma_queue);
819         spin_unlock_irqrestore(&isc->dma_queue_lock, flags);
820
821         return ret;
822 }
823
824 static void isc_stop_streaming(struct vb2_queue *vq)
825 {
826         struct isc_device *isc = vb2_get_drv_priv(vq);
827         unsigned long flags;
828         struct isc_buffer *buf;
829         int ret;
830
831         v4l2_ctrl_activate(isc->do_wb_ctrl, false);
832
833         isc->stop = true;
834
835         /* Wait until the end of the current frame */
836         if (isc->cur_frm && !wait_for_completion_timeout(&isc->comp, 5 * HZ))
837                 v4l2_err(&isc->v4l2_dev,
838                          "Timeout waiting for end of the capture\n");
839
840         /* Disable DMA interrupt */
841         regmap_write(isc->regmap, ISC_INTDIS, ISC_INT_DDONE);
842
843         pm_runtime_put_sync(isc->dev);
844
845         /* Disable stream on the sub device */
846         ret = v4l2_subdev_call(isc->current_subdev->sd, video, s_stream, 0);
847         if (ret && ret != -ENOIOCTLCMD)
848                 v4l2_err(&isc->v4l2_dev, "stream off failed in subdev\n");
849
850         /* Release all active buffers */
851         spin_lock_irqsave(&isc->dma_queue_lock, flags);
852         if (unlikely(isc->cur_frm)) {
853                 vb2_buffer_done(&isc->cur_frm->vb.vb2_buf,
854                                 VB2_BUF_STATE_ERROR);
855                 isc->cur_frm = NULL;
856         }
857         list_for_each_entry(buf, &isc->dma_queue, list)
858                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
859         INIT_LIST_HEAD(&isc->dma_queue);
860         spin_unlock_irqrestore(&isc->dma_queue_lock, flags);
861 }
862
863 static void isc_buffer_queue(struct vb2_buffer *vb)
864 {
865         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
866         struct isc_buffer *buf = container_of(vbuf, struct isc_buffer, vb);
867         struct isc_device *isc = vb2_get_drv_priv(vb->vb2_queue);
868         unsigned long flags;
869
870         spin_lock_irqsave(&isc->dma_queue_lock, flags);
871         if (!isc->cur_frm && list_empty(&isc->dma_queue) &&
872                 vb2_is_streaming(vb->vb2_queue)) {
873                 isc->cur_frm = buf;
874                 isc_start_dma(isc);
875         } else
876                 list_add_tail(&buf->list, &isc->dma_queue);
877         spin_unlock_irqrestore(&isc->dma_queue_lock, flags);
878 }
879
880 static struct isc_format *find_format_by_fourcc(struct isc_device *isc,
881                                                  unsigned int fourcc)
882 {
883         unsigned int num_formats = isc->num_user_formats;
884         struct isc_format *fmt;
885         unsigned int i;
886
887         for (i = 0; i < num_formats; i++) {
888                 fmt = isc->user_formats[i];
889                 if (fmt->fourcc == fourcc)
890                         return fmt;
891         }
892
893         return NULL;
894 }
895
896 static const struct vb2_ops isc_vb2_ops = {
897         .queue_setup            = isc_queue_setup,
898         .wait_prepare           = vb2_ops_wait_prepare,
899         .wait_finish            = vb2_ops_wait_finish,
900         .buf_prepare            = isc_buffer_prepare,
901         .start_streaming        = isc_start_streaming,
902         .stop_streaming         = isc_stop_streaming,
903         .buf_queue              = isc_buffer_queue,
904 };
905
906 static int isc_querycap(struct file *file, void *priv,
907                          struct v4l2_capability *cap)
908 {
909         struct isc_device *isc = video_drvdata(file);
910
911         strscpy(cap->driver, "microchip-isc", sizeof(cap->driver));
912         strscpy(cap->card, "Atmel Image Sensor Controller", sizeof(cap->card));
913         snprintf(cap->bus_info, sizeof(cap->bus_info),
914                  "platform:%s", isc->v4l2_dev.name);
915
916         return 0;
917 }
918
919 static int isc_enum_fmt_vid_cap(struct file *file, void *priv,
920                                  struct v4l2_fmtdesc *f)
921 {
922         u32 index = f->index;
923         u32 i, supported_index;
924
925         if (index < ARRAY_SIZE(controller_formats)) {
926                 f->pixelformat = controller_formats[index].fourcc;
927                 return 0;
928         }
929
930         index -= ARRAY_SIZE(controller_formats);
931
932         supported_index = 0;
933
934         for (i = 0; i < ARRAY_SIZE(formats_list); i++) {
935                 if (!ISC_IS_FORMAT_RAW(formats_list[i].mbus_code) ||
936                     !formats_list[i].sd_support)
937                         continue;
938                 if (supported_index == index) {
939                         f->pixelformat = formats_list[i].fourcc;
940                         return 0;
941                 }
942                 supported_index++;
943         }
944
945         return -EINVAL;
946 }
947
948 static int isc_g_fmt_vid_cap(struct file *file, void *priv,
949                               struct v4l2_format *fmt)
950 {
951         struct isc_device *isc = video_drvdata(file);
952
953         *fmt = isc->fmt;
954
955         return 0;
956 }
957
958 /*
959  * Checks the current configured format, if ISC can output it,
960  * considering which type of format the ISC receives from the sensor
961  */
962 static int isc_try_validate_formats(struct isc_device *isc)
963 {
964         int ret;
965         bool bayer = false, yuv = false, rgb = false, grey = false;
966
967         /* all formats supported by the RLP module are OK */
968         switch (isc->try_config.fourcc) {
969         case V4L2_PIX_FMT_SBGGR8:
970         case V4L2_PIX_FMT_SGBRG8:
971         case V4L2_PIX_FMT_SGRBG8:
972         case V4L2_PIX_FMT_SRGGB8:
973         case V4L2_PIX_FMT_SBGGR10:
974         case V4L2_PIX_FMT_SGBRG10:
975         case V4L2_PIX_FMT_SGRBG10:
976         case V4L2_PIX_FMT_SRGGB10:
977         case V4L2_PIX_FMT_SBGGR12:
978         case V4L2_PIX_FMT_SGBRG12:
979         case V4L2_PIX_FMT_SGRBG12:
980         case V4L2_PIX_FMT_SRGGB12:
981                 ret = 0;
982                 bayer = true;
983                 break;
984
985         case V4L2_PIX_FMT_YUV420:
986         case V4L2_PIX_FMT_YUV422P:
987         case V4L2_PIX_FMT_YUYV:
988                 ret = 0;
989                 yuv = true;
990                 break;
991
992         case V4L2_PIX_FMT_RGB565:
993         case V4L2_PIX_FMT_ABGR32:
994         case V4L2_PIX_FMT_XBGR32:
995         case V4L2_PIX_FMT_ARGB444:
996         case V4L2_PIX_FMT_ARGB555:
997                 ret = 0;
998                 rgb = true;
999                 break;
1000         case V4L2_PIX_FMT_GREY:
1001         case V4L2_PIX_FMT_Y10:
1002                 ret = 0;
1003                 grey = true;
1004                 break;
1005         default:
1006         /* any other different formats are not supported */
1007                 ret = -EINVAL;
1008         }
1009         v4l2_dbg(1, debug, &isc->v4l2_dev,
1010                  "Format validation, requested rgb=%u, yuv=%u, grey=%u, bayer=%u\n",
1011                  rgb, yuv, grey, bayer);
1012
1013         /* we cannot output RAW if we do not receive RAW */
1014         if ((bayer) && !ISC_IS_FORMAT_RAW(isc->try_config.sd_format->mbus_code))
1015                 return -EINVAL;
1016
1017         /* we cannot output GREY if we do not receive RAW/GREY */
1018         if (grey && !ISC_IS_FORMAT_RAW(isc->try_config.sd_format->mbus_code) &&
1019             !ISC_IS_FORMAT_GREY(isc->try_config.sd_format->mbus_code))
1020                 return -EINVAL;
1021
1022         return ret;
1023 }
1024
1025 /*
1026  * Configures the RLP and DMA modules, depending on the output format
1027  * configured for the ISC.
1028  * If direct_dump == true, just dump raw data 8/16 bits depending on format.
1029  */
1030 static int isc_try_configure_rlp_dma(struct isc_device *isc, bool direct_dump)
1031 {
1032         switch (isc->try_config.fourcc) {
1033         case V4L2_PIX_FMT_SBGGR8:
1034         case V4L2_PIX_FMT_SGBRG8:
1035         case V4L2_PIX_FMT_SGRBG8:
1036         case V4L2_PIX_FMT_SRGGB8:
1037                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_DAT8;
1038                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED8;
1039                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1040                 isc->try_config.bpp = 8;
1041                 break;
1042         case V4L2_PIX_FMT_SBGGR10:
1043         case V4L2_PIX_FMT_SGBRG10:
1044         case V4L2_PIX_FMT_SGRBG10:
1045         case V4L2_PIX_FMT_SRGGB10:
1046                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_DAT10;
1047                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED16;
1048                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1049                 isc->try_config.bpp = 16;
1050                 break;
1051         case V4L2_PIX_FMT_SBGGR12:
1052         case V4L2_PIX_FMT_SGBRG12:
1053         case V4L2_PIX_FMT_SGRBG12:
1054         case V4L2_PIX_FMT_SRGGB12:
1055                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_DAT12;
1056                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED16;
1057                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1058                 isc->try_config.bpp = 16;
1059                 break;
1060         case V4L2_PIX_FMT_RGB565:
1061                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_RGB565;
1062                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED16;
1063                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1064                 isc->try_config.bpp = 16;
1065                 break;
1066         case V4L2_PIX_FMT_ARGB444:
1067                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_ARGB444;
1068                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED16;
1069                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1070                 isc->try_config.bpp = 16;
1071                 break;
1072         case V4L2_PIX_FMT_ARGB555:
1073                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_ARGB555;
1074                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED16;
1075                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1076                 isc->try_config.bpp = 16;
1077                 break;
1078         case V4L2_PIX_FMT_ABGR32:
1079         case V4L2_PIX_FMT_XBGR32:
1080                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_ARGB32;
1081                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED32;
1082                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1083                 isc->try_config.bpp = 32;
1084                 break;
1085         case V4L2_PIX_FMT_YUV420:
1086                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_YYCC;
1087                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_YC420P;
1088                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PLANAR;
1089                 isc->try_config.bpp = 12;
1090                 break;
1091         case V4L2_PIX_FMT_YUV422P:
1092                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_YYCC;
1093                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_YC422P;
1094                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PLANAR;
1095                 isc->try_config.bpp = 16;
1096                 break;
1097         case V4L2_PIX_FMT_YUYV:
1098                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_YYCC;
1099                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED32;
1100                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1101                 isc->try_config.bpp = 16;
1102                 break;
1103         case V4L2_PIX_FMT_GREY:
1104                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_DATY8;
1105                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED8;
1106                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1107                 isc->try_config.bpp = 8;
1108                 break;
1109         case V4L2_PIX_FMT_Y10:
1110                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_DATY10;
1111                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED16;
1112                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1113                 isc->try_config.bpp = 16;
1114                 break;
1115         default:
1116                 return -EINVAL;
1117         }
1118
1119         if (direct_dump) {
1120                 isc->try_config.rlp_cfg_mode = ISC_RLP_CFG_MODE_DAT8;
1121                 isc->try_config.dcfg_imode = ISC_DCFG_IMODE_PACKED8;
1122                 isc->try_config.dctrl_dview = ISC_DCTRL_DVIEW_PACKED;
1123                 return 0;
1124         }
1125
1126         return 0;
1127 }
1128
1129 /*
1130  * Configuring pipeline modules, depending on which format the ISC outputs
1131  * and considering which format it has as input from the sensor.
1132  */
1133 static int isc_try_configure_pipeline(struct isc_device *isc)
1134 {
1135         switch (isc->try_config.fourcc) {
1136         case V4L2_PIX_FMT_RGB565:
1137         case V4L2_PIX_FMT_ARGB555:
1138         case V4L2_PIX_FMT_ARGB444:
1139         case V4L2_PIX_FMT_ABGR32:
1140         case V4L2_PIX_FMT_XBGR32:
1141                 /* if sensor format is RAW, we convert inside ISC */
1142                 if (ISC_IS_FORMAT_RAW(isc->try_config.sd_format->mbus_code)) {
1143                         isc->try_config.bits_pipeline = CFA_ENABLE |
1144                                 WB_ENABLE | GAM_ENABLES;
1145                 } else {
1146                         isc->try_config.bits_pipeline = 0x0;
1147                 }
1148                 break;
1149         case V4L2_PIX_FMT_YUV420:
1150                 /* if sensor format is RAW, we convert inside ISC */
1151                 if (ISC_IS_FORMAT_RAW(isc->try_config.sd_format->mbus_code)) {
1152                         isc->try_config.bits_pipeline = CFA_ENABLE |
1153                                 CSC_ENABLE | WB_ENABLE | GAM_ENABLES |
1154                                 SUB420_ENABLE | SUB422_ENABLE | CBC_ENABLE;
1155                 } else {
1156                         isc->try_config.bits_pipeline = 0x0;
1157                 }
1158                 break;
1159         case V4L2_PIX_FMT_YUV422P:
1160                 /* if sensor format is RAW, we convert inside ISC */
1161                 if (ISC_IS_FORMAT_RAW(isc->try_config.sd_format->mbus_code)) {
1162                         isc->try_config.bits_pipeline = CFA_ENABLE |
1163                                 CSC_ENABLE | WB_ENABLE | GAM_ENABLES |
1164                                 SUB422_ENABLE | CBC_ENABLE;
1165                 } else {
1166                         isc->try_config.bits_pipeline = 0x0;
1167                 }
1168                 break;
1169         case V4L2_PIX_FMT_YUYV:
1170                 /* if sensor format is RAW, we convert inside ISC */
1171                 if (ISC_IS_FORMAT_RAW(isc->try_config.sd_format->mbus_code)) {
1172                         isc->try_config.bits_pipeline = CFA_ENABLE |
1173                                 CSC_ENABLE | WB_ENABLE | GAM_ENABLES |
1174                                 SUB422_ENABLE | CBC_ENABLE;
1175                 } else {
1176                         isc->try_config.bits_pipeline = 0x0;
1177                 }
1178                 break;
1179         case V4L2_PIX_FMT_GREY:
1180                 if (ISC_IS_FORMAT_RAW(isc->try_config.sd_format->mbus_code)) {
1181                 /* if sensor format is RAW, we convert inside ISC */
1182                         isc->try_config.bits_pipeline = CFA_ENABLE |
1183                                 CSC_ENABLE | WB_ENABLE | GAM_ENABLES |
1184                                 CBC_ENABLE;
1185                 } else {
1186                         isc->try_config.bits_pipeline = 0x0;
1187                 }
1188                 break;
1189         default:
1190                 isc->try_config.bits_pipeline = 0x0;
1191         }
1192         return 0;
1193 }
1194
1195 static void isc_try_fse(struct isc_device *isc,
1196                         struct v4l2_subdev_pad_config *pad_cfg)
1197 {
1198         int ret;
1199         struct v4l2_subdev_frame_size_enum fse = {};
1200
1201         /*
1202          * If we do not know yet which format the subdev is using, we cannot
1203          * do anything.
1204          */
1205         if (!isc->try_config.sd_format)
1206                 return;
1207
1208         fse.code = isc->try_config.sd_format->mbus_code;
1209         fse.which = V4L2_SUBDEV_FORMAT_TRY;
1210
1211         ret = v4l2_subdev_call(isc->current_subdev->sd, pad, enum_frame_size,
1212                                pad_cfg, &fse);
1213         /*
1214          * Attempt to obtain format size from subdev. If not available,
1215          * just use the maximum ISC can receive.
1216          */
1217         if (ret) {
1218                 pad_cfg->try_crop.width = isc->max_width;
1219                 pad_cfg->try_crop.height = isc->max_height;
1220         } else {
1221                 pad_cfg->try_crop.width = fse.max_width;
1222                 pad_cfg->try_crop.height = fse.max_height;
1223         }
1224 }
1225
1226 static int isc_try_fmt(struct isc_device *isc, struct v4l2_format *f,
1227                         u32 *code)
1228 {
1229         int i;
1230         struct isc_format *sd_fmt = NULL, *direct_fmt = NULL;
1231         struct v4l2_pix_format *pixfmt = &f->fmt.pix;
1232         struct v4l2_subdev_pad_config pad_cfg = {};
1233         struct v4l2_subdev_format format = {
1234                 .which = V4L2_SUBDEV_FORMAT_TRY,
1235         };
1236         u32 mbus_code;
1237         int ret;
1238         bool rlp_dma_direct_dump = false;
1239
1240         if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1241                 return -EINVAL;
1242
1243         /* Step 1: find a RAW format that is supported */
1244         for (i = 0; i < isc->num_user_formats; i++) {
1245                 if (ISC_IS_FORMAT_RAW(isc->user_formats[i]->mbus_code)) {
1246                         sd_fmt = isc->user_formats[i];
1247                         break;
1248                 }
1249         }
1250         /* Step 2: We can continue with this RAW format, or we can look
1251          * for better: maybe sensor supports directly what we need.
1252          */
1253         direct_fmt = find_format_by_fourcc(isc, pixfmt->pixelformat);
1254
1255         /* Step 3: We have both. We decide given the module parameter which
1256          * one to use.
1257          */
1258         if (direct_fmt && sd_fmt && sensor_preferred)
1259                 sd_fmt = direct_fmt;
1260
1261         /* Step 4: we do not have RAW but we have a direct format. Use it. */
1262         if (direct_fmt && !sd_fmt)
1263                 sd_fmt = direct_fmt;
1264
1265         /* Step 5: if we are using a direct format, we need to package
1266          * everything as 8 bit data and just dump it
1267          */
1268         if (sd_fmt == direct_fmt)
1269                 rlp_dma_direct_dump = true;
1270
1271         /* Step 6: We have no format. This can happen if the userspace
1272          * requests some weird/invalid format.
1273          * In this case, default to whatever we have
1274          */
1275         if (!sd_fmt && !direct_fmt) {
1276                 sd_fmt = isc->user_formats[isc->num_user_formats - 1];
1277                 v4l2_dbg(1, debug, &isc->v4l2_dev,
1278                          "Sensor not supporting %.4s, using %.4s\n",
1279                          (char *)&pixfmt->pixelformat, (char *)&sd_fmt->fourcc);
1280         }
1281
1282         if (!sd_fmt) {
1283                 ret = -EINVAL;
1284                 goto isc_try_fmt_err;
1285         }
1286
1287         /* Step 7: Print out what we decided for debugging */
1288         v4l2_dbg(1, debug, &isc->v4l2_dev,
1289                  "Preferring to have sensor using format %.4s\n",
1290                  (char *)&sd_fmt->fourcc);
1291
1292         /* Step 8: at this moment we decided which format the subdev will use */
1293         isc->try_config.sd_format = sd_fmt;
1294
1295         /* Limit to Atmel ISC hardware capabilities */
1296         if (pixfmt->width > isc->max_width)
1297                 pixfmt->width = isc->max_width;
1298         if (pixfmt->height > isc->max_height)
1299                 pixfmt->height = isc->max_height;
1300
1301         /*
1302          * The mbus format is the one the subdev outputs.
1303          * The pixels will be transferred in this format Sensor -> ISC
1304          */
1305         mbus_code = sd_fmt->mbus_code;
1306
1307         /*
1308          * Validate formats. If the required format is not OK, default to raw.
1309          */
1310
1311         isc->try_config.fourcc = pixfmt->pixelformat;
1312
1313         if (isc_try_validate_formats(isc)) {
1314                 pixfmt->pixelformat = isc->try_config.fourcc = sd_fmt->fourcc;
1315                 /* Re-try to validate the new format */
1316                 ret = isc_try_validate_formats(isc);
1317                 if (ret)
1318                         goto isc_try_fmt_err;
1319         }
1320
1321         ret = isc_try_configure_rlp_dma(isc, rlp_dma_direct_dump);
1322         if (ret)
1323                 goto isc_try_fmt_err;
1324
1325         ret = isc_try_configure_pipeline(isc);
1326         if (ret)
1327                 goto isc_try_fmt_err;
1328
1329         /* Obtain frame sizes if possible to have crop requirements ready */
1330         isc_try_fse(isc, &pad_cfg);
1331
1332         v4l2_fill_mbus_format(&format.format, pixfmt, mbus_code);
1333         ret = v4l2_subdev_call(isc->current_subdev->sd, pad, set_fmt,
1334                                &pad_cfg, &format);
1335         if (ret < 0)
1336                 goto isc_try_fmt_subdev_err;
1337
1338         v4l2_fill_pix_format(pixfmt, &format.format);
1339
1340         /* Limit to Atmel ISC hardware capabilities */
1341         if (pixfmt->width > isc->max_width)
1342                 pixfmt->width = isc->max_width;
1343         if (pixfmt->height > isc->max_height)
1344                 pixfmt->height = isc->max_height;
1345
1346         pixfmt->field = V4L2_FIELD_NONE;
1347         pixfmt->bytesperline = (pixfmt->width * isc->try_config.bpp) >> 3;
1348         pixfmt->sizeimage = pixfmt->bytesperline * pixfmt->height;
1349
1350         if (code)
1351                 *code = mbus_code;
1352
1353         return 0;
1354
1355 isc_try_fmt_err:
1356         v4l2_err(&isc->v4l2_dev, "Could not find any possible format for a working pipeline\n");
1357 isc_try_fmt_subdev_err:
1358         memset(&isc->try_config, 0, sizeof(isc->try_config));
1359
1360         return ret;
1361 }
1362
1363 static int isc_set_fmt(struct isc_device *isc, struct v4l2_format *f)
1364 {
1365         struct v4l2_subdev_format format = {
1366                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1367         };
1368         u32 mbus_code = 0;
1369         int ret;
1370
1371         ret = isc_try_fmt(isc, f, &mbus_code);
1372         if (ret)
1373                 return ret;
1374
1375         v4l2_fill_mbus_format(&format.format, &f->fmt.pix, mbus_code);
1376         ret = v4l2_subdev_call(isc->current_subdev->sd, pad,
1377                                set_fmt, NULL, &format);
1378         if (ret < 0)
1379                 return ret;
1380
1381         /* Limit to Atmel ISC hardware capabilities */
1382         if (f->fmt.pix.width > isc->max_width)
1383                 f->fmt.pix.width = isc->max_width;
1384         if (f->fmt.pix.height > isc->max_height)
1385                 f->fmt.pix.height = isc->max_height;
1386
1387         isc->fmt = *f;
1388
1389         if (isc->try_config.sd_format && isc->config.sd_format &&
1390             isc->try_config.sd_format != isc->config.sd_format) {
1391                 isc->ctrls.hist_stat = HIST_INIT;
1392                 isc_reset_awb_ctrls(isc);
1393                 isc_update_v4l2_ctrls(isc);
1394         }
1395         /* make the try configuration active */
1396         isc->config = isc->try_config;
1397
1398         v4l2_dbg(1, debug, &isc->v4l2_dev, "New ISC configuration in place\n");
1399
1400         return 0;
1401 }
1402
1403 static int isc_s_fmt_vid_cap(struct file *file, void *priv,
1404                               struct v4l2_format *f)
1405 {
1406         struct isc_device *isc = video_drvdata(file);
1407
1408         if (vb2_is_streaming(&isc->vb2_vidq))
1409                 return -EBUSY;
1410
1411         return isc_set_fmt(isc, f);
1412 }
1413
1414 static int isc_try_fmt_vid_cap(struct file *file, void *priv,
1415                                 struct v4l2_format *f)
1416 {
1417         struct isc_device *isc = video_drvdata(file);
1418
1419         return isc_try_fmt(isc, f, NULL);
1420 }
1421
1422 static int isc_enum_input(struct file *file, void *priv,
1423                            struct v4l2_input *inp)
1424 {
1425         if (inp->index != 0)
1426                 return -EINVAL;
1427
1428         inp->type = V4L2_INPUT_TYPE_CAMERA;
1429         inp->std = 0;
1430         strscpy(inp->name, "Camera", sizeof(inp->name));
1431
1432         return 0;
1433 }
1434
1435 static int isc_g_input(struct file *file, void *priv, unsigned int *i)
1436 {
1437         *i = 0;
1438
1439         return 0;
1440 }
1441
1442 static int isc_s_input(struct file *file, void *priv, unsigned int i)
1443 {
1444         if (i > 0)
1445                 return -EINVAL;
1446
1447         return 0;
1448 }
1449
1450 static int isc_g_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1451 {
1452         struct isc_device *isc = video_drvdata(file);
1453
1454         return v4l2_g_parm_cap(video_devdata(file), isc->current_subdev->sd, a);
1455 }
1456
1457 static int isc_s_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1458 {
1459         struct isc_device *isc = video_drvdata(file);
1460
1461         return v4l2_s_parm_cap(video_devdata(file), isc->current_subdev->sd, a);
1462 }
1463
1464 static int isc_enum_framesizes(struct file *file, void *fh,
1465                                struct v4l2_frmsizeenum *fsize)
1466 {
1467         struct isc_device *isc = video_drvdata(file);
1468         struct v4l2_subdev_frame_size_enum fse = {
1469                 .code = isc->config.sd_format->mbus_code,
1470                 .index = fsize->index,
1471                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1472         };
1473         int ret = -EINVAL;
1474         int i;
1475
1476         for (i = 0; i < isc->num_user_formats; i++)
1477                 if (isc->user_formats[i]->fourcc == fsize->pixel_format)
1478                         ret = 0;
1479
1480         for (i = 0; i < ARRAY_SIZE(controller_formats); i++)
1481                 if (controller_formats[i].fourcc == fsize->pixel_format)
1482                         ret = 0;
1483
1484         if (ret)
1485                 return ret;
1486
1487         ret = v4l2_subdev_call(isc->current_subdev->sd, pad, enum_frame_size,
1488                                NULL, &fse);
1489         if (ret)
1490                 return ret;
1491
1492         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1493         fsize->discrete.width = fse.max_width;
1494         fsize->discrete.height = fse.max_height;
1495
1496         return 0;
1497 }
1498
1499 static int isc_enum_frameintervals(struct file *file, void *fh,
1500                                     struct v4l2_frmivalenum *fival)
1501 {
1502         struct isc_device *isc = video_drvdata(file);
1503         struct v4l2_subdev_frame_interval_enum fie = {
1504                 .code = isc->config.sd_format->mbus_code,
1505                 .index = fival->index,
1506                 .width = fival->width,
1507                 .height = fival->height,
1508                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1509         };
1510         int ret = -EINVAL;
1511         unsigned int i;
1512
1513         for (i = 0; i < isc->num_user_formats; i++)
1514                 if (isc->user_formats[i]->fourcc == fival->pixel_format)
1515                         ret = 0;
1516
1517         for (i = 0; i < ARRAY_SIZE(controller_formats); i++)
1518                 if (controller_formats[i].fourcc == fival->pixel_format)
1519                         ret = 0;
1520
1521         if (ret)
1522                 return ret;
1523
1524         ret = v4l2_subdev_call(isc->current_subdev->sd, pad,
1525                                enum_frame_interval, NULL, &fie);
1526         if (ret)
1527                 return ret;
1528
1529         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1530         fival->discrete = fie.interval;
1531
1532         return 0;
1533 }
1534
1535 static const struct v4l2_ioctl_ops isc_ioctl_ops = {
1536         .vidioc_querycap                = isc_querycap,
1537         .vidioc_enum_fmt_vid_cap        = isc_enum_fmt_vid_cap,
1538         .vidioc_g_fmt_vid_cap           = isc_g_fmt_vid_cap,
1539         .vidioc_s_fmt_vid_cap           = isc_s_fmt_vid_cap,
1540         .vidioc_try_fmt_vid_cap         = isc_try_fmt_vid_cap,
1541
1542         .vidioc_enum_input              = isc_enum_input,
1543         .vidioc_g_input                 = isc_g_input,
1544         .vidioc_s_input                 = isc_s_input,
1545
1546         .vidioc_reqbufs                 = vb2_ioctl_reqbufs,
1547         .vidioc_querybuf                = vb2_ioctl_querybuf,
1548         .vidioc_qbuf                    = vb2_ioctl_qbuf,
1549         .vidioc_expbuf                  = vb2_ioctl_expbuf,
1550         .vidioc_dqbuf                   = vb2_ioctl_dqbuf,
1551         .vidioc_create_bufs             = vb2_ioctl_create_bufs,
1552         .vidioc_prepare_buf             = vb2_ioctl_prepare_buf,
1553         .vidioc_streamon                = vb2_ioctl_streamon,
1554         .vidioc_streamoff               = vb2_ioctl_streamoff,
1555
1556         .vidioc_g_parm                  = isc_g_parm,
1557         .vidioc_s_parm                  = isc_s_parm,
1558         .vidioc_enum_framesizes         = isc_enum_framesizes,
1559         .vidioc_enum_frameintervals     = isc_enum_frameintervals,
1560
1561         .vidioc_log_status              = v4l2_ctrl_log_status,
1562         .vidioc_subscribe_event         = v4l2_ctrl_subscribe_event,
1563         .vidioc_unsubscribe_event       = v4l2_event_unsubscribe,
1564 };
1565
1566 static int isc_open(struct file *file)
1567 {
1568         struct isc_device *isc = video_drvdata(file);
1569         struct v4l2_subdev *sd = isc->current_subdev->sd;
1570         int ret;
1571
1572         if (mutex_lock_interruptible(&isc->lock))
1573                 return -ERESTARTSYS;
1574
1575         ret = v4l2_fh_open(file);
1576         if (ret < 0)
1577                 goto unlock;
1578
1579         if (!v4l2_fh_is_singular_file(file))
1580                 goto unlock;
1581
1582         ret = v4l2_subdev_call(sd, core, s_power, 1);
1583         if (ret < 0 && ret != -ENOIOCTLCMD) {
1584                 v4l2_fh_release(file);
1585                 goto unlock;
1586         }
1587
1588         ret = isc_set_fmt(isc, &isc->fmt);
1589         if (ret) {
1590                 v4l2_subdev_call(sd, core, s_power, 0);
1591                 v4l2_fh_release(file);
1592         }
1593
1594 unlock:
1595         mutex_unlock(&isc->lock);
1596         return ret;
1597 }
1598
1599 static int isc_release(struct file *file)
1600 {
1601         struct isc_device *isc = video_drvdata(file);
1602         struct v4l2_subdev *sd = isc->current_subdev->sd;
1603         bool fh_singular;
1604         int ret;
1605
1606         mutex_lock(&isc->lock);
1607
1608         fh_singular = v4l2_fh_is_singular_file(file);
1609
1610         ret = _vb2_fop_release(file, NULL);
1611
1612         if (fh_singular)
1613                 v4l2_subdev_call(sd, core, s_power, 0);
1614
1615         mutex_unlock(&isc->lock);
1616
1617         return ret;
1618 }
1619
1620 static const struct v4l2_file_operations isc_fops = {
1621         .owner          = THIS_MODULE,
1622         .open           = isc_open,
1623         .release        = isc_release,
1624         .unlocked_ioctl = video_ioctl2,
1625         .read           = vb2_fop_read,
1626         .mmap           = vb2_fop_mmap,
1627         .poll           = vb2_fop_poll,
1628 };
1629
1630 irqreturn_t isc_interrupt(int irq, void *dev_id)
1631 {
1632         struct isc_device *isc = (struct isc_device *)dev_id;
1633         struct regmap *regmap = isc->regmap;
1634         u32 isc_intsr, isc_intmask, pending;
1635         irqreturn_t ret = IRQ_NONE;
1636
1637         regmap_read(regmap, ISC_INTSR, &isc_intsr);
1638         regmap_read(regmap, ISC_INTMASK, &isc_intmask);
1639
1640         pending = isc_intsr & isc_intmask;
1641
1642         if (likely(pending & ISC_INT_DDONE)) {
1643                 spin_lock(&isc->dma_queue_lock);
1644                 if (isc->cur_frm) {
1645                         struct vb2_v4l2_buffer *vbuf = &isc->cur_frm->vb;
1646                         struct vb2_buffer *vb = &vbuf->vb2_buf;
1647
1648                         vb->timestamp = ktime_get_ns();
1649                         vbuf->sequence = isc->sequence++;
1650                         vb2_buffer_done(vb, VB2_BUF_STATE_DONE);
1651                         isc->cur_frm = NULL;
1652                 }
1653
1654                 if (!list_empty(&isc->dma_queue) && !isc->stop) {
1655                         isc->cur_frm = list_first_entry(&isc->dma_queue,
1656                                                      struct isc_buffer, list);
1657                         list_del(&isc->cur_frm->list);
1658
1659                         isc_start_dma(isc);
1660                 }
1661
1662                 if (isc->stop)
1663                         complete(&isc->comp);
1664
1665                 ret = IRQ_HANDLED;
1666                 spin_unlock(&isc->dma_queue_lock);
1667         }
1668
1669         if (pending & ISC_INT_HISDONE) {
1670                 schedule_work(&isc->awb_work);
1671                 ret = IRQ_HANDLED;
1672         }
1673
1674         return ret;
1675 }
1676
1677 static void isc_hist_count(struct isc_device *isc, u32 *min, u32 *max)
1678 {
1679         struct regmap *regmap = isc->regmap;
1680         struct isc_ctrls *ctrls = &isc->ctrls;
1681         u32 *hist_count = &ctrls->hist_count[ctrls->hist_id];
1682         u32 *hist_entry = &ctrls->hist_entry[0];
1683         u32 i;
1684
1685         *min = 0;
1686         *max = HIST_ENTRIES;
1687
1688         regmap_bulk_read(regmap, ISC_HIS_ENTRY + isc->offsets.his_entry,
1689                          hist_entry, HIST_ENTRIES);
1690
1691         *hist_count = 0;
1692         /*
1693          * we deliberately ignore the end of the histogram,
1694          * the most white pixels
1695          */
1696         for (i = 1; i < HIST_ENTRIES; i++) {
1697                 if (*hist_entry && !*min)
1698                         *min = i;
1699                 if (*hist_entry)
1700                         *max = i;
1701                 *hist_count += i * (*hist_entry++);
1702         }
1703
1704         if (!*min)
1705                 *min = 1;
1706 }
1707
1708 static void isc_wb_update(struct isc_ctrls *ctrls)
1709 {
1710         u32 *hist_count = &ctrls->hist_count[0];
1711         u32 c, offset[4];
1712         u64 avg = 0;
1713         /* We compute two gains, stretch gain and grey world gain */
1714         u32 s_gain[4], gw_gain[4];
1715
1716         /*
1717          * According to Grey World, we need to set gains for R/B to normalize
1718          * them towards the green channel.
1719          * Thus we want to keep Green as fixed and adjust only Red/Blue
1720          * Compute the average of the both green channels first
1721          */
1722         avg = (u64)hist_count[ISC_HIS_CFG_MODE_GR] +
1723                 (u64)hist_count[ISC_HIS_CFG_MODE_GB];
1724         avg >>= 1;
1725
1726         /* Green histogram is null, nothing to do */
1727         if (!avg)
1728                 return;
1729
1730         for (c = ISC_HIS_CFG_MODE_GR; c <= ISC_HIS_CFG_MODE_B; c++) {
1731                 /*
1732                  * the color offset is the minimum value of the histogram.
1733                  * we stretch this color to the full range by substracting
1734                  * this value from the color component.
1735                  */
1736                 offset[c] = ctrls->hist_minmax[c][HIST_MIN_INDEX];
1737                 /*
1738                  * The offset is always at least 1. If the offset is 1, we do
1739                  * not need to adjust it, so our result must be zero.
1740                  * the offset is computed in a histogram on 9 bits (0..512)
1741                  * but the offset in register is based on
1742                  * 12 bits pipeline (0..4096).
1743                  * we need to shift with the 3 bits that the histogram is
1744                  * ignoring
1745                  */
1746                 ctrls->offset[c] = (offset[c] - 1) << 3;
1747
1748                 /*
1749                  * the offset is then taken and converted to 2's complements,
1750                  * and must be negative, as we subtract this value from the
1751                  * color components
1752                  */
1753                 ctrls->offset[c] = -ctrls->offset[c];
1754
1755                 /*
1756                  * the stretch gain is the total number of histogram bins
1757                  * divided by the actual range of color component (Max - Min)
1758                  * If we compute gain like this, the actual color component
1759                  * will be stretched to the full histogram.
1760                  * We need to shift 9 bits for precision, we have 9 bits for
1761                  * decimals
1762                  */
1763                 s_gain[c] = (HIST_ENTRIES << 9) /
1764                         (ctrls->hist_minmax[c][HIST_MAX_INDEX] -
1765                         ctrls->hist_minmax[c][HIST_MIN_INDEX] + 1);
1766
1767                 /*
1768                  * Now we have to compute the gain w.r.t. the average.
1769                  * Add/lose gain to the component towards the average.
1770                  * If it happens that the component is zero, use the
1771                  * fixed point value : 1.0 gain.
1772                  */
1773                 if (hist_count[c])
1774                         gw_gain[c] = div_u64(avg << 9, hist_count[c]);
1775                 else
1776                         gw_gain[c] = 1 << 9;
1777
1778                 /* multiply both gains and adjust for decimals */
1779                 ctrls->gain[c] = s_gain[c] * gw_gain[c];
1780                 ctrls->gain[c] >>= 9;
1781         }
1782 }
1783
1784 static void isc_awb_work(struct work_struct *w)
1785 {
1786         struct isc_device *isc =
1787                 container_of(w, struct isc_device, awb_work);
1788         struct regmap *regmap = isc->regmap;
1789         struct isc_ctrls *ctrls = &isc->ctrls;
1790         u32 hist_id = ctrls->hist_id;
1791         u32 baysel;
1792         unsigned long flags;
1793         u32 min, max;
1794         int ret;
1795
1796         /* streaming is not active anymore */
1797         if (isc->stop)
1798                 return;
1799
1800         if (ctrls->hist_stat != HIST_ENABLED)
1801                 return;
1802
1803         isc_hist_count(isc, &min, &max);
1804         ctrls->hist_minmax[hist_id][HIST_MIN_INDEX] = min;
1805         ctrls->hist_minmax[hist_id][HIST_MAX_INDEX] = max;
1806
1807         if (hist_id != ISC_HIS_CFG_MODE_B) {
1808                 hist_id++;
1809         } else {
1810                 isc_wb_update(ctrls);
1811                 hist_id = ISC_HIS_CFG_MODE_GR;
1812         }
1813
1814         ctrls->hist_id = hist_id;
1815         baysel = isc->config.sd_format->cfa_baycfg << ISC_HIS_CFG_BAYSEL_SHIFT;
1816
1817         ret = pm_runtime_resume_and_get(isc->dev);
1818         if (ret < 0)
1819                 return;
1820
1821         /*
1822          * only update if we have all the required histograms and controls
1823          * if awb has been disabled, we need to reset registers as well.
1824          */
1825         if (hist_id == ISC_HIS_CFG_MODE_GR || ctrls->awb == ISC_WB_NONE) {
1826                 /*
1827                  * It may happen that DMA Done IRQ will trigger while we are
1828                  * updating white balance registers here.
1829                  * In that case, only parts of the controls have been updated.
1830                  * We can avoid that by locking the section.
1831                  */
1832                 spin_lock_irqsave(&isc->awb_lock, flags);
1833                 isc_update_awb_ctrls(isc);
1834                 spin_unlock_irqrestore(&isc->awb_lock, flags);
1835
1836                 /*
1837                  * if we are doing just the one time white balance adjustment,
1838                  * we are basically done.
1839                  */
1840                 if (ctrls->awb == ISC_WB_ONETIME) {
1841                         v4l2_info(&isc->v4l2_dev,
1842                                   "Completed one time white-balance adjustment.\n");
1843                         /* update the v4l2 controls values */
1844                         isc_update_v4l2_ctrls(isc);
1845                         ctrls->awb = ISC_WB_NONE;
1846                 }
1847         }
1848         regmap_write(regmap, ISC_HIS_CFG + isc->offsets.his,
1849                      hist_id | baysel | ISC_HIS_CFG_RAR);
1850         isc_update_profile(isc);
1851         /* if awb has been disabled, we don't need to start another histogram */
1852         if (ctrls->awb)
1853                 regmap_write(regmap, ISC_CTRLEN, ISC_CTRL_HISREQ);
1854
1855         pm_runtime_put_sync(isc->dev);
1856 }
1857
1858 static int isc_s_ctrl(struct v4l2_ctrl *ctrl)
1859 {
1860         struct isc_device *isc = container_of(ctrl->handler,
1861                                              struct isc_device, ctrls.handler);
1862         struct isc_ctrls *ctrls = &isc->ctrls;
1863
1864         if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE)
1865                 return 0;
1866
1867         switch (ctrl->id) {
1868         case V4L2_CID_BRIGHTNESS:
1869                 ctrls->brightness = ctrl->val & ISC_CBC_BRIGHT_MASK;
1870                 break;
1871         case V4L2_CID_CONTRAST:
1872                 ctrls->contrast = ctrl->val & ISC_CBC_CONTRAST_MASK;
1873                 break;
1874         case V4L2_CID_GAMMA:
1875                 ctrls->gamma_index = ctrl->val;
1876                 break;
1877         default:
1878                 return -EINVAL;
1879         }
1880
1881         return 0;
1882 }
1883
1884 static const struct v4l2_ctrl_ops isc_ctrl_ops = {
1885         .s_ctrl = isc_s_ctrl,
1886 };
1887
1888 static int isc_s_awb_ctrl(struct v4l2_ctrl *ctrl)
1889 {
1890         struct isc_device *isc = container_of(ctrl->handler,
1891                                              struct isc_device, ctrls.handler);
1892         struct isc_ctrls *ctrls = &isc->ctrls;
1893
1894         if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE)
1895                 return 0;
1896
1897         switch (ctrl->id) {
1898         case V4L2_CID_AUTO_WHITE_BALANCE:
1899                 if (ctrl->val == 1)
1900                         ctrls->awb = ISC_WB_AUTO;
1901                 else
1902                         ctrls->awb = ISC_WB_NONE;
1903
1904                 /* we did not configure ISC yet */
1905                 if (!isc->config.sd_format)
1906                         break;
1907
1908                 /* configure the controls with new values from v4l2 */
1909                 if (ctrl->cluster[ISC_CTRL_R_GAIN]->is_new)
1910                         ctrls->gain[ISC_HIS_CFG_MODE_R] = isc->r_gain_ctrl->val;
1911                 if (ctrl->cluster[ISC_CTRL_B_GAIN]->is_new)
1912                         ctrls->gain[ISC_HIS_CFG_MODE_B] = isc->b_gain_ctrl->val;
1913                 if (ctrl->cluster[ISC_CTRL_GR_GAIN]->is_new)
1914                         ctrls->gain[ISC_HIS_CFG_MODE_GR] = isc->gr_gain_ctrl->val;
1915                 if (ctrl->cluster[ISC_CTRL_GB_GAIN]->is_new)
1916                         ctrls->gain[ISC_HIS_CFG_MODE_GB] = isc->gb_gain_ctrl->val;
1917
1918                 if (ctrl->cluster[ISC_CTRL_R_OFF]->is_new)
1919                         ctrls->offset[ISC_HIS_CFG_MODE_R] = isc->r_off_ctrl->val;
1920                 if (ctrl->cluster[ISC_CTRL_B_OFF]->is_new)
1921                         ctrls->offset[ISC_HIS_CFG_MODE_B] = isc->b_off_ctrl->val;
1922                 if (ctrl->cluster[ISC_CTRL_GR_OFF]->is_new)
1923                         ctrls->offset[ISC_HIS_CFG_MODE_GR] = isc->gr_off_ctrl->val;
1924                 if (ctrl->cluster[ISC_CTRL_GB_OFF]->is_new)
1925                         ctrls->offset[ISC_HIS_CFG_MODE_GB] = isc->gb_off_ctrl->val;
1926
1927                 isc_update_awb_ctrls(isc);
1928
1929                 if (vb2_is_streaming(&isc->vb2_vidq)) {
1930                         /*
1931                          * If we are streaming, we can update profile to
1932                          * have the new settings in place.
1933                          */
1934                         isc_update_profile(isc);
1935                 } else {
1936                         /*
1937                          * The auto cluster will activate automatically this
1938                          * control. This has to be deactivated when not
1939                          * streaming.
1940                          */
1941                         v4l2_ctrl_activate(isc->do_wb_ctrl, false);
1942                 }
1943
1944                 /* if we have autowhitebalance on, start histogram procedure */
1945                 if (ctrls->awb == ISC_WB_AUTO &&
1946                     vb2_is_streaming(&isc->vb2_vidq) &&
1947                     ISC_IS_FORMAT_RAW(isc->config.sd_format->mbus_code))
1948                         isc_set_histogram(isc, true);
1949
1950                 /*
1951                  * for one time whitebalance adjustment, check the button,
1952                  * if it's pressed, perform the one time operation.
1953                  */
1954                 if (ctrls->awb == ISC_WB_NONE &&
1955                     ctrl->cluster[ISC_CTRL_DO_WB]->is_new &&
1956                     !(ctrl->cluster[ISC_CTRL_DO_WB]->flags &
1957                     V4L2_CTRL_FLAG_INACTIVE)) {
1958                         ctrls->awb = ISC_WB_ONETIME;
1959                         isc_set_histogram(isc, true);
1960                         v4l2_dbg(1, debug, &isc->v4l2_dev,
1961                                  "One time white-balance started.\n");
1962                 }
1963                 return 0;
1964         }
1965         return 0;
1966 }
1967
1968 static int isc_g_volatile_awb_ctrl(struct v4l2_ctrl *ctrl)
1969 {
1970         struct isc_device *isc = container_of(ctrl->handler,
1971                                              struct isc_device, ctrls.handler);
1972         struct isc_ctrls *ctrls = &isc->ctrls;
1973
1974         switch (ctrl->id) {
1975         /* being a cluster, this id will be called for every control */
1976         case V4L2_CID_AUTO_WHITE_BALANCE:
1977                 ctrl->cluster[ISC_CTRL_R_GAIN]->val =
1978                                         ctrls->gain[ISC_HIS_CFG_MODE_R];
1979                 ctrl->cluster[ISC_CTRL_B_GAIN]->val =
1980                                         ctrls->gain[ISC_HIS_CFG_MODE_B];
1981                 ctrl->cluster[ISC_CTRL_GR_GAIN]->val =
1982                                         ctrls->gain[ISC_HIS_CFG_MODE_GR];
1983                 ctrl->cluster[ISC_CTRL_GB_GAIN]->val =
1984                                         ctrls->gain[ISC_HIS_CFG_MODE_GB];
1985
1986                 ctrl->cluster[ISC_CTRL_R_OFF]->val =
1987                         ctrls->offset[ISC_HIS_CFG_MODE_R];
1988                 ctrl->cluster[ISC_CTRL_B_OFF]->val =
1989                         ctrls->offset[ISC_HIS_CFG_MODE_B];
1990                 ctrl->cluster[ISC_CTRL_GR_OFF]->val =
1991                         ctrls->offset[ISC_HIS_CFG_MODE_GR];
1992                 ctrl->cluster[ISC_CTRL_GB_OFF]->val =
1993                         ctrls->offset[ISC_HIS_CFG_MODE_GB];
1994                 break;
1995         }
1996         return 0;
1997 }
1998
1999 static const struct v4l2_ctrl_ops isc_awb_ops = {
2000         .s_ctrl = isc_s_awb_ctrl,
2001         .g_volatile_ctrl = isc_g_volatile_awb_ctrl,
2002 };
2003
2004 #define ISC_CTRL_OFF(_name, _id, _name_str) \
2005         static const struct v4l2_ctrl_config _name = { \
2006                 .ops = &isc_awb_ops, \
2007                 .id = _id, \
2008                 .name = _name_str, \
2009                 .type = V4L2_CTRL_TYPE_INTEGER, \
2010                 .flags = V4L2_CTRL_FLAG_SLIDER, \
2011                 .min = -4095, \
2012                 .max = 4095, \
2013                 .step = 1, \
2014                 .def = 0, \
2015         }
2016
2017 ISC_CTRL_OFF(isc_r_off_ctrl, ISC_CID_R_OFFSET, "Red Component Offset");
2018 ISC_CTRL_OFF(isc_b_off_ctrl, ISC_CID_B_OFFSET, "Blue Component Offset");
2019 ISC_CTRL_OFF(isc_gr_off_ctrl, ISC_CID_GR_OFFSET, "Green Red Component Offset");
2020 ISC_CTRL_OFF(isc_gb_off_ctrl, ISC_CID_GB_OFFSET, "Green Blue Component Offset");
2021
2022 #define ISC_CTRL_GAIN(_name, _id, _name_str) \
2023         static const struct v4l2_ctrl_config _name = { \
2024                 .ops = &isc_awb_ops, \
2025                 .id = _id, \
2026                 .name = _name_str, \
2027                 .type = V4L2_CTRL_TYPE_INTEGER, \
2028                 .flags = V4L2_CTRL_FLAG_SLIDER, \
2029                 .min = 0, \
2030                 .max = 8191, \
2031                 .step = 1, \
2032                 .def = 512, \
2033         }
2034
2035 ISC_CTRL_GAIN(isc_r_gain_ctrl, ISC_CID_R_GAIN, "Red Component Gain");
2036 ISC_CTRL_GAIN(isc_b_gain_ctrl, ISC_CID_B_GAIN, "Blue Component Gain");
2037 ISC_CTRL_GAIN(isc_gr_gain_ctrl, ISC_CID_GR_GAIN, "Green Red Component Gain");
2038 ISC_CTRL_GAIN(isc_gb_gain_ctrl, ISC_CID_GB_GAIN, "Green Blue Component Gain");
2039
2040 static int isc_ctrl_init(struct isc_device *isc)
2041 {
2042         const struct v4l2_ctrl_ops *ops = &isc_ctrl_ops;
2043         struct isc_ctrls *ctrls = &isc->ctrls;
2044         struct v4l2_ctrl_handler *hdl = &ctrls->handler;
2045         int ret;
2046
2047         ctrls->hist_stat = HIST_INIT;
2048         isc_reset_awb_ctrls(isc);
2049
2050         ret = v4l2_ctrl_handler_init(hdl, 13);
2051         if (ret < 0)
2052                 return ret;
2053
2054         /* Initialize product specific controls. For example, contrast */
2055         isc->config_ctrls(isc, ops);
2056
2057         ctrls->brightness = 0;
2058
2059         v4l2_ctrl_new_std(hdl, ops, V4L2_CID_BRIGHTNESS, -1024, 1023, 1, 0);
2060         v4l2_ctrl_new_std(hdl, ops, V4L2_CID_GAMMA, 0, isc->gamma_max, 1,
2061                           isc->gamma_max);
2062         isc->awb_ctrl = v4l2_ctrl_new_std(hdl, &isc_awb_ops,
2063                                           V4L2_CID_AUTO_WHITE_BALANCE,
2064                                           0, 1, 1, 1);
2065
2066         /* do_white_balance is a button, so min,max,step,default are ignored */
2067         isc->do_wb_ctrl = v4l2_ctrl_new_std(hdl, &isc_awb_ops,
2068                                             V4L2_CID_DO_WHITE_BALANCE,
2069                                             0, 0, 0, 0);
2070
2071         if (!isc->do_wb_ctrl) {
2072                 ret = hdl->error;
2073                 v4l2_ctrl_handler_free(hdl);
2074                 return ret;
2075         }
2076
2077         v4l2_ctrl_activate(isc->do_wb_ctrl, false);
2078
2079         isc->r_gain_ctrl = v4l2_ctrl_new_custom(hdl, &isc_r_gain_ctrl, NULL);
2080         isc->b_gain_ctrl = v4l2_ctrl_new_custom(hdl, &isc_b_gain_ctrl, NULL);
2081         isc->gr_gain_ctrl = v4l2_ctrl_new_custom(hdl, &isc_gr_gain_ctrl, NULL);
2082         isc->gb_gain_ctrl = v4l2_ctrl_new_custom(hdl, &isc_gb_gain_ctrl, NULL);
2083         isc->r_off_ctrl = v4l2_ctrl_new_custom(hdl, &isc_r_off_ctrl, NULL);
2084         isc->b_off_ctrl = v4l2_ctrl_new_custom(hdl, &isc_b_off_ctrl, NULL);
2085         isc->gr_off_ctrl = v4l2_ctrl_new_custom(hdl, &isc_gr_off_ctrl, NULL);
2086         isc->gb_off_ctrl = v4l2_ctrl_new_custom(hdl, &isc_gb_off_ctrl, NULL);
2087
2088         /*
2089          * The cluster is in auto mode with autowhitebalance enabled
2090          * and manual mode otherwise.
2091          */
2092         v4l2_ctrl_auto_cluster(10, &isc->awb_ctrl, 0, true);
2093
2094         v4l2_ctrl_handler_setup(hdl);
2095
2096         return 0;
2097 }
2098
2099 static int isc_async_bound(struct v4l2_async_notifier *notifier,
2100                             struct v4l2_subdev *subdev,
2101                             struct v4l2_async_subdev *asd)
2102 {
2103         struct isc_device *isc = container_of(notifier->v4l2_dev,
2104                                               struct isc_device, v4l2_dev);
2105         struct isc_subdev_entity *subdev_entity =
2106                 container_of(notifier, struct isc_subdev_entity, notifier);
2107
2108         if (video_is_registered(&isc->video_dev)) {
2109                 v4l2_err(&isc->v4l2_dev, "only supports one sub-device.\n");
2110                 return -EBUSY;
2111         }
2112
2113         subdev_entity->sd = subdev;
2114
2115         return 0;
2116 }
2117
2118 static void isc_async_unbind(struct v4l2_async_notifier *notifier,
2119                               struct v4l2_subdev *subdev,
2120                               struct v4l2_async_subdev *asd)
2121 {
2122         struct isc_device *isc = container_of(notifier->v4l2_dev,
2123                                               struct isc_device, v4l2_dev);
2124         cancel_work_sync(&isc->awb_work);
2125         video_unregister_device(&isc->video_dev);
2126         v4l2_ctrl_handler_free(&isc->ctrls.handler);
2127 }
2128
2129 static struct isc_format *find_format_by_code(unsigned int code, int *index)
2130 {
2131         struct isc_format *fmt = &formats_list[0];
2132         unsigned int i;
2133
2134         for (i = 0; i < ARRAY_SIZE(formats_list); i++) {
2135                 if (fmt->mbus_code == code) {
2136                         *index = i;
2137                         return fmt;
2138                 }
2139
2140                 fmt++;
2141         }
2142
2143         return NULL;
2144 }
2145
2146 static int isc_formats_init(struct isc_device *isc)
2147 {
2148         struct isc_format *fmt;
2149         struct v4l2_subdev *subdev = isc->current_subdev->sd;
2150         unsigned int num_fmts, i, j;
2151         u32 list_size = ARRAY_SIZE(formats_list);
2152         struct v4l2_subdev_mbus_code_enum mbus_code = {
2153                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
2154         };
2155
2156         num_fmts = 0;
2157         while (!v4l2_subdev_call(subdev, pad, enum_mbus_code,
2158                NULL, &mbus_code)) {
2159                 mbus_code.index++;
2160
2161                 fmt = find_format_by_code(mbus_code.code, &i);
2162                 if (!fmt) {
2163                         v4l2_warn(&isc->v4l2_dev, "Mbus code %x not supported\n",
2164                                   mbus_code.code);
2165                         continue;
2166                 }
2167
2168                 fmt->sd_support = true;
2169                 num_fmts++;
2170         }
2171
2172         if (!num_fmts)
2173                 return -ENXIO;
2174
2175         isc->num_user_formats = num_fmts;
2176         isc->user_formats = devm_kcalloc(isc->dev,
2177                                          num_fmts, sizeof(*isc->user_formats),
2178                                          GFP_KERNEL);
2179         if (!isc->user_formats)
2180                 return -ENOMEM;
2181
2182         fmt = &formats_list[0];
2183         for (i = 0, j = 0; i < list_size; i++) {
2184                 if (fmt->sd_support)
2185                         isc->user_formats[j++] = fmt;
2186                 fmt++;
2187         }
2188
2189         return 0;
2190 }
2191
2192 static int isc_set_default_fmt(struct isc_device *isc)
2193 {
2194         struct v4l2_format f = {
2195                 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2196                 .fmt.pix = {
2197                         .width          = VGA_WIDTH,
2198                         .height         = VGA_HEIGHT,
2199                         .field          = V4L2_FIELD_NONE,
2200                         .pixelformat    = isc->user_formats[0]->fourcc,
2201                 },
2202         };
2203         int ret;
2204
2205         ret = isc_try_fmt(isc, &f, NULL);
2206         if (ret)
2207                 return ret;
2208
2209         isc->fmt = f;
2210         return 0;
2211 }
2212
2213 static int isc_async_complete(struct v4l2_async_notifier *notifier)
2214 {
2215         struct isc_device *isc = container_of(notifier->v4l2_dev,
2216                                               struct isc_device, v4l2_dev);
2217         struct video_device *vdev = &isc->video_dev;
2218         struct vb2_queue *q = &isc->vb2_vidq;
2219         int ret = 0;
2220
2221         INIT_WORK(&isc->awb_work, isc_awb_work);
2222
2223         ret = v4l2_device_register_subdev_nodes(&isc->v4l2_dev);
2224         if (ret < 0) {
2225                 v4l2_err(&isc->v4l2_dev, "Failed to register subdev nodes\n");
2226                 return ret;
2227         }
2228
2229         isc->current_subdev = container_of(notifier,
2230                                            struct isc_subdev_entity, notifier);
2231         mutex_init(&isc->lock);
2232         init_completion(&isc->comp);
2233
2234         /* Initialize videobuf2 queue */
2235         q->type                 = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2236         q->io_modes             = VB2_MMAP | VB2_DMABUF | VB2_READ;
2237         q->drv_priv             = isc;
2238         q->buf_struct_size      = sizeof(struct isc_buffer);
2239         q->ops                  = &isc_vb2_ops;
2240         q->mem_ops              = &vb2_dma_contig_memops;
2241         q->timestamp_flags      = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
2242         q->lock                 = &isc->lock;
2243         q->min_buffers_needed   = 1;
2244         q->dev                  = isc->dev;
2245
2246         ret = vb2_queue_init(q);
2247         if (ret < 0) {
2248                 v4l2_err(&isc->v4l2_dev,
2249                          "vb2_queue_init() failed: %d\n", ret);
2250                 goto isc_async_complete_err;
2251         }
2252
2253         /* Init video dma queues */
2254         INIT_LIST_HEAD(&isc->dma_queue);
2255         spin_lock_init(&isc->dma_queue_lock);
2256         spin_lock_init(&isc->awb_lock);
2257
2258         ret = isc_formats_init(isc);
2259         if (ret < 0) {
2260                 v4l2_err(&isc->v4l2_dev,
2261                          "Init format failed: %d\n", ret);
2262                 goto isc_async_complete_err;
2263         }
2264
2265         ret = isc_set_default_fmt(isc);
2266         if (ret) {
2267                 v4l2_err(&isc->v4l2_dev, "Could not set default format\n");
2268                 goto isc_async_complete_err;
2269         }
2270
2271         ret = isc_ctrl_init(isc);
2272         if (ret) {
2273                 v4l2_err(&isc->v4l2_dev, "Init isc ctrols failed: %d\n", ret);
2274                 goto isc_async_complete_err;
2275         }
2276
2277         /* Register video device */
2278         strscpy(vdev->name, "microchip-isc", sizeof(vdev->name));
2279         vdev->release           = video_device_release_empty;
2280         vdev->fops              = &isc_fops;
2281         vdev->ioctl_ops         = &isc_ioctl_ops;
2282         vdev->v4l2_dev          = &isc->v4l2_dev;
2283         vdev->vfl_dir           = VFL_DIR_RX;
2284         vdev->queue             = q;
2285         vdev->lock              = &isc->lock;
2286         vdev->ctrl_handler      = &isc->ctrls.handler;
2287         vdev->device_caps       = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_CAPTURE;
2288         video_set_drvdata(vdev, isc);
2289
2290         ret = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
2291         if (ret < 0) {
2292                 v4l2_err(&isc->v4l2_dev,
2293                          "video_register_device failed: %d\n", ret);
2294                 goto isc_async_complete_err;
2295         }
2296
2297         return 0;
2298
2299 isc_async_complete_err:
2300         mutex_destroy(&isc->lock);
2301         return ret;
2302 }
2303
2304 const struct v4l2_async_notifier_operations isc_async_ops = {
2305         .bound = isc_async_bound,
2306         .unbind = isc_async_unbind,
2307         .complete = isc_async_complete,
2308 };
2309
2310 void isc_subdev_cleanup(struct isc_device *isc)
2311 {
2312         struct isc_subdev_entity *subdev_entity;
2313
2314         list_for_each_entry(subdev_entity, &isc->subdev_entities, list) {
2315                 v4l2_async_notifier_unregister(&subdev_entity->notifier);
2316                 v4l2_async_notifier_cleanup(&subdev_entity->notifier);
2317         }
2318
2319         INIT_LIST_HEAD(&isc->subdev_entities);
2320 }
2321
2322 int isc_pipeline_init(struct isc_device *isc)
2323 {
2324         struct device *dev = isc->dev;
2325         struct regmap *regmap = isc->regmap;
2326         struct regmap_field *regs;
2327         unsigned int i;
2328
2329         /*
2330          * DPCEN-->GDCEN-->BLCEN-->WB-->CFA-->CC-->
2331          * GAM-->VHXS-->CSC-->CBC-->SUB422-->SUB420
2332          */
2333         const struct reg_field regfields[ISC_PIPE_LINE_NODE_NUM] = {
2334                 REG_FIELD(ISC_DPC_CTRL, 0, 0),
2335                 REG_FIELD(ISC_DPC_CTRL, 1, 1),
2336                 REG_FIELD(ISC_DPC_CTRL, 2, 2),
2337                 REG_FIELD(ISC_WB_CTRL, 0, 0),
2338                 REG_FIELD(ISC_CFA_CTRL, 0, 0),
2339                 REG_FIELD(ISC_CC_CTRL, 0, 0),
2340                 REG_FIELD(ISC_GAM_CTRL, 0, 0),
2341                 REG_FIELD(ISC_GAM_CTRL, 1, 1),
2342                 REG_FIELD(ISC_GAM_CTRL, 2, 2),
2343                 REG_FIELD(ISC_GAM_CTRL, 3, 3),
2344                 REG_FIELD(ISC_VHXS_CTRL, 0, 0),
2345                 REG_FIELD(ISC_CSC_CTRL + isc->offsets.csc, 0, 0),
2346                 REG_FIELD(ISC_CBC_CTRL + isc->offsets.cbc, 0, 0),
2347                 REG_FIELD(ISC_SUB422_CTRL + isc->offsets.sub422, 0, 0),
2348                 REG_FIELD(ISC_SUB420_CTRL + isc->offsets.sub420, 0, 0),
2349         };
2350
2351         for (i = 0; i < ISC_PIPE_LINE_NODE_NUM; i++) {
2352                 regs = devm_regmap_field_alloc(dev, regmap, regfields[i]);
2353                 if (IS_ERR(regs))
2354                         return PTR_ERR(regs);
2355
2356                 isc->pipeline[i] =  regs;
2357         }
2358
2359         return 0;
2360 }
2361
2362 /* regmap configuration */
2363 #define ATMEL_ISC_REG_MAX    0xd5c
2364 const struct regmap_config isc_regmap_config = {
2365         .reg_bits       = 32,
2366         .reg_stride     = 4,
2367         .val_bits       = 32,
2368         .max_register   = ATMEL_ISC_REG_MAX,
2369 };
2370