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