xref: /openbmc/linux/drivers/media/i2c/imx219.c (revision 31e67366)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * A V4L2 driver for Sony IMX219 cameras.
4  * Copyright (C) 2019, Raspberry Pi (Trading) Ltd
5  *
6  * Based on Sony imx258 camera driver
7  * Copyright (C) 2018 Intel Corporation
8  *
9  * DT / fwnode changes, and regulator / GPIO control taken from imx214 driver
10  * Copyright 2018 Qtechnology A/S
11  *
12  * Flip handling taken from the Sony IMX319 driver.
13  * Copyright (C) 2018 Intel Corporation
14  *
15  */
16 
17 #include <linux/clk.h>
18 #include <linux/delay.h>
19 #include <linux/gpio/consumer.h>
20 #include <linux/i2c.h>
21 #include <linux/module.h>
22 #include <linux/pm_runtime.h>
23 #include <linux/regulator/consumer.h>
24 #include <media/v4l2-ctrls.h>
25 #include <media/v4l2-device.h>
26 #include <media/v4l2-event.h>
27 #include <media/v4l2-fwnode.h>
28 #include <media/v4l2-mediabus.h>
29 #include <asm/unaligned.h>
30 
31 #define IMX219_REG_VALUE_08BIT		1
32 #define IMX219_REG_VALUE_16BIT		2
33 
34 #define IMX219_REG_MODE_SELECT		0x0100
35 #define IMX219_MODE_STANDBY		0x00
36 #define IMX219_MODE_STREAMING		0x01
37 
38 /* Chip ID */
39 #define IMX219_REG_CHIP_ID		0x0000
40 #define IMX219_CHIP_ID			0x0219
41 
42 /* External clock frequency is 24.0M */
43 #define IMX219_XCLK_FREQ		24000000
44 
45 /* Pixel rate is fixed at 182.4M for all the modes */
46 #define IMX219_PIXEL_RATE		182400000
47 
48 #define IMX219_DEFAULT_LINK_FREQ	456000000
49 
50 /* V_TIMING internal */
51 #define IMX219_REG_VTS			0x0160
52 #define IMX219_VTS_15FPS		0x0dc6
53 #define IMX219_VTS_30FPS_1080P		0x06e3
54 #define IMX219_VTS_30FPS_BINNED		0x06e3
55 #define IMX219_VTS_30FPS_640x480	0x06e3
56 #define IMX219_VTS_MAX			0xffff
57 
58 #define IMX219_VBLANK_MIN		4
59 
60 /*Frame Length Line*/
61 #define IMX219_FLL_MIN			0x08a6
62 #define IMX219_FLL_MAX			0xffff
63 #define IMX219_FLL_STEP			1
64 #define IMX219_FLL_DEFAULT		0x0c98
65 
66 /* HBLANK control - read only */
67 #define IMX219_PPL_DEFAULT		3448
68 
69 /* Exposure control */
70 #define IMX219_REG_EXPOSURE		0x015a
71 #define IMX219_EXPOSURE_MIN		4
72 #define IMX219_EXPOSURE_STEP		1
73 #define IMX219_EXPOSURE_DEFAULT		0x640
74 #define IMX219_EXPOSURE_MAX		65535
75 
76 /* Analog gain control */
77 #define IMX219_REG_ANALOG_GAIN		0x0157
78 #define IMX219_ANA_GAIN_MIN		0
79 #define IMX219_ANA_GAIN_MAX		232
80 #define IMX219_ANA_GAIN_STEP		1
81 #define IMX219_ANA_GAIN_DEFAULT		0x0
82 
83 /* Digital gain control */
84 #define IMX219_REG_DIGITAL_GAIN		0x0158
85 #define IMX219_DGTL_GAIN_MIN		0x0100
86 #define IMX219_DGTL_GAIN_MAX		0x0fff
87 #define IMX219_DGTL_GAIN_DEFAULT	0x0100
88 #define IMX219_DGTL_GAIN_STEP		1
89 
90 #define IMX219_REG_ORIENTATION		0x0172
91 
92 /* Test Pattern Control */
93 #define IMX219_REG_TEST_PATTERN		0x0600
94 #define IMX219_TEST_PATTERN_DISABLE	0
95 #define IMX219_TEST_PATTERN_SOLID_COLOR	1
96 #define IMX219_TEST_PATTERN_COLOR_BARS	2
97 #define IMX219_TEST_PATTERN_GREY_COLOR	3
98 #define IMX219_TEST_PATTERN_PN9		4
99 
100 /* Test pattern colour components */
101 #define IMX219_REG_TESTP_RED		0x0602
102 #define IMX219_REG_TESTP_GREENR		0x0604
103 #define IMX219_REG_TESTP_BLUE		0x0606
104 #define IMX219_REG_TESTP_GREENB		0x0608
105 #define IMX219_TESTP_COLOUR_MIN		0
106 #define IMX219_TESTP_COLOUR_MAX		0x03ff
107 #define IMX219_TESTP_COLOUR_STEP	1
108 #define IMX219_TESTP_RED_DEFAULT	IMX219_TESTP_COLOUR_MAX
109 #define IMX219_TESTP_GREENR_DEFAULT	0
110 #define IMX219_TESTP_BLUE_DEFAULT	0
111 #define IMX219_TESTP_GREENB_DEFAULT	0
112 
113 /* IMX219 native and active pixel array size. */
114 #define IMX219_NATIVE_WIDTH		3296U
115 #define IMX219_NATIVE_HEIGHT		2480U
116 #define IMX219_PIXEL_ARRAY_LEFT		8U
117 #define IMX219_PIXEL_ARRAY_TOP		8U
118 #define IMX219_PIXEL_ARRAY_WIDTH	3280U
119 #define IMX219_PIXEL_ARRAY_HEIGHT	2464U
120 
121 struct imx219_reg {
122 	u16 address;
123 	u8 val;
124 };
125 
126 struct imx219_reg_list {
127 	unsigned int num_of_regs;
128 	const struct imx219_reg *regs;
129 };
130 
131 /* Mode : resolution and related config&values */
132 struct imx219_mode {
133 	/* Frame width */
134 	unsigned int width;
135 	/* Frame height */
136 	unsigned int height;
137 
138 	/* Analog crop rectangle. */
139 	struct v4l2_rect crop;
140 
141 	/* V-timing */
142 	unsigned int vts_def;
143 
144 	/* Default register values */
145 	struct imx219_reg_list reg_list;
146 };
147 
148 /*
149  * Register sets lifted off the i2C interface from the Raspberry Pi firmware
150  * driver.
151  * 3280x2464 = mode 2, 1920x1080 = mode 1, 1640x1232 = mode 4, 640x480 = mode 7.
152  */
153 static const struct imx219_reg mode_3280x2464_regs[] = {
154 	{0x0100, 0x00},
155 	{0x30eb, 0x0c},
156 	{0x30eb, 0x05},
157 	{0x300a, 0xff},
158 	{0x300b, 0xff},
159 	{0x30eb, 0x05},
160 	{0x30eb, 0x09},
161 	{0x0114, 0x01},
162 	{0x0128, 0x00},
163 	{0x012a, 0x18},
164 	{0x012b, 0x00},
165 	{0x0164, 0x00},
166 	{0x0165, 0x00},
167 	{0x0166, 0x0c},
168 	{0x0167, 0xcf},
169 	{0x0168, 0x00},
170 	{0x0169, 0x00},
171 	{0x016a, 0x09},
172 	{0x016b, 0x9f},
173 	{0x016c, 0x0c},
174 	{0x016d, 0xd0},
175 	{0x016e, 0x09},
176 	{0x016f, 0xa0},
177 	{0x0170, 0x01},
178 	{0x0171, 0x01},
179 	{0x0174, 0x00},
180 	{0x0175, 0x00},
181 	{0x0301, 0x05},
182 	{0x0303, 0x01},
183 	{0x0304, 0x03},
184 	{0x0305, 0x03},
185 	{0x0306, 0x00},
186 	{0x0307, 0x39},
187 	{0x030b, 0x01},
188 	{0x030c, 0x00},
189 	{0x030d, 0x72},
190 	{0x0624, 0x0c},
191 	{0x0625, 0xd0},
192 	{0x0626, 0x09},
193 	{0x0627, 0xa0},
194 	{0x455e, 0x00},
195 	{0x471e, 0x4b},
196 	{0x4767, 0x0f},
197 	{0x4750, 0x14},
198 	{0x4540, 0x00},
199 	{0x47b4, 0x14},
200 	{0x4713, 0x30},
201 	{0x478b, 0x10},
202 	{0x478f, 0x10},
203 	{0x4793, 0x10},
204 	{0x4797, 0x0e},
205 	{0x479b, 0x0e},
206 	{0x0162, 0x0d},
207 	{0x0163, 0x78},
208 };
209 
210 static const struct imx219_reg mode_1920_1080_regs[] = {
211 	{0x0100, 0x00},
212 	{0x30eb, 0x05},
213 	{0x30eb, 0x0c},
214 	{0x300a, 0xff},
215 	{0x300b, 0xff},
216 	{0x30eb, 0x05},
217 	{0x30eb, 0x09},
218 	{0x0114, 0x01},
219 	{0x0128, 0x00},
220 	{0x012a, 0x18},
221 	{0x012b, 0x00},
222 	{0x0162, 0x0d},
223 	{0x0163, 0x78},
224 	{0x0164, 0x02},
225 	{0x0165, 0xa8},
226 	{0x0166, 0x0a},
227 	{0x0167, 0x27},
228 	{0x0168, 0x02},
229 	{0x0169, 0xb4},
230 	{0x016a, 0x06},
231 	{0x016b, 0xeb},
232 	{0x016c, 0x07},
233 	{0x016d, 0x80},
234 	{0x016e, 0x04},
235 	{0x016f, 0x38},
236 	{0x0170, 0x01},
237 	{0x0171, 0x01},
238 	{0x0174, 0x00},
239 	{0x0175, 0x00},
240 	{0x0301, 0x05},
241 	{0x0303, 0x01},
242 	{0x0304, 0x03},
243 	{0x0305, 0x03},
244 	{0x0306, 0x00},
245 	{0x0307, 0x39},
246 	{0x030b, 0x01},
247 	{0x030c, 0x00},
248 	{0x030d, 0x72},
249 	{0x0624, 0x07},
250 	{0x0625, 0x80},
251 	{0x0626, 0x04},
252 	{0x0627, 0x38},
253 	{0x455e, 0x00},
254 	{0x471e, 0x4b},
255 	{0x4767, 0x0f},
256 	{0x4750, 0x14},
257 	{0x4540, 0x00},
258 	{0x47b4, 0x14},
259 	{0x4713, 0x30},
260 	{0x478b, 0x10},
261 	{0x478f, 0x10},
262 	{0x4793, 0x10},
263 	{0x4797, 0x0e},
264 	{0x479b, 0x0e},
265 };
266 
267 static const struct imx219_reg mode_1640_1232_regs[] = {
268 	{0x0100, 0x00},
269 	{0x30eb, 0x0c},
270 	{0x30eb, 0x05},
271 	{0x300a, 0xff},
272 	{0x300b, 0xff},
273 	{0x30eb, 0x05},
274 	{0x30eb, 0x09},
275 	{0x0114, 0x01},
276 	{0x0128, 0x00},
277 	{0x012a, 0x18},
278 	{0x012b, 0x00},
279 	{0x0164, 0x00},
280 	{0x0165, 0x00},
281 	{0x0166, 0x0c},
282 	{0x0167, 0xcf},
283 	{0x0168, 0x00},
284 	{0x0169, 0x00},
285 	{0x016a, 0x09},
286 	{0x016b, 0x9f},
287 	{0x016c, 0x06},
288 	{0x016d, 0x68},
289 	{0x016e, 0x04},
290 	{0x016f, 0xd0},
291 	{0x0170, 0x01},
292 	{0x0171, 0x01},
293 	{0x0174, 0x01},
294 	{0x0175, 0x01},
295 	{0x0301, 0x05},
296 	{0x0303, 0x01},
297 	{0x0304, 0x03},
298 	{0x0305, 0x03},
299 	{0x0306, 0x00},
300 	{0x0307, 0x39},
301 	{0x030b, 0x01},
302 	{0x030c, 0x00},
303 	{0x030d, 0x72},
304 	{0x0624, 0x06},
305 	{0x0625, 0x68},
306 	{0x0626, 0x04},
307 	{0x0627, 0xd0},
308 	{0x455e, 0x00},
309 	{0x471e, 0x4b},
310 	{0x4767, 0x0f},
311 	{0x4750, 0x14},
312 	{0x4540, 0x00},
313 	{0x47b4, 0x14},
314 	{0x4713, 0x30},
315 	{0x478b, 0x10},
316 	{0x478f, 0x10},
317 	{0x4793, 0x10},
318 	{0x4797, 0x0e},
319 	{0x479b, 0x0e},
320 	{0x0162, 0x0d},
321 	{0x0163, 0x78},
322 };
323 
324 static const struct imx219_reg mode_640_480_regs[] = {
325 	{0x0100, 0x00},
326 	{0x30eb, 0x05},
327 	{0x30eb, 0x0c},
328 	{0x300a, 0xff},
329 	{0x300b, 0xff},
330 	{0x30eb, 0x05},
331 	{0x30eb, 0x09},
332 	{0x0114, 0x01},
333 	{0x0128, 0x00},
334 	{0x012a, 0x18},
335 	{0x012b, 0x00},
336 	{0x0162, 0x0d},
337 	{0x0163, 0x78},
338 	{0x0164, 0x03},
339 	{0x0165, 0xe8},
340 	{0x0166, 0x08},
341 	{0x0167, 0xe7},
342 	{0x0168, 0x02},
343 	{0x0169, 0xf0},
344 	{0x016a, 0x06},
345 	{0x016b, 0xaf},
346 	{0x016c, 0x02},
347 	{0x016d, 0x80},
348 	{0x016e, 0x01},
349 	{0x016f, 0xe0},
350 	{0x0170, 0x01},
351 	{0x0171, 0x01},
352 	{0x0174, 0x03},
353 	{0x0175, 0x03},
354 	{0x0301, 0x05},
355 	{0x0303, 0x01},
356 	{0x0304, 0x03},
357 	{0x0305, 0x03},
358 	{0x0306, 0x00},
359 	{0x0307, 0x39},
360 	{0x030b, 0x01},
361 	{0x030c, 0x00},
362 	{0x030d, 0x72},
363 	{0x0624, 0x06},
364 	{0x0625, 0x68},
365 	{0x0626, 0x04},
366 	{0x0627, 0xd0},
367 	{0x455e, 0x00},
368 	{0x471e, 0x4b},
369 	{0x4767, 0x0f},
370 	{0x4750, 0x14},
371 	{0x4540, 0x00},
372 	{0x47b4, 0x14},
373 	{0x4713, 0x30},
374 	{0x478b, 0x10},
375 	{0x478f, 0x10},
376 	{0x4793, 0x10},
377 	{0x4797, 0x0e},
378 	{0x479b, 0x0e},
379 };
380 
381 static const struct imx219_reg raw8_framefmt_regs[] = {
382 	{0x018c, 0x08},
383 	{0x018d, 0x08},
384 	{0x0309, 0x08},
385 };
386 
387 static const struct imx219_reg raw10_framefmt_regs[] = {
388 	{0x018c, 0x0a},
389 	{0x018d, 0x0a},
390 	{0x0309, 0x0a},
391 };
392 
393 static const s64 imx219_link_freq_menu[] = {
394 	IMX219_DEFAULT_LINK_FREQ,
395 };
396 
397 static const char * const imx219_test_pattern_menu[] = {
398 	"Disabled",
399 	"Color Bars",
400 	"Solid Color",
401 	"Grey Color Bars",
402 	"PN9"
403 };
404 
405 static const int imx219_test_pattern_val[] = {
406 	IMX219_TEST_PATTERN_DISABLE,
407 	IMX219_TEST_PATTERN_COLOR_BARS,
408 	IMX219_TEST_PATTERN_SOLID_COLOR,
409 	IMX219_TEST_PATTERN_GREY_COLOR,
410 	IMX219_TEST_PATTERN_PN9,
411 };
412 
413 /* regulator supplies */
414 static const char * const imx219_supply_name[] = {
415 	/* Supplies can be enabled in any order */
416 	"VANA",  /* Analog (2.8V) supply */
417 	"VDIG",  /* Digital Core (1.8V) supply */
418 	"VDDL",  /* IF (1.2V) supply */
419 };
420 
421 #define IMX219_NUM_SUPPLIES ARRAY_SIZE(imx219_supply_name)
422 
423 /*
424  * The supported formats.
425  * This table MUST contain 4 entries per format, to cover the various flip
426  * combinations in the order
427  * - no flip
428  * - h flip
429  * - v flip
430  * - h&v flips
431  */
432 static const u32 codes[] = {
433 	MEDIA_BUS_FMT_SRGGB10_1X10,
434 	MEDIA_BUS_FMT_SGRBG10_1X10,
435 	MEDIA_BUS_FMT_SGBRG10_1X10,
436 	MEDIA_BUS_FMT_SBGGR10_1X10,
437 
438 	MEDIA_BUS_FMT_SRGGB8_1X8,
439 	MEDIA_BUS_FMT_SGRBG8_1X8,
440 	MEDIA_BUS_FMT_SGBRG8_1X8,
441 	MEDIA_BUS_FMT_SBGGR8_1X8,
442 };
443 
444 /*
445  * Initialisation delay between XCLR low->high and the moment when the sensor
446  * can start capture (i.e. can leave software stanby) must be not less than:
447  *   t4 + max(t5, t6 + <time to initialize the sensor register over I2C>)
448  * where
449  *   t4 is fixed, and is max 200uS,
450  *   t5 is fixed, and is 6000uS,
451  *   t6 depends on the sensor external clock, and is max 32000 clock periods.
452  * As per sensor datasheet, the external clock must be from 6MHz to 27MHz.
453  * So for any acceptable external clock t6 is always within the range of
454  * 1185 to 5333 uS, and is always less than t5.
455  * For this reason this is always safe to wait (t4 + t5) = 6200 uS, then
456  * initialize the sensor over I2C, and then exit the software standby.
457  *
458  * This start-up time can be optimized a bit more, if we start the writes
459  * over I2C after (t4+t6), but before (t4+t5) expires. But then sensor
460  * initialization over I2C may complete before (t4+t5) expires, and we must
461  * ensure that capture is not started before (t4+t5).
462  *
463  * This delay doesn't account for the power supply startup time. If needed,
464  * this should be taken care of via the regulator framework. E.g. in the
465  * case of DT for regulator-fixed one should define the startup-delay-us
466  * property.
467  */
468 #define IMX219_XCLR_MIN_DELAY_US	6200
469 #define IMX219_XCLR_DELAY_RANGE_US	1000
470 
471 /* Mode configs */
472 static const struct imx219_mode supported_modes[] = {
473 	{
474 		/* 8MPix 15fps mode */
475 		.width = 3280,
476 		.height = 2464,
477 		.crop = {
478 			.left = IMX219_PIXEL_ARRAY_LEFT,
479 			.top = IMX219_PIXEL_ARRAY_TOP,
480 			.width = 3280,
481 			.height = 2464
482 		},
483 		.vts_def = IMX219_VTS_15FPS,
484 		.reg_list = {
485 			.num_of_regs = ARRAY_SIZE(mode_3280x2464_regs),
486 			.regs = mode_3280x2464_regs,
487 		},
488 	},
489 	{
490 		/* 1080P 30fps cropped */
491 		.width = 1920,
492 		.height = 1080,
493 		.crop = {
494 			.left = 688,
495 			.top = 700,
496 			.width = 1920,
497 			.height = 1080
498 		},
499 		.vts_def = IMX219_VTS_30FPS_1080P,
500 		.reg_list = {
501 			.num_of_regs = ARRAY_SIZE(mode_1920_1080_regs),
502 			.regs = mode_1920_1080_regs,
503 		},
504 	},
505 	{
506 		/* 2x2 binned 30fps mode */
507 		.width = 1640,
508 		.height = 1232,
509 		.crop = {
510 			.left = IMX219_PIXEL_ARRAY_LEFT,
511 			.top = IMX219_PIXEL_ARRAY_TOP,
512 			.width = 3280,
513 			.height = 2464
514 		},
515 		.vts_def = IMX219_VTS_30FPS_BINNED,
516 		.reg_list = {
517 			.num_of_regs = ARRAY_SIZE(mode_1640_1232_regs),
518 			.regs = mode_1640_1232_regs,
519 		},
520 	},
521 	{
522 		/* 640x480 30fps mode */
523 		.width = 640,
524 		.height = 480,
525 		.crop = {
526 			.left = 1008,
527 			.top = 760,
528 			.width = 1280,
529 			.height = 960
530 		},
531 		.vts_def = IMX219_VTS_30FPS_640x480,
532 		.reg_list = {
533 			.num_of_regs = ARRAY_SIZE(mode_640_480_regs),
534 			.regs = mode_640_480_regs,
535 		},
536 	},
537 };
538 
539 struct imx219 {
540 	struct v4l2_subdev sd;
541 	struct media_pad pad;
542 
543 	struct v4l2_mbus_framefmt fmt;
544 
545 	struct clk *xclk; /* system clock to IMX219 */
546 	u32 xclk_freq;
547 
548 	struct gpio_desc *reset_gpio;
549 	struct regulator_bulk_data supplies[IMX219_NUM_SUPPLIES];
550 
551 	struct v4l2_ctrl_handler ctrl_handler;
552 	/* V4L2 Controls */
553 	struct v4l2_ctrl *pixel_rate;
554 	struct v4l2_ctrl *link_freq;
555 	struct v4l2_ctrl *exposure;
556 	struct v4l2_ctrl *vflip;
557 	struct v4l2_ctrl *hflip;
558 	struct v4l2_ctrl *vblank;
559 	struct v4l2_ctrl *hblank;
560 
561 	/* Current mode */
562 	const struct imx219_mode *mode;
563 
564 	/*
565 	 * Mutex for serialized access:
566 	 * Protect sensor module set pad format and start/stop streaming safely.
567 	 */
568 	struct mutex mutex;
569 
570 	/* Streaming on/off */
571 	bool streaming;
572 };
573 
574 static inline struct imx219 *to_imx219(struct v4l2_subdev *_sd)
575 {
576 	return container_of(_sd, struct imx219, sd);
577 }
578 
579 /* Read registers up to 2 at a time */
580 static int imx219_read_reg(struct imx219 *imx219, u16 reg, u32 len, u32 *val)
581 {
582 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
583 	struct i2c_msg msgs[2];
584 	u8 addr_buf[2] = { reg >> 8, reg & 0xff };
585 	u8 data_buf[4] = { 0, };
586 	int ret;
587 
588 	if (len > 4)
589 		return -EINVAL;
590 
591 	/* Write register address */
592 	msgs[0].addr = client->addr;
593 	msgs[0].flags = 0;
594 	msgs[0].len = ARRAY_SIZE(addr_buf);
595 	msgs[0].buf = addr_buf;
596 
597 	/* Read data from register */
598 	msgs[1].addr = client->addr;
599 	msgs[1].flags = I2C_M_RD;
600 	msgs[1].len = len;
601 	msgs[1].buf = &data_buf[4 - len];
602 
603 	ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
604 	if (ret != ARRAY_SIZE(msgs))
605 		return -EIO;
606 
607 	*val = get_unaligned_be32(data_buf);
608 
609 	return 0;
610 }
611 
612 /* Write registers up to 2 at a time */
613 static int imx219_write_reg(struct imx219 *imx219, u16 reg, u32 len, u32 val)
614 {
615 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
616 	u8 buf[6];
617 
618 	if (len > 4)
619 		return -EINVAL;
620 
621 	put_unaligned_be16(reg, buf);
622 	put_unaligned_be32(val << (8 * (4 - len)), buf + 2);
623 	if (i2c_master_send(client, buf, len + 2) != len + 2)
624 		return -EIO;
625 
626 	return 0;
627 }
628 
629 /* Write a list of registers */
630 static int imx219_write_regs(struct imx219 *imx219,
631 			     const struct imx219_reg *regs, u32 len)
632 {
633 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
634 	unsigned int i;
635 	int ret;
636 
637 	for (i = 0; i < len; i++) {
638 		ret = imx219_write_reg(imx219, regs[i].address, 1, regs[i].val);
639 		if (ret) {
640 			dev_err_ratelimited(&client->dev,
641 					    "Failed to write reg 0x%4.4x. error = %d\n",
642 					    regs[i].address, ret);
643 
644 			return ret;
645 		}
646 	}
647 
648 	return 0;
649 }
650 
651 /* Get bayer order based on flip setting. */
652 static u32 imx219_get_format_code(struct imx219 *imx219, u32 code)
653 {
654 	unsigned int i;
655 
656 	lockdep_assert_held(&imx219->mutex);
657 
658 	for (i = 0; i < ARRAY_SIZE(codes); i++)
659 		if (codes[i] == code)
660 			break;
661 
662 	if (i >= ARRAY_SIZE(codes))
663 		i = 0;
664 
665 	i = (i & ~3) | (imx219->vflip->val ? 2 : 0) |
666 	    (imx219->hflip->val ? 1 : 0);
667 
668 	return codes[i];
669 }
670 
671 static void imx219_set_default_format(struct imx219 *imx219)
672 {
673 	struct v4l2_mbus_framefmt *fmt;
674 
675 	fmt = &imx219->fmt;
676 	fmt->code = MEDIA_BUS_FMT_SRGGB10_1X10;
677 	fmt->colorspace = V4L2_COLORSPACE_SRGB;
678 	fmt->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(fmt->colorspace);
679 	fmt->quantization = V4L2_MAP_QUANTIZATION_DEFAULT(true,
680 							  fmt->colorspace,
681 							  fmt->ycbcr_enc);
682 	fmt->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(fmt->colorspace);
683 	fmt->width = supported_modes[0].width;
684 	fmt->height = supported_modes[0].height;
685 	fmt->field = V4L2_FIELD_NONE;
686 }
687 
688 static int imx219_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
689 {
690 	struct imx219 *imx219 = to_imx219(sd);
691 	struct v4l2_mbus_framefmt *try_fmt =
692 		v4l2_subdev_get_try_format(sd, fh->pad, 0);
693 	struct v4l2_rect *try_crop;
694 
695 	mutex_lock(&imx219->mutex);
696 
697 	/* Initialize try_fmt */
698 	try_fmt->width = supported_modes[0].width;
699 	try_fmt->height = supported_modes[0].height;
700 	try_fmt->code = imx219_get_format_code(imx219,
701 					       MEDIA_BUS_FMT_SRGGB10_1X10);
702 	try_fmt->field = V4L2_FIELD_NONE;
703 
704 	/* Initialize try_crop rectangle. */
705 	try_crop = v4l2_subdev_get_try_crop(sd, fh->pad, 0);
706 	try_crop->top = IMX219_PIXEL_ARRAY_TOP;
707 	try_crop->left = IMX219_PIXEL_ARRAY_LEFT;
708 	try_crop->width = IMX219_PIXEL_ARRAY_WIDTH;
709 	try_crop->height = IMX219_PIXEL_ARRAY_HEIGHT;
710 
711 	mutex_unlock(&imx219->mutex);
712 
713 	return 0;
714 }
715 
716 static int imx219_set_ctrl(struct v4l2_ctrl *ctrl)
717 {
718 	struct imx219 *imx219 =
719 		container_of(ctrl->handler, struct imx219, ctrl_handler);
720 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
721 	int ret;
722 
723 	if (ctrl->id == V4L2_CID_VBLANK) {
724 		int exposure_max, exposure_def;
725 
726 		/* Update max exposure while meeting expected vblanking */
727 		exposure_max = imx219->mode->height + ctrl->val - 4;
728 		exposure_def = (exposure_max < IMX219_EXPOSURE_DEFAULT) ?
729 			exposure_max : IMX219_EXPOSURE_DEFAULT;
730 		__v4l2_ctrl_modify_range(imx219->exposure,
731 					 imx219->exposure->minimum,
732 					 exposure_max, imx219->exposure->step,
733 					 exposure_def);
734 	}
735 
736 	/*
737 	 * Applying V4L2 control value only happens
738 	 * when power is up for streaming
739 	 */
740 	if (pm_runtime_get_if_in_use(&client->dev) == 0)
741 		return 0;
742 
743 	switch (ctrl->id) {
744 	case V4L2_CID_ANALOGUE_GAIN:
745 		ret = imx219_write_reg(imx219, IMX219_REG_ANALOG_GAIN,
746 				       IMX219_REG_VALUE_08BIT, ctrl->val);
747 		break;
748 	case V4L2_CID_EXPOSURE:
749 		ret = imx219_write_reg(imx219, IMX219_REG_EXPOSURE,
750 				       IMX219_REG_VALUE_16BIT, ctrl->val);
751 		break;
752 	case V4L2_CID_DIGITAL_GAIN:
753 		ret = imx219_write_reg(imx219, IMX219_REG_DIGITAL_GAIN,
754 				       IMX219_REG_VALUE_16BIT, ctrl->val);
755 		break;
756 	case V4L2_CID_TEST_PATTERN:
757 		ret = imx219_write_reg(imx219, IMX219_REG_TEST_PATTERN,
758 				       IMX219_REG_VALUE_16BIT,
759 				       imx219_test_pattern_val[ctrl->val]);
760 		break;
761 	case V4L2_CID_HFLIP:
762 	case V4L2_CID_VFLIP:
763 		ret = imx219_write_reg(imx219, IMX219_REG_ORIENTATION, 1,
764 				       imx219->hflip->val |
765 				       imx219->vflip->val << 1);
766 		break;
767 	case V4L2_CID_VBLANK:
768 		ret = imx219_write_reg(imx219, IMX219_REG_VTS,
769 				       IMX219_REG_VALUE_16BIT,
770 				       imx219->mode->height + ctrl->val);
771 		break;
772 	case V4L2_CID_TEST_PATTERN_RED:
773 		ret = imx219_write_reg(imx219, IMX219_REG_TESTP_RED,
774 				       IMX219_REG_VALUE_16BIT, ctrl->val);
775 		break;
776 	case V4L2_CID_TEST_PATTERN_GREENR:
777 		ret = imx219_write_reg(imx219, IMX219_REG_TESTP_GREENR,
778 				       IMX219_REG_VALUE_16BIT, ctrl->val);
779 		break;
780 	case V4L2_CID_TEST_PATTERN_BLUE:
781 		ret = imx219_write_reg(imx219, IMX219_REG_TESTP_BLUE,
782 				       IMX219_REG_VALUE_16BIT, ctrl->val);
783 		break;
784 	case V4L2_CID_TEST_PATTERN_GREENB:
785 		ret = imx219_write_reg(imx219, IMX219_REG_TESTP_GREENB,
786 				       IMX219_REG_VALUE_16BIT, ctrl->val);
787 		break;
788 	default:
789 		dev_info(&client->dev,
790 			 "ctrl(id:0x%x,val:0x%x) is not handled\n",
791 			 ctrl->id, ctrl->val);
792 		ret = -EINVAL;
793 		break;
794 	}
795 
796 	pm_runtime_put(&client->dev);
797 
798 	return ret;
799 }
800 
801 static const struct v4l2_ctrl_ops imx219_ctrl_ops = {
802 	.s_ctrl = imx219_set_ctrl,
803 };
804 
805 static int imx219_enum_mbus_code(struct v4l2_subdev *sd,
806 				 struct v4l2_subdev_pad_config *cfg,
807 				 struct v4l2_subdev_mbus_code_enum *code)
808 {
809 	struct imx219 *imx219 = to_imx219(sd);
810 
811 	if (code->index >= (ARRAY_SIZE(codes) / 4))
812 		return -EINVAL;
813 
814 	mutex_lock(&imx219->mutex);
815 	code->code = imx219_get_format_code(imx219, codes[code->index * 4]);
816 	mutex_unlock(&imx219->mutex);
817 
818 	return 0;
819 }
820 
821 static int imx219_enum_frame_size(struct v4l2_subdev *sd,
822 				  struct v4l2_subdev_pad_config *cfg,
823 				  struct v4l2_subdev_frame_size_enum *fse)
824 {
825 	struct imx219 *imx219 = to_imx219(sd);
826 	u32 code;
827 
828 	if (fse->index >= ARRAY_SIZE(supported_modes))
829 		return -EINVAL;
830 
831 	mutex_lock(&imx219->mutex);
832 	code = imx219_get_format_code(imx219, fse->code);
833 	mutex_unlock(&imx219->mutex);
834 	if (fse->code != code)
835 		return -EINVAL;
836 
837 	fse->min_width = supported_modes[fse->index].width;
838 	fse->max_width = fse->min_width;
839 	fse->min_height = supported_modes[fse->index].height;
840 	fse->max_height = fse->min_height;
841 
842 	return 0;
843 }
844 
845 static void imx219_reset_colorspace(struct v4l2_mbus_framefmt *fmt)
846 {
847 	fmt->colorspace = V4L2_COLORSPACE_SRGB;
848 	fmt->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(fmt->colorspace);
849 	fmt->quantization = V4L2_MAP_QUANTIZATION_DEFAULT(true,
850 							  fmt->colorspace,
851 							  fmt->ycbcr_enc);
852 	fmt->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(fmt->colorspace);
853 }
854 
855 static void imx219_update_pad_format(struct imx219 *imx219,
856 				     const struct imx219_mode *mode,
857 				     struct v4l2_subdev_format *fmt)
858 {
859 	fmt->format.width = mode->width;
860 	fmt->format.height = mode->height;
861 	fmt->format.field = V4L2_FIELD_NONE;
862 	imx219_reset_colorspace(&fmt->format);
863 }
864 
865 static int __imx219_get_pad_format(struct imx219 *imx219,
866 				   struct v4l2_subdev_pad_config *cfg,
867 				   struct v4l2_subdev_format *fmt)
868 {
869 	if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
870 		struct v4l2_mbus_framefmt *try_fmt =
871 			v4l2_subdev_get_try_format(&imx219->sd, cfg, fmt->pad);
872 		/* update the code which could change due to vflip or hflip: */
873 		try_fmt->code = imx219_get_format_code(imx219, try_fmt->code);
874 		fmt->format = *try_fmt;
875 	} else {
876 		imx219_update_pad_format(imx219, imx219->mode, fmt);
877 		fmt->format.code = imx219_get_format_code(imx219,
878 							  imx219->fmt.code);
879 	}
880 
881 	return 0;
882 }
883 
884 static int imx219_get_pad_format(struct v4l2_subdev *sd,
885 				 struct v4l2_subdev_pad_config *cfg,
886 				 struct v4l2_subdev_format *fmt)
887 {
888 	struct imx219 *imx219 = to_imx219(sd);
889 	int ret;
890 
891 	mutex_lock(&imx219->mutex);
892 	ret = __imx219_get_pad_format(imx219, cfg, fmt);
893 	mutex_unlock(&imx219->mutex);
894 
895 	return ret;
896 }
897 
898 static int imx219_set_pad_format(struct v4l2_subdev *sd,
899 				 struct v4l2_subdev_pad_config *cfg,
900 				 struct v4l2_subdev_format *fmt)
901 {
902 	struct imx219 *imx219 = to_imx219(sd);
903 	const struct imx219_mode *mode;
904 	struct v4l2_mbus_framefmt *framefmt;
905 	int exposure_max, exposure_def, hblank;
906 	unsigned int i;
907 
908 	mutex_lock(&imx219->mutex);
909 
910 	for (i = 0; i < ARRAY_SIZE(codes); i++)
911 		if (codes[i] == fmt->format.code)
912 			break;
913 	if (i >= ARRAY_SIZE(codes))
914 		i = 0;
915 
916 	/* Bayer order varies with flips */
917 	fmt->format.code = imx219_get_format_code(imx219, codes[i]);
918 
919 	mode = v4l2_find_nearest_size(supported_modes,
920 				      ARRAY_SIZE(supported_modes),
921 				      width, height,
922 				      fmt->format.width, fmt->format.height);
923 	imx219_update_pad_format(imx219, mode, fmt);
924 	if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
925 		framefmt = v4l2_subdev_get_try_format(sd, cfg, fmt->pad);
926 		*framefmt = fmt->format;
927 	} else if (imx219->mode != mode ||
928 		   imx219->fmt.code != fmt->format.code) {
929 		imx219->fmt = fmt->format;
930 		imx219->mode = mode;
931 		/* Update limits and set FPS to default */
932 		__v4l2_ctrl_modify_range(imx219->vblank, IMX219_VBLANK_MIN,
933 					 IMX219_VTS_MAX - mode->height, 1,
934 					 mode->vts_def - mode->height);
935 		__v4l2_ctrl_s_ctrl(imx219->vblank,
936 				   mode->vts_def - mode->height);
937 		/* Update max exposure while meeting expected vblanking */
938 		exposure_max = mode->vts_def - 4;
939 		exposure_def = (exposure_max < IMX219_EXPOSURE_DEFAULT) ?
940 			exposure_max : IMX219_EXPOSURE_DEFAULT;
941 		__v4l2_ctrl_modify_range(imx219->exposure,
942 					 imx219->exposure->minimum,
943 					 exposure_max, imx219->exposure->step,
944 					 exposure_def);
945 		/*
946 		 * Currently PPL is fixed to IMX219_PPL_DEFAULT, so hblank
947 		 * depends on mode->width only, and is not changeble in any
948 		 * way other than changing the mode.
949 		 */
950 		hblank = IMX219_PPL_DEFAULT - mode->width;
951 		__v4l2_ctrl_modify_range(imx219->hblank, hblank, hblank, 1,
952 					 hblank);
953 	}
954 
955 	mutex_unlock(&imx219->mutex);
956 
957 	return 0;
958 }
959 
960 static int imx219_set_framefmt(struct imx219 *imx219)
961 {
962 	switch (imx219->fmt.code) {
963 	case MEDIA_BUS_FMT_SRGGB8_1X8:
964 	case MEDIA_BUS_FMT_SGRBG8_1X8:
965 	case MEDIA_BUS_FMT_SGBRG8_1X8:
966 	case MEDIA_BUS_FMT_SBGGR8_1X8:
967 		return imx219_write_regs(imx219, raw8_framefmt_regs,
968 					ARRAY_SIZE(raw8_framefmt_regs));
969 
970 	case MEDIA_BUS_FMT_SRGGB10_1X10:
971 	case MEDIA_BUS_FMT_SGRBG10_1X10:
972 	case MEDIA_BUS_FMT_SGBRG10_1X10:
973 	case MEDIA_BUS_FMT_SBGGR10_1X10:
974 		return imx219_write_regs(imx219, raw10_framefmt_regs,
975 					ARRAY_SIZE(raw10_framefmt_regs));
976 	}
977 
978 	return -EINVAL;
979 }
980 
981 static const struct v4l2_rect *
982 __imx219_get_pad_crop(struct imx219 *imx219, struct v4l2_subdev_pad_config *cfg,
983 		      unsigned int pad, enum v4l2_subdev_format_whence which)
984 {
985 	switch (which) {
986 	case V4L2_SUBDEV_FORMAT_TRY:
987 		return v4l2_subdev_get_try_crop(&imx219->sd, cfg, pad);
988 	case V4L2_SUBDEV_FORMAT_ACTIVE:
989 		return &imx219->mode->crop;
990 	}
991 
992 	return NULL;
993 }
994 
995 static int imx219_get_selection(struct v4l2_subdev *sd,
996 				struct v4l2_subdev_pad_config *cfg,
997 				struct v4l2_subdev_selection *sel)
998 {
999 	switch (sel->target) {
1000 	case V4L2_SEL_TGT_CROP: {
1001 		struct imx219 *imx219 = to_imx219(sd);
1002 
1003 		mutex_lock(&imx219->mutex);
1004 		sel->r = *__imx219_get_pad_crop(imx219, cfg, sel->pad,
1005 						sel->which);
1006 		mutex_unlock(&imx219->mutex);
1007 
1008 		return 0;
1009 	}
1010 
1011 	case V4L2_SEL_TGT_NATIVE_SIZE:
1012 		sel->r.top = 0;
1013 		sel->r.left = 0;
1014 		sel->r.width = IMX219_NATIVE_WIDTH;
1015 		sel->r.height = IMX219_NATIVE_HEIGHT;
1016 
1017 		return 0;
1018 
1019 	case V4L2_SEL_TGT_CROP_DEFAULT:
1020 	case V4L2_SEL_TGT_CROP_BOUNDS:
1021 		sel->r.top = IMX219_PIXEL_ARRAY_TOP;
1022 		sel->r.left = IMX219_PIXEL_ARRAY_LEFT;
1023 		sel->r.width = IMX219_PIXEL_ARRAY_WIDTH;
1024 		sel->r.height = IMX219_PIXEL_ARRAY_HEIGHT;
1025 
1026 		return 0;
1027 	}
1028 
1029 	return -EINVAL;
1030 }
1031 
1032 static int imx219_start_streaming(struct imx219 *imx219)
1033 {
1034 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
1035 	const struct imx219_reg_list *reg_list;
1036 	int ret;
1037 
1038 	/* Apply default values of current mode */
1039 	reg_list = &imx219->mode->reg_list;
1040 	ret = imx219_write_regs(imx219, reg_list->regs, reg_list->num_of_regs);
1041 	if (ret) {
1042 		dev_err(&client->dev, "%s failed to set mode\n", __func__);
1043 		return ret;
1044 	}
1045 
1046 	ret = imx219_set_framefmt(imx219);
1047 	if (ret) {
1048 		dev_err(&client->dev, "%s failed to set frame format: %d\n",
1049 			__func__, ret);
1050 		return ret;
1051 	}
1052 
1053 	/* Apply customized values from user */
1054 	ret =  __v4l2_ctrl_handler_setup(imx219->sd.ctrl_handler);
1055 	if (ret)
1056 		return ret;
1057 
1058 	/* set stream on register */
1059 	return imx219_write_reg(imx219, IMX219_REG_MODE_SELECT,
1060 				IMX219_REG_VALUE_08BIT, IMX219_MODE_STREAMING);
1061 }
1062 
1063 static void imx219_stop_streaming(struct imx219 *imx219)
1064 {
1065 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
1066 	int ret;
1067 
1068 	/* set stream off register */
1069 	ret = imx219_write_reg(imx219, IMX219_REG_MODE_SELECT,
1070 			       IMX219_REG_VALUE_08BIT, IMX219_MODE_STANDBY);
1071 	if (ret)
1072 		dev_err(&client->dev, "%s failed to set stream\n", __func__);
1073 }
1074 
1075 static int imx219_set_stream(struct v4l2_subdev *sd, int enable)
1076 {
1077 	struct imx219 *imx219 = to_imx219(sd);
1078 	struct i2c_client *client = v4l2_get_subdevdata(sd);
1079 	int ret = 0;
1080 
1081 	mutex_lock(&imx219->mutex);
1082 	if (imx219->streaming == enable) {
1083 		mutex_unlock(&imx219->mutex);
1084 		return 0;
1085 	}
1086 
1087 	if (enable) {
1088 		ret = pm_runtime_get_sync(&client->dev);
1089 		if (ret < 0) {
1090 			pm_runtime_put_noidle(&client->dev);
1091 			goto err_unlock;
1092 		}
1093 
1094 		/*
1095 		 * Apply default & customized values
1096 		 * and then start streaming.
1097 		 */
1098 		ret = imx219_start_streaming(imx219);
1099 		if (ret)
1100 			goto err_rpm_put;
1101 	} else {
1102 		imx219_stop_streaming(imx219);
1103 		pm_runtime_put(&client->dev);
1104 	}
1105 
1106 	imx219->streaming = enable;
1107 
1108 	/* vflip and hflip cannot change during streaming */
1109 	__v4l2_ctrl_grab(imx219->vflip, enable);
1110 	__v4l2_ctrl_grab(imx219->hflip, enable);
1111 
1112 	mutex_unlock(&imx219->mutex);
1113 
1114 	return ret;
1115 
1116 err_rpm_put:
1117 	pm_runtime_put(&client->dev);
1118 err_unlock:
1119 	mutex_unlock(&imx219->mutex);
1120 
1121 	return ret;
1122 }
1123 
1124 /* Power/clock management functions */
1125 static int imx219_power_on(struct device *dev)
1126 {
1127 	struct v4l2_subdev *sd = dev_get_drvdata(dev);
1128 	struct imx219 *imx219 = to_imx219(sd);
1129 	int ret;
1130 
1131 	ret = regulator_bulk_enable(IMX219_NUM_SUPPLIES,
1132 				    imx219->supplies);
1133 	if (ret) {
1134 		dev_err(dev, "%s: failed to enable regulators\n",
1135 			__func__);
1136 		return ret;
1137 	}
1138 
1139 	ret = clk_prepare_enable(imx219->xclk);
1140 	if (ret) {
1141 		dev_err(dev, "%s: failed to enable clock\n",
1142 			__func__);
1143 		goto reg_off;
1144 	}
1145 
1146 	gpiod_set_value_cansleep(imx219->reset_gpio, 1);
1147 	usleep_range(IMX219_XCLR_MIN_DELAY_US,
1148 		     IMX219_XCLR_MIN_DELAY_US + IMX219_XCLR_DELAY_RANGE_US);
1149 
1150 	return 0;
1151 
1152 reg_off:
1153 	regulator_bulk_disable(IMX219_NUM_SUPPLIES, imx219->supplies);
1154 
1155 	return ret;
1156 }
1157 
1158 static int imx219_power_off(struct device *dev)
1159 {
1160 	struct v4l2_subdev *sd = dev_get_drvdata(dev);
1161 	struct imx219 *imx219 = to_imx219(sd);
1162 
1163 	gpiod_set_value_cansleep(imx219->reset_gpio, 0);
1164 	regulator_bulk_disable(IMX219_NUM_SUPPLIES, imx219->supplies);
1165 	clk_disable_unprepare(imx219->xclk);
1166 
1167 	return 0;
1168 }
1169 
1170 static int __maybe_unused imx219_suspend(struct device *dev)
1171 {
1172 	struct v4l2_subdev *sd = dev_get_drvdata(dev);
1173 	struct imx219 *imx219 = to_imx219(sd);
1174 
1175 	if (imx219->streaming)
1176 		imx219_stop_streaming(imx219);
1177 
1178 	return 0;
1179 }
1180 
1181 static int __maybe_unused imx219_resume(struct device *dev)
1182 {
1183 	struct v4l2_subdev *sd = dev_get_drvdata(dev);
1184 	struct imx219 *imx219 = to_imx219(sd);
1185 	int ret;
1186 
1187 	if (imx219->streaming) {
1188 		ret = imx219_start_streaming(imx219);
1189 		if (ret)
1190 			goto error;
1191 	}
1192 
1193 	return 0;
1194 
1195 error:
1196 	imx219_stop_streaming(imx219);
1197 	imx219->streaming = false;
1198 
1199 	return ret;
1200 }
1201 
1202 static int imx219_get_regulators(struct imx219 *imx219)
1203 {
1204 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
1205 	unsigned int i;
1206 
1207 	for (i = 0; i < IMX219_NUM_SUPPLIES; i++)
1208 		imx219->supplies[i].supply = imx219_supply_name[i];
1209 
1210 	return devm_regulator_bulk_get(&client->dev,
1211 				       IMX219_NUM_SUPPLIES,
1212 				       imx219->supplies);
1213 }
1214 
1215 /* Verify chip ID */
1216 static int imx219_identify_module(struct imx219 *imx219)
1217 {
1218 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
1219 	int ret;
1220 	u32 val;
1221 
1222 	ret = imx219_read_reg(imx219, IMX219_REG_CHIP_ID,
1223 			      IMX219_REG_VALUE_16BIT, &val);
1224 	if (ret) {
1225 		dev_err(&client->dev, "failed to read chip id %x\n",
1226 			IMX219_CHIP_ID);
1227 		return ret;
1228 	}
1229 
1230 	if (val != IMX219_CHIP_ID) {
1231 		dev_err(&client->dev, "chip id mismatch: %x!=%x\n",
1232 			IMX219_CHIP_ID, val);
1233 		return -EIO;
1234 	}
1235 
1236 	return 0;
1237 }
1238 
1239 static const struct v4l2_subdev_core_ops imx219_core_ops = {
1240 	.subscribe_event = v4l2_ctrl_subdev_subscribe_event,
1241 	.unsubscribe_event = v4l2_event_subdev_unsubscribe,
1242 };
1243 
1244 static const struct v4l2_subdev_video_ops imx219_video_ops = {
1245 	.s_stream = imx219_set_stream,
1246 };
1247 
1248 static const struct v4l2_subdev_pad_ops imx219_pad_ops = {
1249 	.enum_mbus_code = imx219_enum_mbus_code,
1250 	.get_fmt = imx219_get_pad_format,
1251 	.set_fmt = imx219_set_pad_format,
1252 	.get_selection = imx219_get_selection,
1253 	.enum_frame_size = imx219_enum_frame_size,
1254 };
1255 
1256 static const struct v4l2_subdev_ops imx219_subdev_ops = {
1257 	.core = &imx219_core_ops,
1258 	.video = &imx219_video_ops,
1259 	.pad = &imx219_pad_ops,
1260 };
1261 
1262 static const struct v4l2_subdev_internal_ops imx219_internal_ops = {
1263 	.open = imx219_open,
1264 };
1265 
1266 /* Initialize control handlers */
1267 static int imx219_init_controls(struct imx219 *imx219)
1268 {
1269 	struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
1270 	struct v4l2_ctrl_handler *ctrl_hdlr;
1271 	unsigned int height = imx219->mode->height;
1272 	struct v4l2_fwnode_device_properties props;
1273 	int exposure_max, exposure_def, hblank;
1274 	int i, ret;
1275 
1276 	ctrl_hdlr = &imx219->ctrl_handler;
1277 	ret = v4l2_ctrl_handler_init(ctrl_hdlr, 12);
1278 	if (ret)
1279 		return ret;
1280 
1281 	mutex_init(&imx219->mutex);
1282 	ctrl_hdlr->lock = &imx219->mutex;
1283 
1284 	/* By default, PIXEL_RATE is read only */
1285 	imx219->pixel_rate = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1286 					       V4L2_CID_PIXEL_RATE,
1287 					       IMX219_PIXEL_RATE,
1288 					       IMX219_PIXEL_RATE, 1,
1289 					       IMX219_PIXEL_RATE);
1290 
1291 	imx219->link_freq =
1292 		v4l2_ctrl_new_int_menu(ctrl_hdlr, &imx219_ctrl_ops,
1293 				       V4L2_CID_LINK_FREQ,
1294 				       ARRAY_SIZE(imx219_link_freq_menu) - 1, 0,
1295 				       imx219_link_freq_menu);
1296 	if (imx219->link_freq)
1297 		imx219->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY;
1298 
1299 	/* Initial vblank/hblank/exposure parameters based on current mode */
1300 	imx219->vblank = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1301 					   V4L2_CID_VBLANK, IMX219_VBLANK_MIN,
1302 					   IMX219_VTS_MAX - height, 1,
1303 					   imx219->mode->vts_def - height);
1304 	hblank = IMX219_PPL_DEFAULT - imx219->mode->width;
1305 	imx219->hblank = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1306 					   V4L2_CID_HBLANK, hblank, hblank,
1307 					   1, hblank);
1308 	if (imx219->hblank)
1309 		imx219->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY;
1310 	exposure_max = imx219->mode->vts_def - 4;
1311 	exposure_def = (exposure_max < IMX219_EXPOSURE_DEFAULT) ?
1312 		exposure_max : IMX219_EXPOSURE_DEFAULT;
1313 	imx219->exposure = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1314 					     V4L2_CID_EXPOSURE,
1315 					     IMX219_EXPOSURE_MIN, exposure_max,
1316 					     IMX219_EXPOSURE_STEP,
1317 					     exposure_def);
1318 
1319 	v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops, V4L2_CID_ANALOGUE_GAIN,
1320 			  IMX219_ANA_GAIN_MIN, IMX219_ANA_GAIN_MAX,
1321 			  IMX219_ANA_GAIN_STEP, IMX219_ANA_GAIN_DEFAULT);
1322 
1323 	v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops, V4L2_CID_DIGITAL_GAIN,
1324 			  IMX219_DGTL_GAIN_MIN, IMX219_DGTL_GAIN_MAX,
1325 			  IMX219_DGTL_GAIN_STEP, IMX219_DGTL_GAIN_DEFAULT);
1326 
1327 	imx219->hflip = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1328 					  V4L2_CID_HFLIP, 0, 1, 1, 0);
1329 	if (imx219->hflip)
1330 		imx219->hflip->flags |= V4L2_CTRL_FLAG_MODIFY_LAYOUT;
1331 
1332 	imx219->vflip = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1333 					  V4L2_CID_VFLIP, 0, 1, 1, 0);
1334 	if (imx219->vflip)
1335 		imx219->vflip->flags |= V4L2_CTRL_FLAG_MODIFY_LAYOUT;
1336 
1337 	v4l2_ctrl_new_std_menu_items(ctrl_hdlr, &imx219_ctrl_ops,
1338 				     V4L2_CID_TEST_PATTERN,
1339 				     ARRAY_SIZE(imx219_test_pattern_menu) - 1,
1340 				     0, 0, imx219_test_pattern_menu);
1341 	for (i = 0; i < 4; i++) {
1342 		/*
1343 		 * The assumption is that
1344 		 * V4L2_CID_TEST_PATTERN_GREENR == V4L2_CID_TEST_PATTERN_RED + 1
1345 		 * V4L2_CID_TEST_PATTERN_BLUE   == V4L2_CID_TEST_PATTERN_RED + 2
1346 		 * V4L2_CID_TEST_PATTERN_GREENB == V4L2_CID_TEST_PATTERN_RED + 3
1347 		 */
1348 		v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1349 				  V4L2_CID_TEST_PATTERN_RED + i,
1350 				  IMX219_TESTP_COLOUR_MIN,
1351 				  IMX219_TESTP_COLOUR_MAX,
1352 				  IMX219_TESTP_COLOUR_STEP,
1353 				  IMX219_TESTP_COLOUR_MAX);
1354 		/* The "Solid color" pattern is white by default */
1355 	}
1356 
1357 	if (ctrl_hdlr->error) {
1358 		ret = ctrl_hdlr->error;
1359 		dev_err(&client->dev, "%s control init failed (%d)\n",
1360 			__func__, ret);
1361 		goto error;
1362 	}
1363 
1364 	ret = v4l2_fwnode_device_parse(&client->dev, &props);
1365 	if (ret)
1366 		goto error;
1367 
1368 	ret = v4l2_ctrl_new_fwnode_properties(ctrl_hdlr, &imx219_ctrl_ops,
1369 					      &props);
1370 	if (ret)
1371 		goto error;
1372 
1373 	imx219->sd.ctrl_handler = ctrl_hdlr;
1374 
1375 	return 0;
1376 
1377 error:
1378 	v4l2_ctrl_handler_free(ctrl_hdlr);
1379 	mutex_destroy(&imx219->mutex);
1380 
1381 	return ret;
1382 }
1383 
1384 static void imx219_free_controls(struct imx219 *imx219)
1385 {
1386 	v4l2_ctrl_handler_free(imx219->sd.ctrl_handler);
1387 	mutex_destroy(&imx219->mutex);
1388 }
1389 
1390 static int imx219_check_hwcfg(struct device *dev)
1391 {
1392 	struct fwnode_handle *endpoint;
1393 	struct v4l2_fwnode_endpoint ep_cfg = {
1394 		.bus_type = V4L2_MBUS_CSI2_DPHY
1395 	};
1396 	int ret = -EINVAL;
1397 
1398 	endpoint = fwnode_graph_get_next_endpoint(dev_fwnode(dev), NULL);
1399 	if (!endpoint) {
1400 		dev_err(dev, "endpoint node not found\n");
1401 		return -EINVAL;
1402 	}
1403 
1404 	if (v4l2_fwnode_endpoint_alloc_parse(endpoint, &ep_cfg)) {
1405 		dev_err(dev, "could not parse endpoint\n");
1406 		goto error_out;
1407 	}
1408 
1409 	/* Check the number of MIPI CSI2 data lanes */
1410 	if (ep_cfg.bus.mipi_csi2.num_data_lanes != 2) {
1411 		dev_err(dev, "only 2 data lanes are currently supported\n");
1412 		goto error_out;
1413 	}
1414 
1415 	/* Check the link frequency set in device tree */
1416 	if (!ep_cfg.nr_of_link_frequencies) {
1417 		dev_err(dev, "link-frequency property not found in DT\n");
1418 		goto error_out;
1419 	}
1420 
1421 	if (ep_cfg.nr_of_link_frequencies != 1 ||
1422 	    ep_cfg.link_frequencies[0] != IMX219_DEFAULT_LINK_FREQ) {
1423 		dev_err(dev, "Link frequency not supported: %lld\n",
1424 			ep_cfg.link_frequencies[0]);
1425 		goto error_out;
1426 	}
1427 
1428 	ret = 0;
1429 
1430 error_out:
1431 	v4l2_fwnode_endpoint_free(&ep_cfg);
1432 	fwnode_handle_put(endpoint);
1433 
1434 	return ret;
1435 }
1436 
1437 static int imx219_probe(struct i2c_client *client)
1438 {
1439 	struct device *dev = &client->dev;
1440 	struct imx219 *imx219;
1441 	int ret;
1442 
1443 	imx219 = devm_kzalloc(&client->dev, sizeof(*imx219), GFP_KERNEL);
1444 	if (!imx219)
1445 		return -ENOMEM;
1446 
1447 	v4l2_i2c_subdev_init(&imx219->sd, client, &imx219_subdev_ops);
1448 
1449 	/* Check the hardware configuration in device tree */
1450 	if (imx219_check_hwcfg(dev))
1451 		return -EINVAL;
1452 
1453 	/* Get system clock (xclk) */
1454 	imx219->xclk = devm_clk_get(dev, NULL);
1455 	if (IS_ERR(imx219->xclk)) {
1456 		dev_err(dev, "failed to get xclk\n");
1457 		return PTR_ERR(imx219->xclk);
1458 	}
1459 
1460 	imx219->xclk_freq = clk_get_rate(imx219->xclk);
1461 	if (imx219->xclk_freq != IMX219_XCLK_FREQ) {
1462 		dev_err(dev, "xclk frequency not supported: %d Hz\n",
1463 			imx219->xclk_freq);
1464 		return -EINVAL;
1465 	}
1466 
1467 	ret = imx219_get_regulators(imx219);
1468 	if (ret) {
1469 		dev_err(dev, "failed to get regulators\n");
1470 		return ret;
1471 	}
1472 
1473 	/* Request optional enable pin */
1474 	imx219->reset_gpio = devm_gpiod_get_optional(dev, "reset",
1475 						     GPIOD_OUT_HIGH);
1476 
1477 	/*
1478 	 * The sensor must be powered for imx219_identify_module()
1479 	 * to be able to read the CHIP_ID register
1480 	 */
1481 	ret = imx219_power_on(dev);
1482 	if (ret)
1483 		return ret;
1484 
1485 	ret = imx219_identify_module(imx219);
1486 	if (ret)
1487 		goto error_power_off;
1488 
1489 	/* Set default mode to max resolution */
1490 	imx219->mode = &supported_modes[0];
1491 
1492 	/* sensor doesn't enter LP-11 state upon power up until and unless
1493 	 * streaming is started, so upon power up switch the modes to:
1494 	 * streaming -> standby
1495 	 */
1496 	ret = imx219_write_reg(imx219, IMX219_REG_MODE_SELECT,
1497 			       IMX219_REG_VALUE_08BIT, IMX219_MODE_STREAMING);
1498 	if (ret < 0)
1499 		goto error_power_off;
1500 	usleep_range(100, 110);
1501 
1502 	/* put sensor back to standby mode */
1503 	ret = imx219_write_reg(imx219, IMX219_REG_MODE_SELECT,
1504 			       IMX219_REG_VALUE_08BIT, IMX219_MODE_STANDBY);
1505 	if (ret < 0)
1506 		goto error_power_off;
1507 	usleep_range(100, 110);
1508 
1509 	ret = imx219_init_controls(imx219);
1510 	if (ret)
1511 		goto error_power_off;
1512 
1513 	/* Initialize subdev */
1514 	imx219->sd.internal_ops = &imx219_internal_ops;
1515 	imx219->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE |
1516 			    V4L2_SUBDEV_FL_HAS_EVENTS;
1517 	imx219->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR;
1518 
1519 	/* Initialize source pad */
1520 	imx219->pad.flags = MEDIA_PAD_FL_SOURCE;
1521 
1522 	/* Initialize default format */
1523 	imx219_set_default_format(imx219);
1524 
1525 	ret = media_entity_pads_init(&imx219->sd.entity, 1, &imx219->pad);
1526 	if (ret) {
1527 		dev_err(dev, "failed to init entity pads: %d\n", ret);
1528 		goto error_handler_free;
1529 	}
1530 
1531 	ret = v4l2_async_register_subdev_sensor_common(&imx219->sd);
1532 	if (ret < 0) {
1533 		dev_err(dev, "failed to register sensor sub-device: %d\n", ret);
1534 		goto error_media_entity;
1535 	}
1536 
1537 	/* Enable runtime PM and turn off the device */
1538 	pm_runtime_set_active(dev);
1539 	pm_runtime_enable(dev);
1540 	pm_runtime_idle(dev);
1541 
1542 	return 0;
1543 
1544 error_media_entity:
1545 	media_entity_cleanup(&imx219->sd.entity);
1546 
1547 error_handler_free:
1548 	imx219_free_controls(imx219);
1549 
1550 error_power_off:
1551 	imx219_power_off(dev);
1552 
1553 	return ret;
1554 }
1555 
1556 static int imx219_remove(struct i2c_client *client)
1557 {
1558 	struct v4l2_subdev *sd = i2c_get_clientdata(client);
1559 	struct imx219 *imx219 = to_imx219(sd);
1560 
1561 	v4l2_async_unregister_subdev(sd);
1562 	media_entity_cleanup(&sd->entity);
1563 	imx219_free_controls(imx219);
1564 
1565 	pm_runtime_disable(&client->dev);
1566 	if (!pm_runtime_status_suspended(&client->dev))
1567 		imx219_power_off(&client->dev);
1568 	pm_runtime_set_suspended(&client->dev);
1569 
1570 	return 0;
1571 }
1572 
1573 static const struct of_device_id imx219_dt_ids[] = {
1574 	{ .compatible = "sony,imx219" },
1575 	{ /* sentinel */ }
1576 };
1577 MODULE_DEVICE_TABLE(of, imx219_dt_ids);
1578 
1579 static const struct dev_pm_ops imx219_pm_ops = {
1580 	SET_SYSTEM_SLEEP_PM_OPS(imx219_suspend, imx219_resume)
1581 	SET_RUNTIME_PM_OPS(imx219_power_off, imx219_power_on, NULL)
1582 };
1583 
1584 static struct i2c_driver imx219_i2c_driver = {
1585 	.driver = {
1586 		.name = "imx219",
1587 		.of_match_table	= imx219_dt_ids,
1588 		.pm = &imx219_pm_ops,
1589 	},
1590 	.probe_new = imx219_probe,
1591 	.remove = imx219_remove,
1592 };
1593 
1594 module_i2c_driver(imx219_i2c_driver);
1595 
1596 MODULE_AUTHOR("Dave Stevenson <dave.stevenson@raspberrypi.com");
1597 MODULE_DESCRIPTION("Sony IMX219 sensor driver");
1598 MODULE_LICENSE("GPL v2");
1599