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