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