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