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