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