1 /*
2  * imx274.c - IMX274 CMOS Image Sensor driver
3  *
4  * Copyright (C) 2017, Leopard Imaging, Inc.
5  *
6  * Leon Luo <leonl@leopardimaging.com>
7  * Edwin Zou <edwinz@leopardimaging.com>
8  * Luca Ceresoli <luca@lucaceresoli.net>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms and conditions of the GNU General Public License,
12  * version 2, as published by the Free Software Foundation.
13  *
14  * This program is distributed in the hope it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
17  * more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22 
23 #include <linux/clk.h>
24 #include <linux/delay.h>
25 #include <linux/gpio.h>
26 #include <linux/gpio/consumer.h>
27 #include <linux/i2c.h>
28 #include <linux/init.h>
29 #include <linux/kernel.h>
30 #include <linux/module.h>
31 #include <linux/of_gpio.h>
32 #include <linux/regmap.h>
33 #include <linux/slab.h>
34 #include <linux/v4l2-mediabus.h>
35 #include <linux/videodev2.h>
36 
37 #include <media/v4l2-ctrls.h>
38 #include <media/v4l2-device.h>
39 #include <media/v4l2-subdev.h>
40 
41 /*
42  * See "SHR, SVR Setting" in datasheet
43  */
44 #define IMX274_DEFAULT_FRAME_LENGTH		(4550)
45 #define IMX274_MAX_FRAME_LENGTH			(0x000fffff)
46 
47 /*
48  * See "Frame Rate Adjustment" in datasheet
49  */
50 #define IMX274_PIXCLK_CONST1			(72000000)
51 #define IMX274_PIXCLK_CONST2			(1000000)
52 
53 /*
54  * The input gain is shifted by IMX274_GAIN_SHIFT to get
55  * decimal number. The real gain is
56  * (float)input_gain_value / (1 << IMX274_GAIN_SHIFT)
57  */
58 #define IMX274_GAIN_SHIFT			(8)
59 #define IMX274_GAIN_SHIFT_MASK			((1 << IMX274_GAIN_SHIFT) - 1)
60 
61 /*
62  * See "Analog Gain" and "Digital Gain" in datasheet
63  * min gain is 1X
64  * max gain is calculated based on IMX274_GAIN_REG_MAX
65  */
66 #define IMX274_GAIN_REG_MAX			(1957)
67 #define IMX274_MIN_GAIN				(0x01 << IMX274_GAIN_SHIFT)
68 #define IMX274_MAX_ANALOG_GAIN			((2048 << IMX274_GAIN_SHIFT)\
69 					/ (2048 - IMX274_GAIN_REG_MAX))
70 #define IMX274_MAX_DIGITAL_GAIN			(8)
71 #define IMX274_DEF_GAIN				(20 << IMX274_GAIN_SHIFT)
72 #define IMX274_GAIN_CONST			(2048) /* for gain formula */
73 
74 /*
75  * 1 line time in us = (HMAX / 72), minimal is 4 lines
76  */
77 #define IMX274_MIN_EXPOSURE_TIME		(4 * 260 / 72)
78 
79 #define IMX274_DEFAULT_MODE			IMX274_BINNING_OFF
80 #define IMX274_MAX_WIDTH			(3840)
81 #define IMX274_MAX_HEIGHT			(2160)
82 #define IMX274_MAX_FRAME_RATE			(120)
83 #define IMX274_MIN_FRAME_RATE			(5)
84 #define IMX274_DEF_FRAME_RATE			(60)
85 
86 /*
87  * register SHR is limited to (SVR value + 1) x VMAX value - 4
88  */
89 #define IMX274_SHR_LIMIT_CONST			(4)
90 
91 /*
92  * Min and max sensor reset delay (microseconds)
93  */
94 #define IMX274_RESET_DELAY1			(2000)
95 #define IMX274_RESET_DELAY2			(2200)
96 
97 /*
98  * shift and mask constants
99  */
100 #define IMX274_SHIFT_8_BITS			(8)
101 #define IMX274_SHIFT_16_BITS			(16)
102 #define IMX274_MASK_LSB_2_BITS			(0x03)
103 #define IMX274_MASK_LSB_3_BITS			(0x07)
104 #define IMX274_MASK_LSB_4_BITS			(0x0f)
105 #define IMX274_MASK_LSB_8_BITS			(0x00ff)
106 
107 #define DRIVER_NAME "IMX274"
108 
109 /*
110  * IMX274 register definitions
111  */
112 #define IMX274_SHR_REG_MSB			0x300D /* SHR */
113 #define IMX274_SHR_REG_LSB			0x300C /* SHR */
114 #define IMX274_SVR_REG_MSB			0x300F /* SVR */
115 #define IMX274_SVR_REG_LSB			0x300E /* SVR */
116 #define IMX274_HTRIM_EN_REG			0x3037
117 #define IMX274_HTRIM_START_REG_LSB		0x3038
118 #define IMX274_HTRIM_START_REG_MSB		0x3039
119 #define IMX274_HTRIM_END_REG_LSB		0x303A
120 #define IMX274_HTRIM_END_REG_MSB		0x303B
121 #define IMX274_VWIDCUTEN_REG			0x30DD
122 #define IMX274_VWIDCUT_REG_LSB			0x30DE
123 #define IMX274_VWIDCUT_REG_MSB			0x30DF
124 #define IMX274_VWINPOS_REG_LSB			0x30E0
125 #define IMX274_VWINPOS_REG_MSB			0x30E1
126 #define IMX274_WRITE_VSIZE_REG_LSB		0x3130
127 #define IMX274_WRITE_VSIZE_REG_MSB		0x3131
128 #define IMX274_Y_OUT_SIZE_REG_LSB		0x3132
129 #define IMX274_Y_OUT_SIZE_REG_MSB		0x3133
130 #define IMX274_VMAX_REG_1			0x30FA /* VMAX, MSB */
131 #define IMX274_VMAX_REG_2			0x30F9 /* VMAX */
132 #define IMX274_VMAX_REG_3			0x30F8 /* VMAX, LSB */
133 #define IMX274_HMAX_REG_MSB			0x30F7 /* HMAX */
134 #define IMX274_HMAX_REG_LSB			0x30F6 /* HMAX */
135 #define IMX274_ANALOG_GAIN_ADDR_LSB		0x300A /* ANALOG GAIN LSB */
136 #define IMX274_ANALOG_GAIN_ADDR_MSB		0x300B /* ANALOG GAIN MSB */
137 #define IMX274_DIGITAL_GAIN_REG			0x3012 /* Digital Gain */
138 #define IMX274_VFLIP_REG			0x301A /* VERTICAL FLIP */
139 #define IMX274_TEST_PATTERN_REG			0x303D /* TEST PATTERN */
140 #define IMX274_STANDBY_REG			0x3000 /* STANDBY */
141 
142 #define IMX274_TABLE_WAIT_MS			0
143 #define IMX274_TABLE_END			1
144 
145 /*
146  * imx274 I2C operation related structure
147  */
148 struct reg_8 {
149 	u16 addr;
150 	u8 val;
151 };
152 
153 static const struct regmap_config imx274_regmap_config = {
154 	.reg_bits = 16,
155 	.val_bits = 8,
156 	.cache_type = REGCACHE_RBTREE,
157 };
158 
159 enum imx274_binning {
160 	IMX274_BINNING_OFF,
161 	IMX274_BINNING_2_1,
162 	IMX274_BINNING_3_1,
163 };
164 
165 /*
166  * Parameters for each imx274 readout mode.
167  *
168  * These are the values to configure the sensor in one of the
169  * implemented modes.
170  *
171  * @init_regs: registers to initialize the mode
172  * @bin_ratio: downscale factor (e.g. 3 for 3:1 binning)
173  * @min_frame_len: Minimum frame length for each mode (see "Frame Rate
174  *                 Adjustment (CSI-2)" in the datasheet)
175  * @min_SHR: Minimum SHR register value (see "Shutter Setting (CSI-2)" in the
176  *           datasheet)
177  * @max_fps: Maximum frames per second
178  * @nocpiop: Number of clocks per internal offset period (see "Integration Time
179  *           in Each Readout Drive Mode (CSI-2)" in the datasheet)
180  */
181 struct imx274_frmfmt {
182 	const struct reg_8 *init_regs;
183 	unsigned int bin_ratio;
184 	int min_frame_len;
185 	int min_SHR;
186 	int max_fps;
187 	int nocpiop;
188 };
189 
190 /*
191  * imx274 test pattern related structure
192  */
193 enum {
194 	TEST_PATTERN_DISABLED = 0,
195 	TEST_PATTERN_ALL_000H,
196 	TEST_PATTERN_ALL_FFFH,
197 	TEST_PATTERN_ALL_555H,
198 	TEST_PATTERN_ALL_AAAH,
199 	TEST_PATTERN_VSP_5AH, /* VERTICAL STRIPE PATTERN 555H/AAAH */
200 	TEST_PATTERN_VSP_A5H, /* VERTICAL STRIPE PATTERN AAAH/555H */
201 	TEST_PATTERN_VSP_05H, /* VERTICAL STRIPE PATTERN 000H/555H */
202 	TEST_PATTERN_VSP_50H, /* VERTICAL STRIPE PATTERN 555H/000H */
203 	TEST_PATTERN_VSP_0FH, /* VERTICAL STRIPE PATTERN 000H/FFFH */
204 	TEST_PATTERN_VSP_F0H, /* VERTICAL STRIPE PATTERN FFFH/000H */
205 	TEST_PATTERN_H_COLOR_BARS,
206 	TEST_PATTERN_V_COLOR_BARS,
207 };
208 
209 static const char * const tp_qmenu[] = {
210 	"Disabled",
211 	"All 000h Pattern",
212 	"All FFFh Pattern",
213 	"All 555h Pattern",
214 	"All AAAh Pattern",
215 	"Vertical Stripe (555h / AAAh)",
216 	"Vertical Stripe (AAAh / 555h)",
217 	"Vertical Stripe (000h / 555h)",
218 	"Vertical Stripe (555h / 000h)",
219 	"Vertical Stripe (000h / FFFh)",
220 	"Vertical Stripe (FFFh / 000h)",
221 	"Horizontal Color Bars",
222 	"Vertical Color Bars",
223 };
224 
225 /*
226  * All-pixel scan mode (10-bit)
227  * imx274 mode1(refer to datasheet) register configuration with
228  * 3840x2160 resolution, raw10 data and mipi four lane output
229  */
230 static const struct reg_8 imx274_mode1_3840x2160_raw10[] = {
231 	{0x3004, 0x01},
232 	{0x3005, 0x01},
233 	{0x3006, 0x00},
234 	{0x3007, 0xa2},
235 
236 	{0x3018, 0xA2}, /* output XVS, HVS */
237 
238 	{0x306B, 0x05},
239 	{0x30E2, 0x01},
240 
241 	{0x30EE, 0x01},
242 	{0x3342, 0x0A},
243 	{0x3343, 0x00},
244 	{0x3344, 0x16},
245 	{0x3345, 0x00},
246 	{0x33A6, 0x01},
247 	{0x3528, 0x0E},
248 	{0x3554, 0x1F},
249 	{0x3555, 0x01},
250 	{0x3556, 0x01},
251 	{0x3557, 0x01},
252 	{0x3558, 0x01},
253 	{0x3559, 0x00},
254 	{0x355A, 0x00},
255 	{0x35BA, 0x0E},
256 	{0x366A, 0x1B},
257 	{0x366B, 0x1A},
258 	{0x366C, 0x19},
259 	{0x366D, 0x17},
260 	{0x3A41, 0x08},
261 
262 	{IMX274_TABLE_END, 0x00}
263 };
264 
265 /*
266  * Horizontal/vertical 2/2-line binning
267  * (Horizontal and vertical weightedbinning, 10-bit)
268  * imx274 mode3(refer to datasheet) register configuration with
269  * 1920x1080 resolution, raw10 data and mipi four lane output
270  */
271 static const struct reg_8 imx274_mode3_1920x1080_raw10[] = {
272 	{0x3004, 0x02},
273 	{0x3005, 0x21},
274 	{0x3006, 0x00},
275 	{0x3007, 0xb1},
276 
277 	{0x3018, 0xA2}, /* output XVS, HVS */
278 
279 	{0x306B, 0x05},
280 	{0x30E2, 0x02},
281 
282 	{0x30EE, 0x01},
283 	{0x3342, 0x0A},
284 	{0x3343, 0x00},
285 	{0x3344, 0x1A},
286 	{0x3345, 0x00},
287 	{0x33A6, 0x01},
288 	{0x3528, 0x0E},
289 	{0x3554, 0x00},
290 	{0x3555, 0x01},
291 	{0x3556, 0x01},
292 	{0x3557, 0x01},
293 	{0x3558, 0x01},
294 	{0x3559, 0x00},
295 	{0x355A, 0x00},
296 	{0x35BA, 0x0E},
297 	{0x366A, 0x1B},
298 	{0x366B, 0x1A},
299 	{0x366C, 0x19},
300 	{0x366D, 0x17},
301 	{0x3A41, 0x08},
302 
303 	{IMX274_TABLE_END, 0x00}
304 };
305 
306 /*
307  * Vertical 2/3 subsampling binning horizontal 3 binning
308  * imx274 mode5(refer to datasheet) register configuration with
309  * 1280x720 resolution, raw10 data and mipi four lane output
310  */
311 static const struct reg_8 imx274_mode5_1280x720_raw10[] = {
312 	{0x3004, 0x03},
313 	{0x3005, 0x31},
314 	{0x3006, 0x00},
315 	{0x3007, 0xa9},
316 
317 	{0x3018, 0xA2}, /* output XVS, HVS */
318 
319 	{0x306B, 0x05},
320 	{0x30E2, 0x03},
321 
322 	{0x30EE, 0x01},
323 	{0x3342, 0x0A},
324 	{0x3343, 0x00},
325 	{0x3344, 0x1B},
326 	{0x3345, 0x00},
327 	{0x33A6, 0x01},
328 	{0x3528, 0x0E},
329 	{0x3554, 0x00},
330 	{0x3555, 0x01},
331 	{0x3556, 0x01},
332 	{0x3557, 0x01},
333 	{0x3558, 0x01},
334 	{0x3559, 0x00},
335 	{0x355A, 0x00},
336 	{0x35BA, 0x0E},
337 	{0x366A, 0x1B},
338 	{0x366B, 0x19},
339 	{0x366C, 0x17},
340 	{0x366D, 0x17},
341 	{0x3A41, 0x04},
342 
343 	{IMX274_TABLE_END, 0x00}
344 };
345 
346 /*
347  * imx274 first step register configuration for
348  * starting stream
349  */
350 static const struct reg_8 imx274_start_1[] = {
351 	{IMX274_STANDBY_REG, 0x12},
352 	{IMX274_TABLE_END, 0x00}
353 };
354 
355 /*
356  * imx274 second step register configuration for
357  * starting stream
358  */
359 static const struct reg_8 imx274_start_2[] = {
360 	{0x3120, 0xF0}, /* clock settings */
361 	{0x3121, 0x00}, /* clock settings */
362 	{0x3122, 0x02}, /* clock settings */
363 	{0x3129, 0x9C}, /* clock settings */
364 	{0x312A, 0x02}, /* clock settings */
365 	{0x312D, 0x02}, /* clock settings */
366 
367 	{0x310B, 0x00},
368 
369 	/* PLSTMG */
370 	{0x304C, 0x00}, /* PLSTMG01 */
371 	{0x304D, 0x03},
372 	{0x331C, 0x1A},
373 	{0x331D, 0x00},
374 	{0x3502, 0x02},
375 	{0x3529, 0x0E},
376 	{0x352A, 0x0E},
377 	{0x352B, 0x0E},
378 	{0x3538, 0x0E},
379 	{0x3539, 0x0E},
380 	{0x3553, 0x00},
381 	{0x357D, 0x05},
382 	{0x357F, 0x05},
383 	{0x3581, 0x04},
384 	{0x3583, 0x76},
385 	{0x3587, 0x01},
386 	{0x35BB, 0x0E},
387 	{0x35BC, 0x0E},
388 	{0x35BD, 0x0E},
389 	{0x35BE, 0x0E},
390 	{0x35BF, 0x0E},
391 	{0x366E, 0x00},
392 	{0x366F, 0x00},
393 	{0x3670, 0x00},
394 	{0x3671, 0x00},
395 
396 	/* PSMIPI */
397 	{0x3304, 0x32}, /* PSMIPI1 */
398 	{0x3305, 0x00},
399 	{0x3306, 0x32},
400 	{0x3307, 0x00},
401 	{0x3590, 0x32},
402 	{0x3591, 0x00},
403 	{0x3686, 0x32},
404 	{0x3687, 0x00},
405 
406 	{IMX274_TABLE_END, 0x00}
407 };
408 
409 /*
410  * imx274 third step register configuration for
411  * starting stream
412  */
413 static const struct reg_8 imx274_start_3[] = {
414 	{IMX274_STANDBY_REG, 0x00},
415 	{0x303E, 0x02}, /* SYS_MODE = 2 */
416 	{IMX274_TABLE_END, 0x00}
417 };
418 
419 /*
420  * imx274 forth step register configuration for
421  * starting stream
422  */
423 static const struct reg_8 imx274_start_4[] = {
424 	{0x30F4, 0x00},
425 	{0x3018, 0xA2}, /* XHS VHS OUTUPT */
426 	{IMX274_TABLE_END, 0x00}
427 };
428 
429 /*
430  * imx274 register configuration for stoping stream
431  */
432 static const struct reg_8 imx274_stop[] = {
433 	{IMX274_STANDBY_REG, 0x01},
434 	{IMX274_TABLE_END, 0x00}
435 };
436 
437 /*
438  * imx274 disable test pattern register configuration
439  */
440 static const struct reg_8 imx274_tp_disabled[] = {
441 	{0x303C, 0x00},
442 	{0x377F, 0x00},
443 	{0x3781, 0x00},
444 	{0x370B, 0x00},
445 	{IMX274_TABLE_END, 0x00}
446 };
447 
448 /*
449  * imx274 test pattern register configuration
450  * reg 0x303D defines the test pattern modes
451  */
452 static const struct reg_8 imx274_tp_regs[] = {
453 	{0x303C, 0x11},
454 	{0x370E, 0x01},
455 	{0x377F, 0x01},
456 	{0x3781, 0x01},
457 	{0x370B, 0x11},
458 	{IMX274_TABLE_END, 0x00}
459 };
460 
461 /* nocpiop happens to be the same number for the implemented modes */
462 static const struct imx274_frmfmt imx274_formats[] = {
463 	{
464 		/* mode 1, 4K */
465 		.bin_ratio = 1,
466 		.init_regs = imx274_mode1_3840x2160_raw10,
467 		.min_frame_len = 4550,
468 		.min_SHR = 12,
469 		.max_fps = 60,
470 		.nocpiop = 112,
471 	},
472 	{
473 		/* mode 3, 1080p */
474 		.bin_ratio = 2,
475 		.init_regs = imx274_mode3_1920x1080_raw10,
476 		.min_frame_len = 2310,
477 		.min_SHR = 8,
478 		.max_fps = 120,
479 		.nocpiop = 112,
480 	},
481 	{
482 		/* mode 5, 720p */
483 		.bin_ratio = 3,
484 		.init_regs = imx274_mode5_1280x720_raw10,
485 		.min_frame_len = 2310,
486 		.min_SHR = 8,
487 		.max_fps = 120,
488 		.nocpiop = 112,
489 	},
490 };
491 
492 /*
493  * struct imx274_ctrls - imx274 ctrl structure
494  * @handler: V4L2 ctrl handler structure
495  * @exposure: Pointer to expsure ctrl structure
496  * @gain: Pointer to gain ctrl structure
497  * @vflip: Pointer to vflip ctrl structure
498  * @test_pattern: Pointer to test pattern ctrl structure
499  */
500 struct imx274_ctrls {
501 	struct v4l2_ctrl_handler handler;
502 	struct v4l2_ctrl *exposure;
503 	struct v4l2_ctrl *gain;
504 	struct v4l2_ctrl *vflip;
505 	struct v4l2_ctrl *test_pattern;
506 };
507 
508 /*
509  * struct stim274 - imx274 device structure
510  * @sd: V4L2 subdevice structure
511  * @pad: Media pad structure
512  * @client: Pointer to I2C client
513  * @ctrls: imx274 control structure
514  * @crop: rect to be captured
515  * @compose: compose rect, i.e. output resolution
516  * @format: V4L2 media bus frame format structure
517  *          (width and height are in sync with the compose rect)
518  * @frame_rate: V4L2 frame rate structure
519  * @regmap: Pointer to regmap structure
520  * @reset_gpio: Pointer to reset gpio
521  * @lock: Mutex structure
522  * @mode: Parameters for the selected readout mode
523  */
524 struct stimx274 {
525 	struct v4l2_subdev sd;
526 	struct media_pad pad;
527 	struct i2c_client *client;
528 	struct imx274_ctrls ctrls;
529 	struct v4l2_rect crop;
530 	struct v4l2_mbus_framefmt format;
531 	struct v4l2_fract frame_interval;
532 	struct regmap *regmap;
533 	struct gpio_desc *reset_gpio;
534 	struct mutex lock; /* mutex lock for operations */
535 	const struct imx274_frmfmt *mode;
536 };
537 
538 #define IMX274_ROUND(dim, step, flags)			\
539 	((flags) & V4L2_SEL_FLAG_GE			\
540 	 ? roundup((dim), (step))			\
541 	 : ((flags) & V4L2_SEL_FLAG_LE			\
542 	    ? rounddown((dim), (step))			\
543 	    : rounddown((dim) + (step) / 2, (step))))
544 
545 /*
546  * Function declaration
547  */
548 static int imx274_set_gain(struct stimx274 *priv, struct v4l2_ctrl *ctrl);
549 static int imx274_set_exposure(struct stimx274 *priv, int val);
550 static int imx274_set_vflip(struct stimx274 *priv, int val);
551 static int imx274_set_test_pattern(struct stimx274 *priv, int val);
552 static int imx274_set_frame_interval(struct stimx274 *priv,
553 				     struct v4l2_fract frame_interval);
554 
msleep_range(unsigned int delay_base)555 static inline void msleep_range(unsigned int delay_base)
556 {
557 	usleep_range(delay_base * 1000, delay_base * 1000 + 500);
558 }
559 
560 /*
561  * v4l2_ctrl and v4l2_subdev related operations
562  */
ctrl_to_sd(struct v4l2_ctrl * ctrl)563 static inline struct v4l2_subdev *ctrl_to_sd(struct v4l2_ctrl *ctrl)
564 {
565 	return &container_of(ctrl->handler,
566 			     struct stimx274, ctrls.handler)->sd;
567 }
568 
to_imx274(struct v4l2_subdev * sd)569 static inline struct stimx274 *to_imx274(struct v4l2_subdev *sd)
570 {
571 	return container_of(sd, struct stimx274, sd);
572 }
573 
574 /*
575  * Writing a register table
576  *
577  * @priv: Pointer to device
578  * @table: Table containing register values (with optional delays)
579  *
580  * This is used to write register table into sensor's reg map.
581  *
582  * Return: 0 on success, errors otherwise
583  */
imx274_write_table(struct stimx274 * priv,const struct reg_8 table[])584 static int imx274_write_table(struct stimx274 *priv, const struct reg_8 table[])
585 {
586 	struct regmap *regmap = priv->regmap;
587 	int err = 0;
588 	const struct reg_8 *next;
589 	u8 val;
590 
591 	int range_start = -1;
592 	int range_count = 0;
593 	u8 range_vals[16];
594 	int max_range_vals = ARRAY_SIZE(range_vals);
595 
596 	for (next = table;; next++) {
597 		if ((next->addr != range_start + range_count) ||
598 		    (next->addr == IMX274_TABLE_END) ||
599 		    (next->addr == IMX274_TABLE_WAIT_MS) ||
600 		    (range_count == max_range_vals)) {
601 			if (range_count == 1)
602 				err = regmap_write(regmap,
603 						   range_start, range_vals[0]);
604 			else if (range_count > 1)
605 				err = regmap_bulk_write(regmap, range_start,
606 							&range_vals[0],
607 							range_count);
608 			else
609 				err = 0;
610 
611 			if (err)
612 				return err;
613 
614 			range_start = -1;
615 			range_count = 0;
616 
617 			/* Handle special address values */
618 			if (next->addr == IMX274_TABLE_END)
619 				break;
620 
621 			if (next->addr == IMX274_TABLE_WAIT_MS) {
622 				msleep_range(next->val);
623 				continue;
624 			}
625 		}
626 
627 		val = next->val;
628 
629 		if (range_start == -1)
630 			range_start = next->addr;
631 
632 		range_vals[range_count++] = val;
633 	}
634 	return 0;
635 }
636 
imx274_read_reg(struct stimx274 * priv,u16 addr,u8 * val)637 static inline int imx274_read_reg(struct stimx274 *priv, u16 addr, u8 *val)
638 {
639 	int err;
640 
641 	err = regmap_read(priv->regmap, addr, (unsigned int *)val);
642 	if (err)
643 		dev_err(&priv->client->dev,
644 			"%s : i2c read failed, addr = %x\n", __func__, addr);
645 	else
646 		dev_dbg(&priv->client->dev,
647 			"%s : addr 0x%x, val=0x%x\n", __func__,
648 			addr, *val);
649 	return err;
650 }
651 
imx274_write_reg(struct stimx274 * priv,u16 addr,u8 val)652 static inline int imx274_write_reg(struct stimx274 *priv, u16 addr, u8 val)
653 {
654 	int err;
655 
656 	err = regmap_write(priv->regmap, addr, val);
657 	if (err)
658 		dev_err(&priv->client->dev,
659 			"%s : i2c write failed, %x = %x\n", __func__,
660 			addr, val);
661 	else
662 		dev_dbg(&priv->client->dev,
663 			"%s : addr 0x%x, val=0x%x\n", __func__,
664 			addr, val);
665 	return err;
666 }
667 
668 /**
669  * Write a multibyte register.
670  *
671  * Uses a bulk write where possible.
672  *
673  * @priv: Pointer to device structure
674  * @addr: Address of the LSB register.  Other registers must be
675  *        consecutive, least-to-most significant.
676  * @val: Value to be written to the register (cpu endianness)
677  * @nbytes: Number of bits to write (range: [1..3])
678  */
imx274_write_mbreg(struct stimx274 * priv,u16 addr,u32 val,size_t nbytes)679 static int imx274_write_mbreg(struct stimx274 *priv, u16 addr, u32 val,
680 			      size_t nbytes)
681 {
682 	__le32 val_le = cpu_to_le32(val);
683 	int err;
684 
685 	err = regmap_bulk_write(priv->regmap, addr, &val_le, nbytes);
686 	if (err)
687 		dev_err(&priv->client->dev,
688 			"%s : i2c bulk write failed, %x = %x (%zu bytes)\n",
689 			__func__, addr, val, nbytes);
690 	else
691 		dev_dbg(&priv->client->dev,
692 			"%s : addr 0x%x, val=0x%x (%zu bytes)\n",
693 			__func__, addr, val, nbytes);
694 	return err;
695 }
696 
697 /*
698  * Set mode registers to start stream.
699  * @priv: Pointer to device structure
700  *
701  * Return: 0 on success, errors otherwise
702  */
imx274_mode_regs(struct stimx274 * priv)703 static int imx274_mode_regs(struct stimx274 *priv)
704 {
705 	int err = 0;
706 
707 	err = imx274_write_table(priv, imx274_start_1);
708 	if (err)
709 		return err;
710 
711 	err = imx274_write_table(priv, imx274_start_2);
712 	if (err)
713 		return err;
714 
715 	err = imx274_write_table(priv, priv->mode->init_regs);
716 
717 	return err;
718 }
719 
720 /*
721  * imx274_start_stream - Function for starting stream per mode index
722  * @priv: Pointer to device structure
723  *
724  * Return: 0 on success, errors otherwise
725  */
imx274_start_stream(struct stimx274 * priv)726 static int imx274_start_stream(struct stimx274 *priv)
727 {
728 	int err = 0;
729 
730 	/*
731 	 * Refer to "Standby Cancel Sequence when using CSI-2" in
732 	 * imx274 datasheet, it should wait 10ms or more here.
733 	 * give it 1 extra ms for margin
734 	 */
735 	msleep_range(11);
736 	err = imx274_write_table(priv, imx274_start_3);
737 	if (err)
738 		return err;
739 
740 	/*
741 	 * Refer to "Standby Cancel Sequence when using CSI-2" in
742 	 * imx274 datasheet, it should wait 7ms or more here.
743 	 * give it 1 extra ms for margin
744 	 */
745 	msleep_range(8);
746 	err = imx274_write_table(priv, imx274_start_4);
747 	if (err)
748 		return err;
749 
750 	return 0;
751 }
752 
753 /*
754  * imx274_reset - Function called to reset the sensor
755  * @priv: Pointer to device structure
756  * @rst: Input value for determining the sensor's end state after reset
757  *
758  * Set the senor in reset and then
759  * if rst = 0, keep it in reset;
760  * if rst = 1, bring it out of reset.
761  *
762  */
imx274_reset(struct stimx274 * priv,int rst)763 static void imx274_reset(struct stimx274 *priv, int rst)
764 {
765 	gpiod_set_value_cansleep(priv->reset_gpio, 0);
766 	usleep_range(IMX274_RESET_DELAY1, IMX274_RESET_DELAY2);
767 	gpiod_set_value_cansleep(priv->reset_gpio, !!rst);
768 	usleep_range(IMX274_RESET_DELAY1, IMX274_RESET_DELAY2);
769 }
770 
771 /**
772  * imx274_s_ctrl - This is used to set the imx274 V4L2 controls
773  * @ctrl: V4L2 control to be set
774  *
775  * This function is used to set the V4L2 controls for the imx274 sensor.
776  *
777  * Return: 0 on success, errors otherwise
778  */
imx274_s_ctrl(struct v4l2_ctrl * ctrl)779 static int imx274_s_ctrl(struct v4l2_ctrl *ctrl)
780 {
781 	struct v4l2_subdev *sd = ctrl_to_sd(ctrl);
782 	struct stimx274 *imx274 = to_imx274(sd);
783 	int ret = -EINVAL;
784 
785 	dev_dbg(&imx274->client->dev,
786 		"%s : s_ctrl: %s, value: %d\n", __func__,
787 		ctrl->name, ctrl->val);
788 
789 	switch (ctrl->id) {
790 	case V4L2_CID_EXPOSURE:
791 		dev_dbg(&imx274->client->dev,
792 			"%s : set V4L2_CID_EXPOSURE\n", __func__);
793 		ret = imx274_set_exposure(imx274, ctrl->val);
794 		break;
795 
796 	case V4L2_CID_GAIN:
797 		dev_dbg(&imx274->client->dev,
798 			"%s : set V4L2_CID_GAIN\n", __func__);
799 		ret = imx274_set_gain(imx274, ctrl);
800 		break;
801 
802 	case V4L2_CID_VFLIP:
803 		dev_dbg(&imx274->client->dev,
804 			"%s : set V4L2_CID_VFLIP\n", __func__);
805 		ret = imx274_set_vflip(imx274, ctrl->val);
806 		break;
807 
808 	case V4L2_CID_TEST_PATTERN:
809 		dev_dbg(&imx274->client->dev,
810 			"%s : set V4L2_CID_TEST_PATTERN\n", __func__);
811 		ret = imx274_set_test_pattern(imx274, ctrl->val);
812 		break;
813 	}
814 
815 	return ret;
816 }
817 
imx274_binning_goodness(struct stimx274 * imx274,int w,int ask_w,int h,int ask_h,u32 flags)818 static int imx274_binning_goodness(struct stimx274 *imx274,
819 				   int w, int ask_w,
820 				   int h, int ask_h, u32 flags)
821 {
822 	struct device *dev = &imx274->client->dev;
823 	const int goodness = 100000;
824 	int val = 0;
825 
826 	if (flags & V4L2_SEL_FLAG_GE) {
827 		if (w < ask_w)
828 			val -= goodness;
829 		if (h < ask_h)
830 			val -= goodness;
831 	}
832 
833 	if (flags & V4L2_SEL_FLAG_LE) {
834 		if (w > ask_w)
835 			val -= goodness;
836 		if (h > ask_h)
837 			val -= goodness;
838 	}
839 
840 	val -= abs(w - ask_w);
841 	val -= abs(h - ask_h);
842 
843 	dev_dbg(dev, "%s: ask %dx%d, size %dx%d, goodness %d\n",
844 		__func__, ask_w, ask_h, w, h, val);
845 
846 	return val;
847 }
848 
849 /**
850  * Helper function to change binning and set both compose and format.
851  *
852  * We have two entry points to change binning: set_fmt and
853  * set_selection(COMPOSE). Both have to compute the new output size
854  * and set it in both the compose rect and the frame format size. We
855  * also need to do the same things after setting cropping to restore
856  * 1:1 binning.
857  *
858  * This function contains the common code for these three cases, it
859  * has many arguments in order to accommodate the needs of all of
860  * them.
861  *
862  * Must be called with imx274->lock locked.
863  *
864  * @imx274: The device object
865  * @cfg:    The pad config we are editing for TRY requests
866  * @which:  V4L2_SUBDEV_FORMAT_ACTIVE or V4L2_SUBDEV_FORMAT_TRY from the caller
867  * @width:  Input-output parameter: set to the desired width before
868  *          the call, contains the chosen value after returning successfully
869  * @height: Input-output parameter for height (see @width)
870  * @flags:  Selection flags from struct v4l2_subdev_selection, or 0 if not
871  *          available (when called from set_fmt)
872  */
__imx274_change_compose(struct stimx274 * imx274,struct v4l2_subdev_pad_config * cfg,u32 which,u32 * width,u32 * height,u32 flags)873 static int __imx274_change_compose(struct stimx274 *imx274,
874 				   struct v4l2_subdev_pad_config *cfg,
875 				   u32 which,
876 				   u32 *width,
877 				   u32 *height,
878 				   u32 flags)
879 {
880 	struct device *dev = &imx274->client->dev;
881 	const struct v4l2_rect *cur_crop;
882 	struct v4l2_mbus_framefmt *tgt_fmt;
883 	unsigned int i;
884 	const struct imx274_frmfmt *best_mode = &imx274_formats[0];
885 	int best_goodness = INT_MIN;
886 
887 	if (which == V4L2_SUBDEV_FORMAT_TRY) {
888 		cur_crop = &cfg->try_crop;
889 		tgt_fmt = &cfg->try_fmt;
890 	} else {
891 		cur_crop = &imx274->crop;
892 		tgt_fmt = &imx274->format;
893 	}
894 
895 	for (i = 0; i < ARRAY_SIZE(imx274_formats); i++) {
896 		unsigned int ratio = imx274_formats[i].bin_ratio;
897 
898 		int goodness = imx274_binning_goodness(
899 			imx274,
900 			cur_crop->width / ratio, *width,
901 			cur_crop->height / ratio, *height,
902 			flags);
903 
904 		if (goodness >= best_goodness) {
905 			best_goodness = goodness;
906 			best_mode = &imx274_formats[i];
907 		}
908 	}
909 
910 	*width = cur_crop->width / best_mode->bin_ratio;
911 	*height = cur_crop->height / best_mode->bin_ratio;
912 
913 	if (which == V4L2_SUBDEV_FORMAT_ACTIVE)
914 		imx274->mode = best_mode;
915 
916 	dev_dbg(dev, "%s: selected %u:1 binning\n",
917 		__func__, best_mode->bin_ratio);
918 
919 	tgt_fmt->width = *width;
920 	tgt_fmt->height = *height;
921 	tgt_fmt->field = V4L2_FIELD_NONE;
922 
923 	return 0;
924 }
925 
926 /**
927  * imx274_get_fmt - Get the pad format
928  * @sd: Pointer to V4L2 Sub device structure
929  * @cfg: Pointer to sub device pad information structure
930  * @fmt: Pointer to pad level media bus format
931  *
932  * This function is used to get the pad format information.
933  *
934  * Return: 0 on success
935  */
imx274_get_fmt(struct v4l2_subdev * sd,struct v4l2_subdev_pad_config * cfg,struct v4l2_subdev_format * fmt)936 static int imx274_get_fmt(struct v4l2_subdev *sd,
937 			  struct v4l2_subdev_pad_config *cfg,
938 			  struct v4l2_subdev_format *fmt)
939 {
940 	struct stimx274 *imx274 = to_imx274(sd);
941 
942 	mutex_lock(&imx274->lock);
943 	fmt->format = imx274->format;
944 	mutex_unlock(&imx274->lock);
945 	return 0;
946 }
947 
948 /**
949  * imx274_set_fmt - This is used to set the pad format
950  * @sd: Pointer to V4L2 Sub device structure
951  * @cfg: Pointer to sub device pad information structure
952  * @format: Pointer to pad level media bus format
953  *
954  * This function is used to set the pad format.
955  *
956  * Return: 0 on success
957  */
imx274_set_fmt(struct v4l2_subdev * sd,struct v4l2_subdev_pad_config * cfg,struct v4l2_subdev_format * format)958 static int imx274_set_fmt(struct v4l2_subdev *sd,
959 			  struct v4l2_subdev_pad_config *cfg,
960 			  struct v4l2_subdev_format *format)
961 {
962 	struct v4l2_mbus_framefmt *fmt = &format->format;
963 	struct stimx274 *imx274 = to_imx274(sd);
964 	int err = 0;
965 
966 	mutex_lock(&imx274->lock);
967 
968 	err = __imx274_change_compose(imx274, cfg, format->which,
969 				      &fmt->width, &fmt->height, 0);
970 
971 	if (err)
972 		goto out;
973 
974 	/*
975 	 * __imx274_change_compose already set width and height in the
976 	 * applicable format, but we need to keep all other format
977 	 * values, so do a full copy here
978 	 */
979 	fmt->field = V4L2_FIELD_NONE;
980 	if (format->which == V4L2_SUBDEV_FORMAT_TRY)
981 		cfg->try_fmt = *fmt;
982 	else
983 		imx274->format = *fmt;
984 
985 out:
986 	mutex_unlock(&imx274->lock);
987 
988 	return err;
989 }
990 
imx274_get_selection(struct v4l2_subdev * sd,struct v4l2_subdev_pad_config * cfg,struct v4l2_subdev_selection * sel)991 static int imx274_get_selection(struct v4l2_subdev *sd,
992 				struct v4l2_subdev_pad_config *cfg,
993 				struct v4l2_subdev_selection *sel)
994 {
995 	struct stimx274 *imx274 = to_imx274(sd);
996 	const struct v4l2_rect *src_crop;
997 	const struct v4l2_mbus_framefmt *src_fmt;
998 	int ret = 0;
999 
1000 	if (sel->pad != 0)
1001 		return -EINVAL;
1002 
1003 	if (sel->target == V4L2_SEL_TGT_CROP_BOUNDS) {
1004 		sel->r.left = 0;
1005 		sel->r.top = 0;
1006 		sel->r.width = IMX274_MAX_WIDTH;
1007 		sel->r.height = IMX274_MAX_HEIGHT;
1008 		return 0;
1009 	}
1010 
1011 	if (sel->which == V4L2_SUBDEV_FORMAT_TRY) {
1012 		src_crop = &cfg->try_crop;
1013 		src_fmt = &cfg->try_fmt;
1014 	} else {
1015 		src_crop = &imx274->crop;
1016 		src_fmt = &imx274->format;
1017 	}
1018 
1019 	mutex_lock(&imx274->lock);
1020 
1021 	switch (sel->target) {
1022 	case V4L2_SEL_TGT_CROP:
1023 		sel->r = *src_crop;
1024 		break;
1025 	case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1026 		sel->r.top = 0;
1027 		sel->r.left = 0;
1028 		sel->r.width = src_crop->width;
1029 		sel->r.height = src_crop->height;
1030 		break;
1031 	case V4L2_SEL_TGT_COMPOSE:
1032 		sel->r.top = 0;
1033 		sel->r.left = 0;
1034 		sel->r.width = src_fmt->width;
1035 		sel->r.height = src_fmt->height;
1036 		break;
1037 	default:
1038 		ret = -EINVAL;
1039 	}
1040 
1041 	mutex_unlock(&imx274->lock);
1042 
1043 	return ret;
1044 }
1045 
imx274_set_selection_crop(struct stimx274 * imx274,struct v4l2_subdev_pad_config * cfg,struct v4l2_subdev_selection * sel)1046 static int imx274_set_selection_crop(struct stimx274 *imx274,
1047 				     struct v4l2_subdev_pad_config *cfg,
1048 				     struct v4l2_subdev_selection *sel)
1049 {
1050 	struct v4l2_rect *tgt_crop;
1051 	struct v4l2_rect new_crop;
1052 	bool size_changed;
1053 
1054 	/*
1055 	 * h_step could be 12 or 24 depending on the binning. But we
1056 	 * won't know the binning until we choose the mode later in
1057 	 * __imx274_change_compose(). Thus let's be safe and use the
1058 	 * most conservative value in all cases.
1059 	 */
1060 	const u32 h_step = 24;
1061 
1062 	new_crop.width = min_t(u32,
1063 			       IMX274_ROUND(sel->r.width, h_step, sel->flags),
1064 			       IMX274_MAX_WIDTH);
1065 
1066 	/* Constraint: HTRIMMING_END - HTRIMMING_START >= 144 */
1067 	if (new_crop.width < 144)
1068 		new_crop.width = 144;
1069 
1070 	new_crop.left = min_t(u32,
1071 			      IMX274_ROUND(sel->r.left, h_step, 0),
1072 			      IMX274_MAX_WIDTH - new_crop.width);
1073 
1074 	new_crop.height = min_t(u32,
1075 				IMX274_ROUND(sel->r.height, 2, sel->flags),
1076 				IMX274_MAX_HEIGHT);
1077 
1078 	new_crop.top = min_t(u32, IMX274_ROUND(sel->r.top, 2, 0),
1079 			     IMX274_MAX_HEIGHT - new_crop.height);
1080 
1081 	sel->r = new_crop;
1082 
1083 	if (sel->which == V4L2_SUBDEV_FORMAT_TRY)
1084 		tgt_crop = &cfg->try_crop;
1085 	else
1086 		tgt_crop = &imx274->crop;
1087 
1088 	mutex_lock(&imx274->lock);
1089 
1090 	size_changed = (new_crop.width != tgt_crop->width ||
1091 			new_crop.height != tgt_crop->height);
1092 
1093 	/* __imx274_change_compose needs the new size in *tgt_crop */
1094 	*tgt_crop = new_crop;
1095 
1096 	/* if crop size changed then reset the output image size */
1097 	if (size_changed)
1098 		__imx274_change_compose(imx274, cfg, sel->which,
1099 					&new_crop.width, &new_crop.height,
1100 					sel->flags);
1101 
1102 	mutex_unlock(&imx274->lock);
1103 
1104 	return 0;
1105 }
1106 
imx274_set_selection(struct v4l2_subdev * sd,struct v4l2_subdev_pad_config * cfg,struct v4l2_subdev_selection * sel)1107 static int imx274_set_selection(struct v4l2_subdev *sd,
1108 				struct v4l2_subdev_pad_config *cfg,
1109 				struct v4l2_subdev_selection *sel)
1110 {
1111 	struct stimx274 *imx274 = to_imx274(sd);
1112 
1113 	if (sel->pad != 0)
1114 		return -EINVAL;
1115 
1116 	if (sel->target == V4L2_SEL_TGT_CROP)
1117 		return imx274_set_selection_crop(imx274, cfg, sel);
1118 
1119 	if (sel->target == V4L2_SEL_TGT_COMPOSE) {
1120 		int err;
1121 
1122 		mutex_lock(&imx274->lock);
1123 		err =  __imx274_change_compose(imx274, cfg, sel->which,
1124 					       &sel->r.width, &sel->r.height,
1125 					       sel->flags);
1126 		mutex_unlock(&imx274->lock);
1127 
1128 		/*
1129 		 * __imx274_change_compose already set width and
1130 		 * height in set->r, we still need to set top-left
1131 		 */
1132 		if (!err) {
1133 			sel->r.top = 0;
1134 			sel->r.left = 0;
1135 		}
1136 
1137 		return err;
1138 	}
1139 
1140 	return -EINVAL;
1141 }
1142 
imx274_apply_trimming(struct stimx274 * imx274)1143 static int imx274_apply_trimming(struct stimx274 *imx274)
1144 {
1145 	u32 h_start;
1146 	u32 h_end;
1147 	u32 hmax;
1148 	u32 v_cut;
1149 	s32 v_pos;
1150 	u32 write_v_size;
1151 	u32 y_out_size;
1152 	int err;
1153 
1154 	h_start = imx274->crop.left + 12;
1155 	h_end = h_start + imx274->crop.width;
1156 
1157 	/* Use the minimum allowed value of HMAX */
1158 	/* Note: except in mode 1, (width / 16 + 23) is always < hmax_min */
1159 	/* Note: 260 is the minimum HMAX in all implemented modes */
1160 	hmax = max_t(u32, 260, (imx274->crop.width) / 16 + 23);
1161 
1162 	/* invert v_pos if VFLIP */
1163 	v_pos = imx274->ctrls.vflip->cur.val ?
1164 		(-imx274->crop.top / 2) : (imx274->crop.top / 2);
1165 	v_cut = (IMX274_MAX_HEIGHT - imx274->crop.height) / 2;
1166 	write_v_size = imx274->crop.height + 22;
1167 	y_out_size   = imx274->crop.height + 14;
1168 
1169 	err = imx274_write_mbreg(imx274, IMX274_HMAX_REG_LSB, hmax, 2);
1170 	if (!err)
1171 		err = imx274_write_mbreg(imx274, IMX274_HTRIM_EN_REG, 1, 1);
1172 	if (!err)
1173 		err = imx274_write_mbreg(imx274, IMX274_HTRIM_START_REG_LSB,
1174 					 h_start, 2);
1175 	if (!err)
1176 		err = imx274_write_mbreg(imx274, IMX274_HTRIM_END_REG_LSB,
1177 					 h_end, 2);
1178 	if (!err)
1179 		err = imx274_write_mbreg(imx274, IMX274_VWIDCUTEN_REG, 1, 1);
1180 	if (!err)
1181 		err = imx274_write_mbreg(imx274, IMX274_VWIDCUT_REG_LSB,
1182 					 v_cut, 2);
1183 	if (!err)
1184 		err = imx274_write_mbreg(imx274, IMX274_VWINPOS_REG_LSB,
1185 					 v_pos, 2);
1186 	if (!err)
1187 		err = imx274_write_mbreg(imx274, IMX274_WRITE_VSIZE_REG_LSB,
1188 					 write_v_size, 2);
1189 	if (!err)
1190 		err = imx274_write_mbreg(imx274, IMX274_Y_OUT_SIZE_REG_LSB,
1191 					 y_out_size, 2);
1192 
1193 	return err;
1194 }
1195 
1196 /**
1197  * imx274_g_frame_interval - Get the frame interval
1198  * @sd: Pointer to V4L2 Sub device structure
1199  * @fi: Pointer to V4l2 Sub device frame interval structure
1200  *
1201  * This function is used to get the frame interval.
1202  *
1203  * Return: 0 on success
1204  */
imx274_g_frame_interval(struct v4l2_subdev * sd,struct v4l2_subdev_frame_interval * fi)1205 static int imx274_g_frame_interval(struct v4l2_subdev *sd,
1206 				   struct v4l2_subdev_frame_interval *fi)
1207 {
1208 	struct stimx274 *imx274 = to_imx274(sd);
1209 
1210 	fi->interval = imx274->frame_interval;
1211 	dev_dbg(&imx274->client->dev, "%s frame rate = %d / %d\n",
1212 		__func__, imx274->frame_interval.numerator,
1213 		imx274->frame_interval.denominator);
1214 
1215 	return 0;
1216 }
1217 
1218 /**
1219  * imx274_s_frame_interval - Set the frame interval
1220  * @sd: Pointer to V4L2 Sub device structure
1221  * @fi: Pointer to V4l2 Sub device frame interval structure
1222  *
1223  * This function is used to set the frame intervavl.
1224  *
1225  * Return: 0 on success
1226  */
imx274_s_frame_interval(struct v4l2_subdev * sd,struct v4l2_subdev_frame_interval * fi)1227 static int imx274_s_frame_interval(struct v4l2_subdev *sd,
1228 				   struct v4l2_subdev_frame_interval *fi)
1229 {
1230 	struct stimx274 *imx274 = to_imx274(sd);
1231 	struct v4l2_ctrl *ctrl = imx274->ctrls.exposure;
1232 	int min, max, def;
1233 	int ret;
1234 
1235 	mutex_lock(&imx274->lock);
1236 	ret = imx274_set_frame_interval(imx274, fi->interval);
1237 
1238 	if (!ret) {
1239 		/*
1240 		 * exposure time range is decided by frame interval
1241 		 * need to update it after frame interval changes
1242 		 */
1243 		min = IMX274_MIN_EXPOSURE_TIME;
1244 		max = fi->interval.numerator * 1000000
1245 			/ fi->interval.denominator;
1246 		def = max;
1247 		if (__v4l2_ctrl_modify_range(ctrl, min, max, 1, def)) {
1248 			dev_err(&imx274->client->dev,
1249 				"Exposure ctrl range update failed\n");
1250 			goto unlock;
1251 		}
1252 
1253 		/* update exposure time accordingly */
1254 		imx274_set_exposure(imx274, ctrl->val);
1255 
1256 		dev_dbg(&imx274->client->dev, "set frame interval to %uus\n",
1257 			fi->interval.numerator * 1000000
1258 			/ fi->interval.denominator);
1259 	}
1260 
1261 unlock:
1262 	mutex_unlock(&imx274->lock);
1263 
1264 	return ret;
1265 }
1266 
1267 /**
1268  * imx274_load_default - load default control values
1269  * @priv: Pointer to device structure
1270  *
1271  * Return: 0 on success, errors otherwise
1272  */
imx274_load_default(struct stimx274 * priv)1273 static int imx274_load_default(struct stimx274 *priv)
1274 {
1275 	int ret;
1276 
1277 	/* load default control values */
1278 	priv->frame_interval.numerator = 1;
1279 	priv->frame_interval.denominator = IMX274_DEF_FRAME_RATE;
1280 	priv->ctrls.exposure->val = 1000000 / IMX274_DEF_FRAME_RATE;
1281 	priv->ctrls.gain->val = IMX274_DEF_GAIN;
1282 	priv->ctrls.vflip->val = 0;
1283 	priv->ctrls.test_pattern->val = TEST_PATTERN_DISABLED;
1284 
1285 	/* update frame rate */
1286 	ret = imx274_set_frame_interval(priv,
1287 					priv->frame_interval);
1288 	if (ret)
1289 		return ret;
1290 
1291 	/* update exposure time */
1292 	ret = v4l2_ctrl_s_ctrl(priv->ctrls.exposure, priv->ctrls.exposure->val);
1293 	if (ret)
1294 		return ret;
1295 
1296 	/* update gain */
1297 	ret = v4l2_ctrl_s_ctrl(priv->ctrls.gain, priv->ctrls.gain->val);
1298 	if (ret)
1299 		return ret;
1300 
1301 	/* update vflip */
1302 	ret = v4l2_ctrl_s_ctrl(priv->ctrls.vflip, priv->ctrls.vflip->val);
1303 	if (ret)
1304 		return ret;
1305 
1306 	return 0;
1307 }
1308 
1309 /**
1310  * imx274_s_stream - It is used to start/stop the streaming.
1311  * @sd: V4L2 Sub device
1312  * @on: Flag (True / False)
1313  *
1314  * This function controls the start or stop of streaming for the
1315  * imx274 sensor.
1316  *
1317  * Return: 0 on success, errors otherwise
1318  */
imx274_s_stream(struct v4l2_subdev * sd,int on)1319 static int imx274_s_stream(struct v4l2_subdev *sd, int on)
1320 {
1321 	struct stimx274 *imx274 = to_imx274(sd);
1322 	int ret = 0;
1323 
1324 	dev_dbg(&imx274->client->dev, "%s : %s, mode index = %td\n", __func__,
1325 		on ? "Stream Start" : "Stream Stop",
1326 		imx274->mode - &imx274_formats[0]);
1327 
1328 	mutex_lock(&imx274->lock);
1329 
1330 	if (on) {
1331 		/* load mode registers */
1332 		ret = imx274_mode_regs(imx274);
1333 		if (ret)
1334 			goto fail;
1335 
1336 		ret = imx274_apply_trimming(imx274);
1337 		if (ret)
1338 			goto fail;
1339 
1340 		/*
1341 		 * update frame rate & expsoure. if the last mode is different,
1342 		 * HMAX could be changed. As the result, frame rate & exposure
1343 		 * are changed.
1344 		 * gain is not affected.
1345 		 */
1346 		ret = imx274_set_frame_interval(imx274,
1347 						imx274->frame_interval);
1348 		if (ret)
1349 			goto fail;
1350 
1351 		/* update exposure time */
1352 		ret = __v4l2_ctrl_s_ctrl(imx274->ctrls.exposure,
1353 					 imx274->ctrls.exposure->val);
1354 		if (ret)
1355 			goto fail;
1356 
1357 		/* start stream */
1358 		ret = imx274_start_stream(imx274);
1359 		if (ret)
1360 			goto fail;
1361 	} else {
1362 		/* stop stream */
1363 		ret = imx274_write_table(imx274, imx274_stop);
1364 		if (ret)
1365 			goto fail;
1366 	}
1367 
1368 	mutex_unlock(&imx274->lock);
1369 	dev_dbg(&imx274->client->dev, "%s : Done\n", __func__);
1370 	return 0;
1371 
1372 fail:
1373 	mutex_unlock(&imx274->lock);
1374 	dev_err(&imx274->client->dev, "s_stream failed\n");
1375 	return ret;
1376 }
1377 
1378 /*
1379  * imx274_get_frame_length - Function for obtaining current frame length
1380  * @priv: Pointer to device structure
1381  * @val: Pointer to obainted value
1382  *
1383  * frame_length = vmax x (svr + 1), in unit of hmax.
1384  *
1385  * Return: 0 on success
1386  */
imx274_get_frame_length(struct stimx274 * priv,u32 * val)1387 static int imx274_get_frame_length(struct stimx274 *priv, u32 *val)
1388 {
1389 	int err;
1390 	u16 svr;
1391 	u32 vmax;
1392 	u8 reg_val[3];
1393 
1394 	/* svr */
1395 	err = imx274_read_reg(priv, IMX274_SVR_REG_LSB, &reg_val[0]);
1396 	if (err)
1397 		goto fail;
1398 
1399 	err = imx274_read_reg(priv, IMX274_SVR_REG_MSB, &reg_val[1]);
1400 	if (err)
1401 		goto fail;
1402 
1403 	svr = (reg_val[1] << IMX274_SHIFT_8_BITS) + reg_val[0];
1404 
1405 	/* vmax */
1406 	err = imx274_read_reg(priv, IMX274_VMAX_REG_3, &reg_val[0]);
1407 	if (err)
1408 		goto fail;
1409 
1410 	err = imx274_read_reg(priv, IMX274_VMAX_REG_2, &reg_val[1]);
1411 	if (err)
1412 		goto fail;
1413 
1414 	err = imx274_read_reg(priv, IMX274_VMAX_REG_1, &reg_val[2]);
1415 	if (err)
1416 		goto fail;
1417 
1418 	vmax = ((reg_val[2] & IMX274_MASK_LSB_3_BITS) << IMX274_SHIFT_16_BITS)
1419 		+ (reg_val[1] << IMX274_SHIFT_8_BITS) + reg_val[0];
1420 
1421 	*val = vmax * (svr + 1);
1422 
1423 	return 0;
1424 
1425 fail:
1426 	dev_err(&priv->client->dev, "%s error = %d\n", __func__, err);
1427 	return err;
1428 }
1429 
imx274_clamp_coarse_time(struct stimx274 * priv,u32 * val,u32 * frame_length)1430 static int imx274_clamp_coarse_time(struct stimx274 *priv, u32 *val,
1431 				    u32 *frame_length)
1432 {
1433 	int err;
1434 
1435 	err = imx274_get_frame_length(priv, frame_length);
1436 	if (err)
1437 		return err;
1438 
1439 	if (*frame_length < priv->mode->min_frame_len)
1440 		*frame_length =  priv->mode->min_frame_len;
1441 
1442 	*val = *frame_length - *val; /* convert to raw shr */
1443 	if (*val > *frame_length - IMX274_SHR_LIMIT_CONST)
1444 		*val = *frame_length - IMX274_SHR_LIMIT_CONST;
1445 	else if (*val < priv->mode->min_SHR)
1446 		*val = priv->mode->min_SHR;
1447 
1448 	return 0;
1449 }
1450 
1451 /*
1452  * imx274_set_digital gain - Function called when setting digital gain
1453  * @priv: Pointer to device structure
1454  * @dgain: Value of digital gain.
1455  *
1456  * Digital gain has only 4 steps: 1x, 2x, 4x, and 8x
1457  *
1458  * Return: 0 on success
1459  */
imx274_set_digital_gain(struct stimx274 * priv,u32 dgain)1460 static int imx274_set_digital_gain(struct stimx274 *priv, u32 dgain)
1461 {
1462 	u8 reg_val;
1463 
1464 	reg_val = ffs(dgain);
1465 
1466 	if (reg_val)
1467 		reg_val--;
1468 
1469 	reg_val = clamp(reg_val, (u8)0, (u8)3);
1470 
1471 	return imx274_write_reg(priv, IMX274_DIGITAL_GAIN_REG,
1472 				reg_val & IMX274_MASK_LSB_4_BITS);
1473 }
1474 
1475 /*
1476  * imx274_set_gain - Function called when setting gain
1477  * @priv: Pointer to device structure
1478  * @val: Value of gain. the real value = val << IMX274_GAIN_SHIFT;
1479  * @ctrl: v4l2 control pointer
1480  *
1481  * Set the gain based on input value.
1482  * The caller should hold the mutex lock imx274->lock if necessary
1483  *
1484  * Return: 0 on success
1485  */
imx274_set_gain(struct stimx274 * priv,struct v4l2_ctrl * ctrl)1486 static int imx274_set_gain(struct stimx274 *priv, struct v4l2_ctrl *ctrl)
1487 {
1488 	int err;
1489 	u32 gain, analog_gain, digital_gain, gain_reg;
1490 
1491 	gain = (u32)(ctrl->val);
1492 
1493 	dev_dbg(&priv->client->dev,
1494 		"%s : input gain = %d.%d\n", __func__,
1495 		gain >> IMX274_GAIN_SHIFT,
1496 		((gain & IMX274_GAIN_SHIFT_MASK) * 100) >> IMX274_GAIN_SHIFT);
1497 
1498 	if (gain > IMX274_MAX_DIGITAL_GAIN * IMX274_MAX_ANALOG_GAIN)
1499 		gain = IMX274_MAX_DIGITAL_GAIN * IMX274_MAX_ANALOG_GAIN;
1500 	else if (gain < IMX274_MIN_GAIN)
1501 		gain = IMX274_MIN_GAIN;
1502 
1503 	if (gain <= IMX274_MAX_ANALOG_GAIN)
1504 		digital_gain = 1;
1505 	else if (gain <= IMX274_MAX_ANALOG_GAIN * 2)
1506 		digital_gain = 2;
1507 	else if (gain <= IMX274_MAX_ANALOG_GAIN * 4)
1508 		digital_gain = 4;
1509 	else
1510 		digital_gain = IMX274_MAX_DIGITAL_GAIN;
1511 
1512 	analog_gain = gain / digital_gain;
1513 
1514 	dev_dbg(&priv->client->dev,
1515 		"%s : digital gain = %d, analog gain = %d.%d\n",
1516 		__func__, digital_gain, analog_gain >> IMX274_GAIN_SHIFT,
1517 		((analog_gain & IMX274_GAIN_SHIFT_MASK) * 100)
1518 		>> IMX274_GAIN_SHIFT);
1519 
1520 	err = imx274_set_digital_gain(priv, digital_gain);
1521 	if (err)
1522 		goto fail;
1523 
1524 	/* convert to register value, refer to imx274 datasheet */
1525 	gain_reg = (u32)IMX274_GAIN_CONST -
1526 		(IMX274_GAIN_CONST << IMX274_GAIN_SHIFT) / analog_gain;
1527 	if (gain_reg > IMX274_GAIN_REG_MAX)
1528 		gain_reg = IMX274_GAIN_REG_MAX;
1529 
1530 	err = imx274_write_mbreg(priv, IMX274_ANALOG_GAIN_ADDR_LSB, gain_reg,
1531 				 2);
1532 	if (err)
1533 		goto fail;
1534 
1535 	if (IMX274_GAIN_CONST - gain_reg == 0) {
1536 		err = -EINVAL;
1537 		goto fail;
1538 	}
1539 
1540 	/* convert register value back to gain value */
1541 	ctrl->val = (IMX274_GAIN_CONST << IMX274_GAIN_SHIFT)
1542 			/ (IMX274_GAIN_CONST - gain_reg) * digital_gain;
1543 
1544 	dev_dbg(&priv->client->dev,
1545 		"%s : GAIN control success, gain_reg = %d, new gain = %d\n",
1546 		__func__, gain_reg, ctrl->val);
1547 
1548 	return 0;
1549 
1550 fail:
1551 	dev_err(&priv->client->dev, "%s error = %d\n", __func__, err);
1552 	return err;
1553 }
1554 
1555 /*
1556  * imx274_set_coarse_time - Function called when setting SHR value
1557  * @priv: Pointer to device structure
1558  * @val: Value for exposure time in number of line_length, or [HMAX]
1559  *
1560  * Set SHR value based on input value.
1561  *
1562  * Return: 0 on success
1563  */
imx274_set_coarse_time(struct stimx274 * priv,u32 * val)1564 static int imx274_set_coarse_time(struct stimx274 *priv, u32 *val)
1565 {
1566 	int err;
1567 	u32 coarse_time, frame_length;
1568 
1569 	coarse_time = *val;
1570 
1571 	/* convert exposure_time to appropriate SHR value */
1572 	err = imx274_clamp_coarse_time(priv, &coarse_time, &frame_length);
1573 	if (err)
1574 		goto fail;
1575 
1576 	err = imx274_write_mbreg(priv, IMX274_SHR_REG_LSB, coarse_time, 2);
1577 	if (err)
1578 		goto fail;
1579 
1580 	*val = frame_length - coarse_time;
1581 	return 0;
1582 
1583 fail:
1584 	dev_err(&priv->client->dev, "%s error = %d\n", __func__, err);
1585 	return err;
1586 }
1587 
1588 /*
1589  * imx274_set_exposure - Function called when setting exposure time
1590  * @priv: Pointer to device structure
1591  * @val: Variable for exposure time, in the unit of micro-second
1592  *
1593  * Set exposure time based on input value.
1594  * The caller should hold the mutex lock imx274->lock if necessary
1595  *
1596  * Return: 0 on success
1597  */
imx274_set_exposure(struct stimx274 * priv,int val)1598 static int imx274_set_exposure(struct stimx274 *priv, int val)
1599 {
1600 	int err;
1601 	u16 hmax;
1602 	u8 reg_val[2];
1603 	u32 coarse_time; /* exposure time in unit of line (HMAX)*/
1604 
1605 	dev_dbg(&priv->client->dev,
1606 		"%s : EXPOSURE control input = %d\n", __func__, val);
1607 
1608 	/* step 1: convert input exposure_time (val) into number of 1[HMAX] */
1609 
1610 	/* obtain HMAX value */
1611 	err = imx274_read_reg(priv, IMX274_HMAX_REG_LSB, &reg_val[0]);
1612 	if (err)
1613 		goto fail;
1614 	err = imx274_read_reg(priv, IMX274_HMAX_REG_MSB, &reg_val[1]);
1615 	if (err)
1616 		goto fail;
1617 	hmax = (reg_val[1] << IMX274_SHIFT_8_BITS) + reg_val[0];
1618 	if (hmax == 0) {
1619 		err = -EINVAL;
1620 		goto fail;
1621 	}
1622 
1623 	coarse_time = (IMX274_PIXCLK_CONST1 / IMX274_PIXCLK_CONST2 * val
1624 			- priv->mode->nocpiop) / hmax;
1625 
1626 	/* step 2: convert exposure_time into SHR value */
1627 
1628 	/* set SHR */
1629 	err = imx274_set_coarse_time(priv, &coarse_time);
1630 	if (err)
1631 		goto fail;
1632 
1633 	priv->ctrls.exposure->val =
1634 			(coarse_time * hmax + priv->mode->nocpiop)
1635 			/ (IMX274_PIXCLK_CONST1 / IMX274_PIXCLK_CONST2);
1636 
1637 	dev_dbg(&priv->client->dev,
1638 		"%s : EXPOSURE control success\n", __func__);
1639 	return 0;
1640 
1641 fail:
1642 	dev_err(&priv->client->dev, "%s error = %d\n", __func__, err);
1643 
1644 	return err;
1645 }
1646 
1647 /*
1648  * imx274_set_vflip - Function called when setting vertical flip
1649  * @priv: Pointer to device structure
1650  * @val: Value for vflip setting
1651  *
1652  * Set vertical flip based on input value.
1653  * val = 0: normal, no vertical flip
1654  * val = 1: vertical flip enabled
1655  * The caller should hold the mutex lock imx274->lock if necessary
1656  *
1657  * Return: 0 on success
1658  */
imx274_set_vflip(struct stimx274 * priv,int val)1659 static int imx274_set_vflip(struct stimx274 *priv, int val)
1660 {
1661 	int err;
1662 
1663 	err = imx274_write_reg(priv, IMX274_VFLIP_REG, val);
1664 	if (err) {
1665 		dev_err(&priv->client->dev, "VFLIP control error\n");
1666 		return err;
1667 	}
1668 
1669 	dev_dbg(&priv->client->dev,
1670 		"%s : VFLIP control success\n", __func__);
1671 
1672 	return 0;
1673 }
1674 
1675 /*
1676  * imx274_set_test_pattern - Function called when setting test pattern
1677  * @priv: Pointer to device structure
1678  * @val: Variable for test pattern
1679  *
1680  * Set to different test patterns based on input value.
1681  *
1682  * Return: 0 on success
1683  */
imx274_set_test_pattern(struct stimx274 * priv,int val)1684 static int imx274_set_test_pattern(struct stimx274 *priv, int val)
1685 {
1686 	int err = 0;
1687 
1688 	if (val == TEST_PATTERN_DISABLED) {
1689 		err = imx274_write_table(priv, imx274_tp_disabled);
1690 	} else if (val <= TEST_PATTERN_V_COLOR_BARS) {
1691 		err = imx274_write_reg(priv, IMX274_TEST_PATTERN_REG, val - 1);
1692 		if (!err)
1693 			err = imx274_write_table(priv, imx274_tp_regs);
1694 	} else {
1695 		err = -EINVAL;
1696 	}
1697 
1698 	if (!err)
1699 		dev_dbg(&priv->client->dev,
1700 			"%s : TEST PATTERN control success\n", __func__);
1701 	else
1702 		dev_err(&priv->client->dev, "%s error = %d\n", __func__, err);
1703 
1704 	return err;
1705 }
1706 
1707 /*
1708  * imx274_set_frame_length - Function called when setting frame length
1709  * @priv: Pointer to device structure
1710  * @val: Variable for frame length (= VMAX, i.e. vertical drive period length)
1711  *
1712  * Set frame length based on input value.
1713  *
1714  * Return: 0 on success
1715  */
imx274_set_frame_length(struct stimx274 * priv,u32 val)1716 static int imx274_set_frame_length(struct stimx274 *priv, u32 val)
1717 {
1718 	int err;
1719 	u32 frame_length;
1720 
1721 	dev_dbg(&priv->client->dev, "%s : input length = %d\n",
1722 		__func__, val);
1723 
1724 	frame_length = (u32)val;
1725 
1726 	err = imx274_write_mbreg(priv, IMX274_VMAX_REG_3, frame_length, 3);
1727 	if (err)
1728 		goto fail;
1729 
1730 	return 0;
1731 
1732 fail:
1733 	dev_err(&priv->client->dev, "%s error = %d\n", __func__, err);
1734 	return err;
1735 }
1736 
1737 /*
1738  * imx274_set_frame_interval - Function called when setting frame interval
1739  * @priv: Pointer to device structure
1740  * @frame_interval: Variable for frame interval
1741  *
1742  * Change frame interval by updating VMAX value
1743  * The caller should hold the mutex lock imx274->lock if necessary
1744  *
1745  * Return: 0 on success
1746  */
imx274_set_frame_interval(struct stimx274 * priv,struct v4l2_fract frame_interval)1747 static int imx274_set_frame_interval(struct stimx274 *priv,
1748 				     struct v4l2_fract frame_interval)
1749 {
1750 	int err;
1751 	u32 frame_length, req_frame_rate;
1752 	u16 svr;
1753 	u16 hmax;
1754 	u8 reg_val[2];
1755 
1756 	dev_dbg(&priv->client->dev, "%s: input frame interval = %d / %d",
1757 		__func__, frame_interval.numerator,
1758 		frame_interval.denominator);
1759 
1760 	if (frame_interval.numerator == 0) {
1761 		err = -EINVAL;
1762 		goto fail;
1763 	}
1764 
1765 	req_frame_rate = (u32)(frame_interval.denominator
1766 				/ frame_interval.numerator);
1767 
1768 	/* boundary check */
1769 	if (req_frame_rate > priv->mode->max_fps) {
1770 		frame_interval.numerator = 1;
1771 		frame_interval.denominator = priv->mode->max_fps;
1772 	} else if (req_frame_rate < IMX274_MIN_FRAME_RATE) {
1773 		frame_interval.numerator = 1;
1774 		frame_interval.denominator = IMX274_MIN_FRAME_RATE;
1775 	}
1776 
1777 	/*
1778 	 * VMAX = 1/frame_rate x 72M / (SVR+1) / HMAX
1779 	 * frame_length (i.e. VMAX) = (frame_interval) x 72M /(SVR+1) / HMAX
1780 	 */
1781 
1782 	/* SVR */
1783 	err = imx274_read_reg(priv, IMX274_SVR_REG_LSB, &reg_val[0]);
1784 	if (err)
1785 		goto fail;
1786 	err = imx274_read_reg(priv, IMX274_SVR_REG_MSB, &reg_val[1]);
1787 	if (err)
1788 		goto fail;
1789 	svr = (reg_val[1] << IMX274_SHIFT_8_BITS) + reg_val[0];
1790 	dev_dbg(&priv->client->dev,
1791 		"%s : register SVR = %d\n", __func__, svr);
1792 
1793 	/* HMAX */
1794 	err = imx274_read_reg(priv, IMX274_HMAX_REG_LSB, &reg_val[0]);
1795 	if (err)
1796 		goto fail;
1797 	err = imx274_read_reg(priv, IMX274_HMAX_REG_MSB, &reg_val[1]);
1798 	if (err)
1799 		goto fail;
1800 	hmax = (reg_val[1] << IMX274_SHIFT_8_BITS) + reg_val[0];
1801 	dev_dbg(&priv->client->dev,
1802 		"%s : register HMAX = %d\n", __func__, hmax);
1803 
1804 	if (hmax == 0 || frame_interval.denominator == 0) {
1805 		err = -EINVAL;
1806 		goto fail;
1807 	}
1808 
1809 	frame_length = IMX274_PIXCLK_CONST1 / (svr + 1) / hmax
1810 					* frame_interval.numerator
1811 					/ frame_interval.denominator;
1812 
1813 	err = imx274_set_frame_length(priv, frame_length);
1814 	if (err)
1815 		goto fail;
1816 
1817 	priv->frame_interval = frame_interval;
1818 	return 0;
1819 
1820 fail:
1821 	dev_err(&priv->client->dev, "%s error = %d\n", __func__, err);
1822 	return err;
1823 }
1824 
1825 static const struct v4l2_subdev_pad_ops imx274_pad_ops = {
1826 	.get_fmt = imx274_get_fmt,
1827 	.set_fmt = imx274_set_fmt,
1828 	.get_selection = imx274_get_selection,
1829 	.set_selection = imx274_set_selection,
1830 };
1831 
1832 static const struct v4l2_subdev_video_ops imx274_video_ops = {
1833 	.g_frame_interval = imx274_g_frame_interval,
1834 	.s_frame_interval = imx274_s_frame_interval,
1835 	.s_stream = imx274_s_stream,
1836 };
1837 
1838 static const struct v4l2_subdev_ops imx274_subdev_ops = {
1839 	.pad = &imx274_pad_ops,
1840 	.video = &imx274_video_ops,
1841 };
1842 
1843 static const struct v4l2_ctrl_ops imx274_ctrl_ops = {
1844 	.s_ctrl	= imx274_s_ctrl,
1845 };
1846 
1847 static const struct of_device_id imx274_of_id_table[] = {
1848 	{ .compatible = "sony,imx274" },
1849 	{ }
1850 };
1851 MODULE_DEVICE_TABLE(of, imx274_of_id_table);
1852 
1853 static const struct i2c_device_id imx274_id[] = {
1854 	{ "IMX274", 0 },
1855 	{ }
1856 };
1857 MODULE_DEVICE_TABLE(i2c, imx274_id);
1858 
imx274_probe(struct i2c_client * client,const struct i2c_device_id * id)1859 static int imx274_probe(struct i2c_client *client,
1860 			const struct i2c_device_id *id)
1861 {
1862 	struct v4l2_subdev *sd;
1863 	struct stimx274 *imx274;
1864 	int ret;
1865 
1866 	/* initialize imx274 */
1867 	imx274 = devm_kzalloc(&client->dev, sizeof(*imx274), GFP_KERNEL);
1868 	if (!imx274)
1869 		return -ENOMEM;
1870 
1871 	mutex_init(&imx274->lock);
1872 
1873 	/* initialize format */
1874 	imx274->mode = &imx274_formats[IMX274_DEFAULT_MODE];
1875 	imx274->crop.width = IMX274_MAX_WIDTH;
1876 	imx274->crop.height = IMX274_MAX_HEIGHT;
1877 	imx274->format.width = imx274->crop.width / imx274->mode->bin_ratio;
1878 	imx274->format.height = imx274->crop.height / imx274->mode->bin_ratio;
1879 	imx274->format.field = V4L2_FIELD_NONE;
1880 	imx274->format.code = MEDIA_BUS_FMT_SRGGB10_1X10;
1881 	imx274->format.colorspace = V4L2_COLORSPACE_SRGB;
1882 	imx274->frame_interval.numerator = 1;
1883 	imx274->frame_interval.denominator = IMX274_DEF_FRAME_RATE;
1884 
1885 	/* initialize regmap */
1886 	imx274->regmap = devm_regmap_init_i2c(client, &imx274_regmap_config);
1887 	if (IS_ERR(imx274->regmap)) {
1888 		dev_err(&client->dev,
1889 			"regmap init failed: %ld\n", PTR_ERR(imx274->regmap));
1890 		ret = -ENODEV;
1891 		goto err_regmap;
1892 	}
1893 
1894 	/* initialize subdevice */
1895 	imx274->client = client;
1896 	sd = &imx274->sd;
1897 	v4l2_i2c_subdev_init(sd, client, &imx274_subdev_ops);
1898 	strlcpy(sd->name, DRIVER_NAME, sizeof(sd->name));
1899 	sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS;
1900 
1901 	/* initialize subdev media pad */
1902 	imx274->pad.flags = MEDIA_PAD_FL_SOURCE;
1903 	sd->entity.function = MEDIA_ENT_F_CAM_SENSOR;
1904 	ret = media_entity_pads_init(&sd->entity, 1, &imx274->pad);
1905 	if (ret < 0) {
1906 		dev_err(&client->dev,
1907 			"%s : media entity init Failed %d\n", __func__, ret);
1908 		goto err_regmap;
1909 	}
1910 
1911 	/* initialize sensor reset gpio */
1912 	imx274->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset",
1913 						     GPIOD_OUT_HIGH);
1914 	if (IS_ERR(imx274->reset_gpio)) {
1915 		if (PTR_ERR(imx274->reset_gpio) != -EPROBE_DEFER)
1916 			dev_err(&client->dev, "Reset GPIO not setup in DT");
1917 		ret = PTR_ERR(imx274->reset_gpio);
1918 		goto err_me;
1919 	}
1920 
1921 	/* pull sensor out of reset */
1922 	imx274_reset(imx274, 1);
1923 
1924 	/* initialize controls */
1925 	ret = v4l2_ctrl_handler_init(&imx274->ctrls.handler, 2);
1926 	if (ret < 0) {
1927 		dev_err(&client->dev,
1928 			"%s : ctrl handler init Failed\n", __func__);
1929 		goto err_me;
1930 	}
1931 
1932 	imx274->ctrls.handler.lock = &imx274->lock;
1933 
1934 	/* add new controls */
1935 	imx274->ctrls.test_pattern = v4l2_ctrl_new_std_menu_items(
1936 		&imx274->ctrls.handler, &imx274_ctrl_ops,
1937 		V4L2_CID_TEST_PATTERN,
1938 		ARRAY_SIZE(tp_qmenu) - 1, 0, 0, tp_qmenu);
1939 
1940 	imx274->ctrls.gain = v4l2_ctrl_new_std(
1941 		&imx274->ctrls.handler,
1942 		&imx274_ctrl_ops,
1943 		V4L2_CID_GAIN, IMX274_MIN_GAIN,
1944 		IMX274_MAX_DIGITAL_GAIN * IMX274_MAX_ANALOG_GAIN, 1,
1945 		IMX274_DEF_GAIN);
1946 
1947 	imx274->ctrls.exposure = v4l2_ctrl_new_std(
1948 		&imx274->ctrls.handler,
1949 		&imx274_ctrl_ops,
1950 		V4L2_CID_EXPOSURE, IMX274_MIN_EXPOSURE_TIME,
1951 		1000000 / IMX274_DEF_FRAME_RATE, 1,
1952 		IMX274_MIN_EXPOSURE_TIME);
1953 
1954 	imx274->ctrls.vflip = v4l2_ctrl_new_std(
1955 		&imx274->ctrls.handler,
1956 		&imx274_ctrl_ops,
1957 		V4L2_CID_VFLIP, 0, 1, 1, 0);
1958 
1959 	imx274->sd.ctrl_handler = &imx274->ctrls.handler;
1960 	if (imx274->ctrls.handler.error) {
1961 		ret = imx274->ctrls.handler.error;
1962 		goto err_ctrls;
1963 	}
1964 
1965 	/* setup default controls */
1966 	ret = v4l2_ctrl_handler_setup(&imx274->ctrls.handler);
1967 	if (ret) {
1968 		dev_err(&client->dev,
1969 			"Error %d setup default controls\n", ret);
1970 		goto err_ctrls;
1971 	}
1972 
1973 	/* load default control values */
1974 	ret = imx274_load_default(imx274);
1975 	if (ret) {
1976 		dev_err(&client->dev,
1977 			"%s : imx274_load_default failed %d\n",
1978 			__func__, ret);
1979 		goto err_ctrls;
1980 	}
1981 
1982 	/* register subdevice */
1983 	ret = v4l2_async_register_subdev(sd);
1984 	if (ret < 0) {
1985 		dev_err(&client->dev,
1986 			"%s : v4l2_async_register_subdev failed %d\n",
1987 			__func__, ret);
1988 		goto err_ctrls;
1989 	}
1990 
1991 	dev_info(&client->dev, "imx274 : imx274 probe success !\n");
1992 	return 0;
1993 
1994 err_ctrls:
1995 	v4l2_ctrl_handler_free(&imx274->ctrls.handler);
1996 err_me:
1997 	media_entity_cleanup(&sd->entity);
1998 err_regmap:
1999 	mutex_destroy(&imx274->lock);
2000 	return ret;
2001 }
2002 
imx274_remove(struct i2c_client * client)2003 static int imx274_remove(struct i2c_client *client)
2004 {
2005 	struct v4l2_subdev *sd = i2c_get_clientdata(client);
2006 	struct stimx274 *imx274 = to_imx274(sd);
2007 
2008 	/* stop stream */
2009 	imx274_write_table(imx274, imx274_stop);
2010 
2011 	v4l2_async_unregister_subdev(sd);
2012 	v4l2_ctrl_handler_free(&imx274->ctrls.handler);
2013 	media_entity_cleanup(&sd->entity);
2014 	mutex_destroy(&imx274->lock);
2015 	return 0;
2016 }
2017 
2018 static struct i2c_driver imx274_i2c_driver = {
2019 	.driver = {
2020 		.name	= DRIVER_NAME,
2021 		.of_match_table	= imx274_of_id_table,
2022 	},
2023 	.probe		= imx274_probe,
2024 	.remove		= imx274_remove,
2025 	.id_table	= imx274_id,
2026 };
2027 
2028 module_i2c_driver(imx274_i2c_driver);
2029 
2030 MODULE_AUTHOR("Leon Luo <leonl@leopardimaging.com>");
2031 MODULE_DESCRIPTION("IMX274 CMOS Image Sensor driver");
2032 MODULE_LICENSE("GPL v2");
2033