xref: /linux/drivers/media/i2c/thp7312.c (revision 98b3cd0bfc5c07809166421e8b8f82bf74ee8970)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2021 THine Electronics, Inc.
4  * Copyright (C) 2023 Ideas on Board Oy
5  */
6 
7 #include <asm/unaligned.h>
8 
9 #include <linux/clk.h>
10 #include <linux/delay.h>
11 #include <linux/device.h>
12 #include <linux/firmware.h>
13 #include <linux/gpio/consumer.h>
14 #include <linux/i2c.h>
15 #include <linux/init.h>
16 #include <linux/iopoll.h>
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/mtd/spi-nor.h>
20 #include <linux/pm_runtime.h>
21 #include <linux/property.h>
22 #include <linux/regulator/consumer.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
25 
26 #include <media/v4l2-async.h>
27 #include <media/v4l2-cci.h>
28 #include <media/v4l2-ctrls.h>
29 #include <media/v4l2-device.h>
30 #include <media/v4l2-event.h>
31 #include <media/v4l2-fwnode.h>
32 #include <media/v4l2-subdev.h>
33 
34 #include <uapi/linux/thp7312.h>
35 
36 /* ISP registers */
37 
38 #define THP7312_REG_FIRMWARE_VERSION_1			CCI_REG8(0xf000)
39 #define THP7312_REG_CAMERA_STATUS			CCI_REG8(0xf001)
40 #define THP7312_REG_FIRMWARE_VERSION_2			CCI_REG8(0xf005)
41 #define THP7312_REG_SET_OUTPUT_ENABLE			CCI_REG8(0xf008)
42 #define THP7312_OUTPUT_ENABLE				0x01
43 #define THP7312_OUTPUT_DISABLE				0x00
44 #define THP7312_REG_SET_OUTPUT_COLOR_COMPRESSION	CCI_REG8(0xf009)
45 #define THP7312_REG_SET_OUTPUT_COLOR_UYVY		0x00
46 #define THP7312_REG_SET_OUTPUT_COLOR_YUY2		0x04
47 #define THP7312_REG_FLIP_MIRROR				CCI_REG8(0xf00c)
48 #define THP7312_REG_FLIP_MIRROR_FLIP			BIT(0)
49 #define THP7312_REG_FLIP_MIRROR_MIRROR			BIT(1)
50 #define THP7312_REG_VIDEO_IMAGE_SIZE			CCI_REG8(0xf00d)
51 #define THP7312_VIDEO_IMAGE_SIZE_640x360		0x52
52 #define THP7312_VIDEO_IMAGE_SIZE_640x460		0x03
53 #define THP7312_VIDEO_IMAGE_SIZE_1280x720		0x0a
54 #define THP7312_VIDEO_IMAGE_SIZE_1920x1080		0x0b
55 #define THP7312_VIDEO_IMAGE_SIZE_3840x2160		0x0d
56 #define THP7312_VIDEO_IMAGE_SIZE_4160x3120		0x14
57 #define THP7312_VIDEO_IMAGE_SIZE_2016x1512		0x20
58 #define THP7312_VIDEO_IMAGE_SIZE_2048x1536		0x21
59 #define THP7312_REG_VIDEO_FRAME_RATE_MODE		CCI_REG8(0xf00f)
60 #define THP7312_VIDEO_FRAME_RATE_MODE1			0x80
61 #define THP7312_VIDEO_FRAME_RATE_MODE2			0x81
62 #define THP7312_VIDEO_FRAME_RATE_MODE3			0x82
63 #define THP7312_REG_SET_DRIVING_MODE			CCI_REG8(0xf010)
64 #define THP7312_REG_DRIVING_MODE_STATUS			CCI_REG8(0xf011)
65 #define THP7312_REG_JPEG_COMPRESSION_FACTOR		CCI_REG8(0xf01b)
66 #define THP7312_REG_AE_EXPOSURE_COMPENSATION		CCI_REG8(0xf022)
67 #define THP7312_REG_AE_FLICKER_MODE			CCI_REG8(0xf023)
68 #define THP7312_AE_FLICKER_MODE_50			0x00
69 #define THP7312_AE_FLICKER_MODE_60			0x01
70 #define THP7312_AE_FLICKER_MODE_DISABLE			0x80
71 #define THP7312_REG_AE_FIX_FRAME_RATE			CCI_REG8(0xf02e)
72 #define THP7312_REG_MANUAL_WB_RED_GAIN			CCI_REG8(0xf036)
73 #define THP7312_REG_MANUAL_WB_BLUE_GAIN			CCI_REG8(0xf037)
74 #define THP7312_REG_WB_MODE				CCI_REG8(0xf039)
75 #define THP7312_WB_MODE_AUTO				0x00
76 #define THP7312_WB_MODE_MANUAL				0x11
77 #define THP7312_REG_MANUAL_FOCUS_POSITION		CCI_REG16(0xf03c)
78 #define THP7312_REG_AF_CONTROL				CCI_REG8(0xf040)
79 #define THP7312_REG_AF_CONTROL_AF			0x01
80 #define THP7312_REG_AF_CONTROL_MANUAL			0x10
81 #define THP7312_REG_AF_CONTROL_LOCK			0x80
82 #define THP7312_REG_AF_SETTING				CCI_REG8(0xf041)
83 #define THP7312_REG_AF_SETTING_ONESHOT_CONTRAST		0x00
84 #define THP7312_REG_AF_SETTING_ONESHOT_PDAF		0x40
85 #define THP7312_REG_AF_SETTING_ONESHOT_HYBRID		0x80
86 #define THP7312_REG_AF_SETTING_CONTINUOUS_CONTRAST	0x30
87 #define THP7312_REG_AF_SETTING_CONTINUOUS_PDAF		0x70
88 #define THP7312_REG_AF_SETTING_CONTINUOUS_HYBRID	0xf0
89 #define THP7312_REG_AF_SUPPORT				CCI_REG8(0xf043)
90 #define THP7312_AF_SUPPORT_PDAF				BIT(1)
91 #define THP7312_AF_SUPPORT_CONTRAST			BIT(0)
92 #define THP7312_REG_SATURATION				CCI_REG8(0xf052)
93 #define THP7312_REG_SHARPNESS				CCI_REG8(0xf053)
94 #define THP7312_REG_BRIGHTNESS				CCI_REG8(0xf056)
95 #define THP7312_REG_CONTRAST				CCI_REG8(0xf057)
96 #define THP7312_REG_NOISE_REDUCTION			CCI_REG8(0xf059)
97 #define THP7312_REG_NOISE_REDUCTION_FIXED		BIT(7)
98 
99 #define TH7312_REG_CUSTOM_MIPI_SET			CCI_REG8(0xf0f6)
100 #define TH7312_REG_CUSTOM_MIPI_STATUS			CCI_REG8(0xf0f7)
101 #define TH7312_REG_CUSTOM_MIPI_RD			CCI_REG8(0xf0f8)
102 #define TH7312_REG_CUSTOM_MIPI_TD			CCI_REG8(0xf0f9)
103 
104 /*
105  * Firmware update registers. Those use a different address space than the
106  * normal operation ISP registers.
107  */
108 
109 #define THP7312_REG_FW_DRIVABILITY			CCI_REG32(0xd65c)
110 #define THP7312_REG_FW_DEST_BANK_ADDR			CCI_REG32(0xff08)
111 #define THP7312_REG_FW_VERIFY_RESULT			CCI_REG8(0xff60)
112 #define THP7312_REG_FW_RESET_FLASH			CCI_REG8(0xff61)
113 #define THP7312_REG_FW_MEMORY_IO_SETTING		CCI_REG8(0xff62)
114 #define THP7312_FW_MEMORY_IO_GPIO0			1
115 #define THP7312_FW_MEMORY_IO_GPIO1			0
116 #define THP7312_REG_FW_CRC_RESULT			CCI_REG32(0xff64)
117 #define THP7312_REG_FW_STATUS				CCI_REG8(0xfffc)
118 
119 #define THP7312_FW_VERSION(major, minor)		(((major) << 8) | (minor))
120 #define THP7312_FW_VERSION_MAJOR(v)			((v) >> 8)
121 #define THP7312_FW_VERSION_MINOR(v)			((v) & 0xff)
122 
123 enum thp7312_focus_method {
124 	THP7312_FOCUS_METHOD_CONTRAST,
125 	THP7312_FOCUS_METHOD_PDAF,
126 	THP7312_FOCUS_METHOD_HYBRID,
127 };
128 
129 /*
130  * enum thp7312_focus_state - State of the focus handler
131  *
132  * @THP7312_FOCUS_STATE_MANUAL: Manual focus, controlled through the
133  *	V4L2_CID_FOCUS_ABSOLUTE control
134  * @THP7312_FOCUS_STATE_AUTO: Continuous auto-focus
135  * @THP7312_FOCUS_STATE_LOCKED: Lock the focus to a fixed position. This state
136  *	is entered when switching from auto to manual mode.
137  * @THP7312_FOCUS_STATE_ONESHOT: One-shot auto-focus
138  *
139  * Valid transitions are as follow:
140  *
141  * digraph fsm {
142  *         node [shape=circle];
143  *
144  *         manual [label="MANUAL"];
145  *         auto [label="AUTO"];
146  *         locked [label="LOCKED"];
147  *         oneshot [label="ONESHOT"];
148  *
149  *         manual -> auto [label="FOCUS_AUTO <- true"]
150  *         locked -> auto [label="FOCUS_AUTO <- true"]
151  *         oneshot -> auto [label="FOCUS_AUTO <- true"]
152  *         auto -> locked [label="FOCUS_AUTO <- false"]
153  *
154  *         locked -> manual [label="FOCUS_ABSOLUTE <- *"]
155  *         oneshot -> manual [label="FOCUS_ABSOLUTE <- *"]
156  *
157  *         manual -> oneshot [label="FOCUS_START <- *"]
158  *         locked -> oneshot [label="FOCUS_START <- *"]
159  * }
160  */
161 enum thp7312_focus_state {
162 	THP7312_FOCUS_STATE_MANUAL,
163 	THP7312_FOCUS_STATE_AUTO,
164 	THP7312_FOCUS_STATE_LOCKED,
165 	THP7312_FOCUS_STATE_ONESHOT,
166 };
167 
168 enum thp7312_boot_mode {
169 	THP7312_BOOT_MODE_2WIRE_SLAVE = 0,
170 	THP7312_BOOT_MODE_SPI_MASTER = 1,
171 };
172 
173 struct thp7312_frame_rate {
174 	u32 fps;
175 	u32 link_freq;
176 	u8 reg_frame_rate_mode;
177 };
178 
179 struct thp7312_mode_info {
180 	u32 width;
181 	u32 height;
182 	u8 reg_image_size;
183 	const struct thp7312_frame_rate *rates;
184 };
185 
186 static const u32 thp7312_colour_fmts[] = {
187 	MEDIA_BUS_FMT_YUYV8_1X16,
188 };
189 
190 /* regulator supplies */
191 static const char * const thp7312_supply_name[] = {
192 	"vddcore",
193 	"vhtermrx",
194 	"vddtx",
195 	"vddhost",
196 	"vddcmos",
197 	"vddgpio-0",
198 	"vddgpio-1",
199 };
200 
201 static const struct thp7312_mode_info thp7312_mode_info_data[] = {
202 	{
203 		.width = 1920,
204 		.height = 1080,
205 		.reg_image_size = THP7312_VIDEO_IMAGE_SIZE_1920x1080,
206 		.rates = (const struct thp7312_frame_rate[]) {
207 			{ 30, 300000000, 0x81 },
208 			{ 60, 387500000, 0x82 },
209 			{ 0 }
210 		},
211 	}, {
212 		.width = 2048,
213 		.height = 1536,
214 		.reg_image_size = THP7312_VIDEO_IMAGE_SIZE_2048x1536,
215 		.rates = (const struct thp7312_frame_rate[]) {
216 			{ 30, 300000000, 0x81 },
217 			{ 0 }
218 		}
219 	}, {
220 		.width = 3840,
221 		.height = 2160,
222 		.reg_image_size = THP7312_VIDEO_IMAGE_SIZE_3840x2160,
223 		.rates = (const struct thp7312_frame_rate[]) {
224 			{ 30, 600000000, 0x81 },
225 			{ 0 }
226 		},
227 	}, {
228 		.width = 4160,
229 		.height = 3120,
230 		.reg_image_size = THP7312_VIDEO_IMAGE_SIZE_4160x3120,
231 		.rates = (const struct thp7312_frame_rate[]) {
232 			{ 20, 600000000, 0x81 },
233 			{ 0 }
234 		},
235 	},
236 };
237 
238 struct thp7312_device;
239 
240 struct thp7312_sensor_info {
241 	const char *model;
242 };
243 
244 struct thp7312_sensor {
245 	const struct thp7312_sensor_info *info;
246 	u8 lane_remap;
247 };
248 
249 struct thp7312_device {
250 	struct device *dev;
251 	struct regmap *regmap;
252 
253 	struct v4l2_subdev sd;
254 	struct media_pad pad;
255 
256 	struct gpio_desc *reset_gpio;
257 	struct regulator_bulk_data supplies[ARRAY_SIZE(thp7312_supply_name)];
258 	struct clk *iclk;
259 
260 	u8 lane_remap;
261 
262 	struct thp7312_sensor sensors[1];
263 
264 	enum thp7312_boot_mode boot_mode;
265 
266 	struct v4l2_ctrl_handler ctrl_handler;
267 	bool ctrls_applied;
268 
269 	/* These are protected by v4l2 active state */
270 	const struct thp7312_mode_info *current_mode;
271 	const struct thp7312_frame_rate *current_rate;
272 	s64 link_freq;
273 
274 	struct {
275 		struct v4l2_ctrl *hflip;
276 		struct v4l2_ctrl *vflip;
277 	};
278 
279 	struct {
280 		struct v4l2_ctrl *focus_auto;
281 		struct v4l2_ctrl *focus_absolute;
282 		struct v4l2_ctrl *focus_start;
283 		struct v4l2_ctrl *focus_method;
284 	};
285 
286 	enum thp7312_focus_state focus_state;
287 
288 	struct {
289 		struct v4l2_ctrl *noise_reduction_auto;
290 		struct v4l2_ctrl *noise_reduction_absolute;
291 	};
292 
293 	/* Lock to protect fw_cancel */
294 	struct mutex fw_lock;
295 	struct fw_upload *fwl;
296 	u8 *fw_write_buf;
297 	bool fw_cancel;
298 
299 	u16 fw_version;
300 };
301 
302 static const struct thp7312_sensor_info thp7312_sensor_info[] = {
303 	{
304 		.model = "sony,imx258",
305 	},
306 };
307 
308 static inline struct thp7312_device *to_thp7312_dev(struct v4l2_subdev *sd)
309 {
310 	return container_of(sd, struct thp7312_device, sd);
311 }
312 
313 /* -----------------------------------------------------------------------------
314  * Device Access & Configuration
315  */
316 
317 #define thp7312_read_poll_timeout(dev, addr, val, cond, sleep_us, timeout_us) \
318 ({ \
319 	int __ret, __err; \
320 	__ret = read_poll_timeout(cci_read, __err, __err || (cond), sleep_us, \
321 				  timeout_us, false, (dev)->regmap, addr, \
322 				  &(val), NULL); \
323 	__ret ? : __err; \
324 })
325 
326 static int thp7312_map_data_lanes(u8 *lane_remap, const u8 *lanes, u8 num_lanes)
327 {
328 	u8 used_lanes = 0;
329 	u8 val = 0;
330 	unsigned int i;
331 
332 	/*
333 	 * The value that we write to the register is the index in the
334 	 * data-lanes array, so we need to do a conversion. Do this in the same
335 	 * pass as validating data-lanes.
336 	 */
337 	for (i = 0; i < num_lanes; i++) {
338 		if (lanes[i] < 1 || lanes[i] > 4)
339 			return -EINVAL;
340 
341 		if (used_lanes & (BIT(lanes[i])))
342 			return -EINVAL;
343 
344 		used_lanes |= BIT(lanes[i]);
345 
346 		/*
347 		 * data-lanes is 1-indexed while the field position in the
348 		 * register is 0-indexed.
349 		 */
350 		val |= i << ((lanes[i] - 1) * 2);
351 	}
352 
353 	*lane_remap = val;
354 
355 	return 0;
356 }
357 
358 static int thp7312_set_mipi_lanes(struct thp7312_device *thp7312)
359 {
360 	struct device *dev = thp7312->dev;
361 	int ret = 0;
362 	u64 val;
363 
364 	cci_write(thp7312->regmap, TH7312_REG_CUSTOM_MIPI_RD,
365 		  thp7312->sensors[0].lane_remap, &ret);
366 	cci_write(thp7312->regmap, TH7312_REG_CUSTOM_MIPI_TD,
367 		  thp7312->lane_remap, &ret);
368 	cci_write(thp7312->regmap, TH7312_REG_CUSTOM_MIPI_SET, 1, &ret);
369 
370 	if (ret)
371 		return ret;
372 
373 	ret = thp7312_read_poll_timeout(thp7312, TH7312_REG_CUSTOM_MIPI_STATUS,
374 					val, val == 0x00, 100000, 2000000);
375 	if (ret) {
376 		dev_err(dev, "Failed to poll MIPI lane status: %d\n", ret);
377 		return ret;
378 	}
379 
380 	return 0;
381 }
382 
383 static int thp7312_change_mode(struct thp7312_device *thp7312,
384 			       const struct thp7312_mode_info *mode,
385 			       const struct thp7312_frame_rate *rate)
386 {
387 	struct device *dev = thp7312->dev;
388 	u64 val = 0;
389 	int ret;
390 
391 	ret = thp7312_read_poll_timeout(thp7312, THP7312_REG_CAMERA_STATUS, val,
392 					val == 0x80, 20000, 200000);
393 	if (ret < 0) {
394 		dev_err(dev, "%s(): failed to poll ISP: %d\n", __func__, ret);
395 		return ret;
396 	}
397 
398 	cci_write(thp7312->regmap, THP7312_REG_VIDEO_IMAGE_SIZE,
399 		  mode->reg_image_size, &ret);
400 	cci_write(thp7312->regmap, THP7312_REG_VIDEO_FRAME_RATE_MODE,
401 		  rate->reg_frame_rate_mode, &ret);
402 	cci_write(thp7312->regmap, THP7312_REG_JPEG_COMPRESSION_FACTOR, 0x5e,
403 		  &ret);
404 	cci_write(thp7312->regmap, THP7312_REG_SET_DRIVING_MODE, 0x01, &ret);
405 
406 	if (ret)
407 		return ret;
408 
409 	ret = thp7312_read_poll_timeout(thp7312, THP7312_REG_DRIVING_MODE_STATUS,
410 					val, val == 0x01, 20000, 100000);
411 	if (ret < 0) {
412 		dev_err(dev, "%s(): failed\n", __func__);
413 		return ret;
414 	}
415 
416 	return 0;
417 }
418 
419 static int thp7312_set_framefmt(struct thp7312_device *thp7312,
420 				struct v4l2_mbus_framefmt *format)
421 {
422 	u8 val;
423 
424 	switch (format->code) {
425 	case MEDIA_BUS_FMT_UYVY8_1X16:
426 		/* YUV422, UYVY */
427 		val = THP7312_REG_SET_OUTPUT_COLOR_UYVY;
428 		break;
429 	case MEDIA_BUS_FMT_YUYV8_1X16:
430 		/* YUV422, YUYV */
431 		val = THP7312_REG_SET_OUTPUT_COLOR_YUY2;
432 		break;
433 	default:
434 		/* Should never happen */
435 		return -EINVAL;
436 	}
437 
438 	return cci_write(thp7312->regmap,
439 			 THP7312_REG_SET_OUTPUT_COLOR_COMPRESSION, val, NULL);
440 }
441 
442 static int thp7312_init_mode(struct thp7312_device *thp7312,
443 			     struct v4l2_subdev_state *sd_state)
444 {
445 	struct v4l2_mbus_framefmt *fmt;
446 	int ret;
447 
448 	fmt = v4l2_subdev_state_get_format(sd_state, 0);
449 
450 	ret = thp7312_set_framefmt(thp7312, fmt);
451 	if (ret)
452 		return ret;
453 
454 	return thp7312_change_mode(thp7312, thp7312->current_mode,
455 				   thp7312->current_rate);
456 }
457 
458 static int thp7312_stream_enable(struct thp7312_device *thp7312, bool enable)
459 {
460 	return cci_write(thp7312->regmap, THP7312_REG_SET_OUTPUT_ENABLE,
461 			 enable ? THP7312_OUTPUT_ENABLE : THP7312_OUTPUT_DISABLE,
462 			 NULL);
463 }
464 
465 static int thp7312_check_status_stream_mode(struct thp7312_device *thp7312)
466 {
467 	struct device *dev = thp7312->dev;
468 	u64 status = 0;
469 	int ret;
470 
471 	while (status != 0x80) {
472 		ret = cci_read(thp7312->regmap, THP7312_REG_CAMERA_STATUS,
473 			       &status, NULL);
474 		if (ret)
475 			return ret;
476 
477 		if (status == 0x80) {
478 			dev_dbg(dev, "Camera initialization done\n");
479 			return 0;
480 		}
481 
482 		if (status != 0x00) {
483 			dev_err(dev, "Invalid camera status %llx\n", status);
484 			return -EINVAL;
485 		}
486 
487 		dev_dbg(dev, "Camera initializing...\n");
488 		usleep_range(70000, 80000);
489 	}
490 
491 	return 0;
492 }
493 
494 static void thp7312_reset(struct thp7312_device *thp7312)
495 {
496 	unsigned long rate;
497 
498 	gpiod_set_value_cansleep(thp7312->reset_gpio, 1);
499 
500 	/*
501 	 * The minimum reset duration is 8 clock cycles, make it 10 to provide
502 	 * a safety margin.
503 	 */
504 	rate = clk_get_rate(thp7312->iclk);
505 	fsleep(DIV_ROUND_UP(10 * USEC_PER_SEC, rate));
506 
507 	gpiod_set_value_cansleep(thp7312->reset_gpio, 0);
508 
509 	/*
510 	 * TODO: The documentation states that the device needs 2ms to
511 	 * initialize after reset is deasserted. It then proceeds to load the
512 	 * firmware from the flash memory, which takes an unspecified amount of
513 	 * time. Check if this delay could be reduced.
514 	 */
515 	fsleep(300000);
516 }
517 
518 /* -----------------------------------------------------------------------------
519  * Power Management
520  */
521 
522 static void __thp7312_power_off(struct thp7312_device *thp7312)
523 {
524 	regulator_bulk_disable(ARRAY_SIZE(thp7312->supplies), thp7312->supplies);
525 	clk_disable_unprepare(thp7312->iclk);
526 }
527 
528 static void thp7312_power_off(struct thp7312_device *thp7312)
529 {
530 	__thp7312_power_off(thp7312);
531 }
532 
533 static int __thp7312_power_on(struct thp7312_device *thp7312)
534 {
535 	struct device *dev = thp7312->dev;
536 	int ret;
537 
538 	ret = regulator_bulk_enable(ARRAY_SIZE(thp7312->supplies),
539 				    thp7312->supplies);
540 	if (ret < 0)
541 		return ret;
542 
543 	ret = clk_prepare_enable(thp7312->iclk);
544 	if (ret < 0) {
545 		dev_err(dev, "clk prepare enable failed\n");
546 		regulator_bulk_disable(ARRAY_SIZE(thp7312->supplies),
547 				       thp7312->supplies);
548 		return ret;
549 	}
550 
551 	/*
552 	 * We cannot assume that turning off and on again will reset, so do a
553 	 * software reset on power up.
554 	 */
555 	thp7312_reset(thp7312);
556 
557 	return 0;
558 }
559 
560 static int thp7312_power_on(struct thp7312_device *thp7312)
561 {
562 	int ret;
563 
564 	ret = __thp7312_power_on(thp7312);
565 	if (ret < 0)
566 		return ret;
567 
568 	ret = thp7312_check_status_stream_mode(thp7312);
569 	if (ret < 0)
570 		goto error;
571 
572 	ret = thp7312_set_mipi_lanes(thp7312);
573 	if (ret)
574 		goto error;
575 
576 	return 0;
577 
578 error:
579 	thp7312_power_off(thp7312);
580 	return ret;
581 }
582 
583 static int __maybe_unused thp7312_pm_runtime_suspend(struct device *dev)
584 {
585 	struct v4l2_subdev *sd = dev_get_drvdata(dev);
586 	struct thp7312_device *thp7312 = to_thp7312_dev(sd);
587 
588 	thp7312_power_off(thp7312);
589 
590 	thp7312->ctrls_applied = false;
591 
592 	return 0;
593 }
594 
595 static int __maybe_unused thp7312_pm_runtime_resume(struct device *dev)
596 {
597 	struct v4l2_subdev *sd = dev_get_drvdata(dev);
598 	struct thp7312_device *thp7312 = to_thp7312_dev(sd);
599 
600 	return thp7312_power_on(thp7312);
601 }
602 
603 static const struct dev_pm_ops thp7312_pm_ops = {
604 	SET_RUNTIME_PM_OPS(thp7312_pm_runtime_suspend,
605 			   thp7312_pm_runtime_resume, NULL)
606 };
607 
608 /* -----------------------------------------------------------------------------
609  * V4L2 Subdev Operations
610  */
611 
612 static bool thp7312_find_bus_code(u32 code)
613 {
614 	unsigned int i;
615 
616 	for (i = 0; i < ARRAY_SIZE(thp7312_colour_fmts); ++i) {
617 		if (thp7312_colour_fmts[i] == code)
618 			return true;
619 	}
620 
621 	return false;
622 }
623 
624 static const struct thp7312_mode_info *
625 thp7312_find_mode(unsigned int width, unsigned int height, bool nearest)
626 {
627 	const struct thp7312_mode_info *mode;
628 
629 	mode = v4l2_find_nearest_size(thp7312_mode_info_data,
630 				      ARRAY_SIZE(thp7312_mode_info_data),
631 				      width, height, width, height);
632 
633 	if (!nearest && (mode->width != width || mode->height != height))
634 		return NULL;
635 
636 	return mode;
637 }
638 
639 static void thp7312_set_frame_rate(struct thp7312_device *thp7312,
640 				   const struct thp7312_frame_rate *rate)
641 {
642 	thp7312->link_freq = rate->link_freq;
643 	thp7312->current_rate = rate;
644 }
645 
646 static int thp7312_enum_mbus_code(struct v4l2_subdev *sd,
647 				  struct v4l2_subdev_state *sd_state,
648 				  struct v4l2_subdev_mbus_code_enum *code)
649 {
650 	if (code->index >= ARRAY_SIZE(thp7312_colour_fmts))
651 		return -EINVAL;
652 
653 	code->code = thp7312_colour_fmts[code->index];
654 
655 	return 0;
656 }
657 
658 static int thp7312_enum_frame_size(struct v4l2_subdev *sd,
659 				   struct v4l2_subdev_state *sd_state,
660 				   struct v4l2_subdev_frame_size_enum *fse)
661 {
662 	if (!thp7312_find_bus_code(fse->code))
663 		return -EINVAL;
664 
665 	if (fse->index >= ARRAY_SIZE(thp7312_mode_info_data))
666 		return -EINVAL;
667 
668 	fse->min_width = thp7312_mode_info_data[fse->index].width;
669 	fse->max_width = fse->min_width;
670 	fse->min_height = thp7312_mode_info_data[fse->index].height;
671 	fse->max_height = fse->min_height;
672 
673 	return 0;
674 }
675 
676 static int thp7312_enum_frame_interval(struct v4l2_subdev *sd,
677 				       struct v4l2_subdev_state *sd_state,
678 				       struct v4l2_subdev_frame_interval_enum *fie)
679 {
680 	const struct thp7312_frame_rate *rate;
681 	const struct thp7312_mode_info *mode;
682 	unsigned int index = fie->index;
683 
684 	if (!thp7312_find_bus_code(fie->code))
685 		return -EINVAL;
686 
687 	mode = thp7312_find_mode(fie->width, fie->height, false);
688 	if (!mode)
689 		return -EINVAL;
690 
691 	for (rate = mode->rates; rate->fps; ++rate, --index) {
692 		if (!index) {
693 			fie->interval.numerator = 1;
694 			fie->interval.denominator = rate->fps;
695 
696 			return 0;
697 		}
698 	}
699 
700 	return -EINVAL;
701 }
702 
703 static int thp7312_set_fmt(struct v4l2_subdev *sd,
704 			   struct v4l2_subdev_state *sd_state,
705 			   struct v4l2_subdev_format *format)
706 {
707 	struct thp7312_device *thp7312 = to_thp7312_dev(sd);
708 	struct v4l2_mbus_framefmt *mbus_fmt = &format->format;
709 	struct v4l2_mbus_framefmt *fmt;
710 	const struct thp7312_mode_info *mode;
711 
712 	if (!thp7312_find_bus_code(mbus_fmt->code))
713 		mbus_fmt->code = thp7312_colour_fmts[0];
714 
715 	mode = thp7312_find_mode(mbus_fmt->width, mbus_fmt->height, true);
716 
717 	fmt = v4l2_subdev_state_get_format(sd_state, 0);
718 
719 	fmt->code = mbus_fmt->code;
720 	fmt->width = mode->width;
721 	fmt->height = mode->height;
722 	fmt->colorspace = V4L2_COLORSPACE_SRGB;
723 	fmt->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(fmt->colorspace);
724 	fmt->quantization = V4L2_QUANTIZATION_FULL_RANGE;
725 	fmt->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(fmt->colorspace);
726 
727 	*mbus_fmt = *fmt;
728 
729 	if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
730 		thp7312->current_mode = mode;
731 		thp7312_set_frame_rate(thp7312, &mode->rates[0]);
732 	}
733 
734 	return 0;
735 }
736 
737 static int thp7312_g_frame_interval(struct v4l2_subdev *sd,
738 				    struct v4l2_subdev_frame_interval *fi)
739 {
740 	struct thp7312_device *thp7312 = to_thp7312_dev(sd);
741 	struct v4l2_subdev_state *sd_state;
742 
743 	sd_state = v4l2_subdev_lock_and_get_active_state(sd);
744 	fi->interval.numerator = 1;
745 	fi->interval.denominator = thp7312->current_rate->fps;
746 	v4l2_subdev_unlock_state(sd_state);
747 
748 	return 0;
749 }
750 
751 static int thp7312_s_frame_interval(struct v4l2_subdev *sd,
752 				    struct v4l2_subdev_frame_interval *fi)
753 {
754 	struct thp7312_device *thp7312 = to_thp7312_dev(sd);
755 	const struct thp7312_mode_info *mode;
756 	const struct thp7312_frame_rate *best_rate = NULL;
757 	const struct thp7312_frame_rate *rate;
758 	struct v4l2_subdev_state *sd_state;
759 	unsigned int best_delta = UINT_MAX;
760 	unsigned int fps;
761 
762 	/* Avoid divisions by 0, pick the highest frame if the interval is 0. */
763 	fps = fi->interval.numerator
764 	    ? DIV_ROUND_CLOSEST(fi->interval.denominator, fi->interval.numerator)
765 	    : UINT_MAX;
766 
767 	sd_state = v4l2_subdev_lock_and_get_active_state(sd);
768 
769 	mode = thp7312->current_mode;
770 
771 	for (rate = mode->rates; rate->fps && best_delta; ++rate) {
772 		unsigned int delta = abs(rate->fps - fps);
773 
774 		if (delta <= best_delta) {
775 			best_delta = delta;
776 			best_rate = rate;
777 		}
778 	}
779 
780 	thp7312_set_frame_rate(thp7312, best_rate);
781 
782 	v4l2_subdev_unlock_state(sd_state);
783 
784 	fi->interval.numerator = 1;
785 	fi->interval.denominator = best_rate->fps;
786 
787 	return 0;
788 }
789 
790 static int thp7312_s_stream(struct v4l2_subdev *sd, int enable)
791 {
792 	struct thp7312_device *thp7312 = to_thp7312_dev(sd);
793 	struct v4l2_subdev_state *sd_state;
794 	int ret;
795 
796 	sd_state = v4l2_subdev_lock_and_get_active_state(sd);
797 
798 	if (!enable) {
799 		thp7312_stream_enable(thp7312, false);
800 
801 		pm_runtime_mark_last_busy(thp7312->dev);
802 		pm_runtime_put_autosuspend(thp7312->dev);
803 
804 		v4l2_subdev_unlock_state(sd_state);
805 
806 		return 0;
807 	}
808 
809 	ret = pm_runtime_resume_and_get(thp7312->dev);
810 	if (ret)
811 		goto finish_unlock;
812 
813 	ret = thp7312_init_mode(thp7312, sd_state);
814 	if (ret)
815 		goto finish_pm;
816 
817 	if (!thp7312->ctrls_applied) {
818 		ret = __v4l2_ctrl_handler_setup(&thp7312->ctrl_handler);
819 		if (ret)
820 			goto finish_pm;
821 
822 		thp7312->ctrls_applied = true;
823 	}
824 
825 	ret = thp7312_stream_enable(thp7312, true);
826 	if (ret)
827 		goto finish_pm;
828 
829 	goto finish_unlock;
830 
831 finish_pm:
832 	pm_runtime_mark_last_busy(thp7312->dev);
833 	pm_runtime_put_autosuspend(thp7312->dev);
834 finish_unlock:
835 	v4l2_subdev_unlock_state(sd_state);
836 
837 	return ret;
838 }
839 
840 static int thp7312_init_state(struct v4l2_subdev *sd,
841 			      struct v4l2_subdev_state *sd_state)
842 {
843 	const struct thp7312_mode_info *default_mode = &thp7312_mode_info_data[0];
844 	struct v4l2_mbus_framefmt *fmt;
845 
846 	fmt = v4l2_subdev_state_get_format(sd_state, 0);
847 
848 	/*
849 	 * default init sequence initialize thp7312 to
850 	 * YUV422 YUYV VGA@30fps
851 	 */
852 	fmt->code = MEDIA_BUS_FMT_YUYV8_1X16;
853 	fmt->colorspace = V4L2_COLORSPACE_SRGB;
854 	fmt->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(fmt->colorspace);
855 	fmt->quantization = V4L2_QUANTIZATION_FULL_RANGE;
856 	fmt->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(fmt->colorspace);
857 	fmt->width = default_mode->width;
858 	fmt->height = default_mode->height;
859 	fmt->field = V4L2_FIELD_NONE;
860 
861 	return 0;
862 }
863 
864 static const struct v4l2_subdev_core_ops thp7312_core_ops = {
865 	.log_status = v4l2_ctrl_subdev_log_status,
866 	.subscribe_event = v4l2_ctrl_subdev_subscribe_event,
867 	.unsubscribe_event = v4l2_event_subdev_unsubscribe,
868 };
869 
870 static const struct v4l2_subdev_video_ops thp7312_video_ops = {
871 	.g_frame_interval = thp7312_g_frame_interval,
872 	.s_frame_interval = thp7312_s_frame_interval,
873 	.s_stream = thp7312_s_stream,
874 };
875 
876 static const struct v4l2_subdev_pad_ops thp7312_pad_ops = {
877 	.enum_mbus_code = thp7312_enum_mbus_code,
878 	.get_fmt = v4l2_subdev_get_fmt,
879 	.set_fmt = thp7312_set_fmt,
880 	.enum_frame_size = thp7312_enum_frame_size,
881 	.enum_frame_interval = thp7312_enum_frame_interval,
882 };
883 
884 static const struct v4l2_subdev_ops thp7312_subdev_ops = {
885 	.core = &thp7312_core_ops,
886 	.video = &thp7312_video_ops,
887 	.pad = &thp7312_pad_ops,
888 };
889 
890 static const struct v4l2_subdev_internal_ops thp7312_internal_ops = {
891 	.init_state = thp7312_init_state,
892 };
893 
894 /* -----------------------------------------------------------------------------
895  * V4L2 Control Operations
896  */
897 
898 static inline struct thp7312_device *to_thp7312_from_ctrl(struct v4l2_ctrl *ctrl)
899 {
900 	return container_of(ctrl->handler, struct thp7312_device, ctrl_handler);
901 }
902 
903 /* 0: 3000cm, 18: 8cm */
904 static const u16 thp7312_focus_values[] = {
905 	3000, 1000, 600, 450, 350,
906 	290,  240,  200, 170, 150,
907 	140,  130,  120, 110, 100,
908 	93,   87,   83,  80,
909 };
910 
911 static int thp7312_set_focus(struct thp7312_device *thp7312)
912 {
913 	enum thp7312_focus_state new_state = thp7312->focus_state;
914 	bool continuous;
915 	u8 af_control;
916 	u8 af_setting;
917 	int ret = 0;
918 
919 	/* Start by programming the manual focus position if it has changed. */
920 	if (thp7312->focus_absolute->is_new) {
921 		unsigned int value;
922 
923 		value = thp7312_focus_values[thp7312->focus_absolute->val];
924 
925 		ret = cci_write(thp7312->regmap,
926 				THP7312_REG_MANUAL_FOCUS_POSITION, value, NULL);
927 		if (ret)
928 			return ret;
929 	}
930 
931 	/* Calculate the new focus state. */
932 	switch (thp7312->focus_state) {
933 	case THP7312_FOCUS_STATE_MANUAL:
934 	default:
935 		if (thp7312->focus_auto->val)
936 			new_state = THP7312_FOCUS_STATE_AUTO;
937 		else if (thp7312->focus_start->is_new)
938 			new_state = THP7312_FOCUS_STATE_ONESHOT;
939 		break;
940 
941 	case THP7312_FOCUS_STATE_AUTO:
942 		if (!thp7312->focus_auto->val)
943 			new_state = THP7312_FOCUS_STATE_LOCKED;
944 		break;
945 
946 	case THP7312_FOCUS_STATE_LOCKED:
947 		if (thp7312->focus_auto->val)
948 			new_state = THP7312_FOCUS_STATE_AUTO;
949 		else if (thp7312->focus_start->is_new)
950 			new_state = THP7312_FOCUS_STATE_ONESHOT;
951 		else if (thp7312->focus_absolute->is_new)
952 			new_state = THP7312_FOCUS_STATE_MANUAL;
953 		break;
954 
955 	case THP7312_FOCUS_STATE_ONESHOT:
956 		if (thp7312->focus_auto->val)
957 			new_state = THP7312_FOCUS_STATE_AUTO;
958 		else if (thp7312->focus_start->is_new)
959 			new_state = THP7312_FOCUS_STATE_ONESHOT;
960 		else if (thp7312->focus_absolute->is_new)
961 			new_state = THP7312_FOCUS_STATE_MANUAL;
962 		break;
963 	}
964 
965 	/*
966 	 * If neither the state nor the focus method has changed, and no new
967 	 * one-shot focus is requested, there's nothing new to program to the
968 	 * hardware.
969 	 */
970 	if (thp7312->focus_state == new_state &&
971 	    !thp7312->focus_method->is_new && !thp7312->focus_start->is_new)
972 		return 0;
973 
974 	continuous = new_state == THP7312_FOCUS_STATE_MANUAL ||
975 		     new_state == THP7312_FOCUS_STATE_ONESHOT;
976 
977 	switch (thp7312->focus_method->val) {
978 	case THP7312_FOCUS_METHOD_CONTRAST:
979 	default:
980 		af_setting = continuous
981 			   ? THP7312_REG_AF_SETTING_CONTINUOUS_CONTRAST
982 			   : THP7312_REG_AF_SETTING_ONESHOT_CONTRAST;
983 		break;
984 	case THP7312_FOCUS_METHOD_PDAF:
985 		af_setting = continuous
986 			   ? THP7312_REG_AF_SETTING_CONTINUOUS_PDAF
987 			   : THP7312_REG_AF_SETTING_ONESHOT_PDAF;
988 		break;
989 	case THP7312_FOCUS_METHOD_HYBRID:
990 		af_setting = continuous
991 			   ? THP7312_REG_AF_SETTING_CONTINUOUS_HYBRID
992 			   : THP7312_REG_AF_SETTING_ONESHOT_HYBRID;
993 		break;
994 	}
995 
996 	switch (new_state) {
997 	case THP7312_FOCUS_STATE_MANUAL:
998 	default:
999 		af_control = THP7312_REG_AF_CONTROL_MANUAL;
1000 		break;
1001 	case THP7312_FOCUS_STATE_AUTO:
1002 	case THP7312_FOCUS_STATE_ONESHOT:
1003 		af_control = THP7312_REG_AF_CONTROL_AF;
1004 		break;
1005 	case THP7312_FOCUS_STATE_LOCKED:
1006 		af_control = THP7312_REG_AF_CONTROL_LOCK;
1007 		break;
1008 	}
1009 
1010 	cci_write(thp7312->regmap, THP7312_REG_AF_SETTING, af_setting, &ret);
1011 
1012 	if (new_state == THP7312_FOCUS_STATE_MANUAL &&
1013 	    (thp7312->focus_state == THP7312_FOCUS_STATE_AUTO ||
1014 	     thp7312->focus_state == THP7312_FOCUS_STATE_ONESHOT)) {
1015 		/* When switching to manual state, lock AF first. */
1016 		cci_write(thp7312->regmap, THP7312_REG_AF_CONTROL,
1017 			  THP7312_REG_AF_CONTROL_LOCK, &ret);
1018 	}
1019 
1020 	cci_write(thp7312->regmap, THP7312_REG_AF_CONTROL, af_control, &ret);
1021 
1022 	if (ret)
1023 		return ret;
1024 
1025 	thp7312->focus_state = new_state;
1026 
1027 	return 0;
1028 }
1029 
1030 static int thp7312_s_ctrl(struct v4l2_ctrl *ctrl)
1031 {
1032 	struct thp7312_device *thp7312 = to_thp7312_from_ctrl(ctrl);
1033 	int ret = 0;
1034 	u8 value;
1035 
1036 	if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE)
1037 		return -EINVAL;
1038 
1039 	if (!pm_runtime_get_if_active(thp7312->dev, true))
1040 		return 0;
1041 
1042 	switch (ctrl->id) {
1043 	case V4L2_CID_BRIGHTNESS:
1044 		cci_write(thp7312->regmap, THP7312_REG_BRIGHTNESS,
1045 			  ctrl->val + 10, &ret);
1046 		break;
1047 
1048 	case V4L2_CID_THP7312_LOW_LIGHT_COMPENSATION:
1049 		/* 0 = Auto adjust frame rate, 1 = Fix frame rate */
1050 		cci_write(thp7312->regmap, THP7312_REG_AE_FIX_FRAME_RATE,
1051 			  ctrl->val ? 0 : 1, &ret);
1052 		break;
1053 
1054 	case V4L2_CID_FOCUS_AUTO:
1055 	case V4L2_CID_FOCUS_ABSOLUTE:
1056 	case V4L2_CID_AUTO_FOCUS_START:
1057 	case V4L2_CID_THP7312_AUTO_FOCUS_METHOD:
1058 		ret = thp7312_set_focus(thp7312);
1059 		break;
1060 
1061 	case V4L2_CID_HFLIP:
1062 	case V4L2_CID_VFLIP:
1063 		value = (thp7312->hflip->val ? THP7312_REG_FLIP_MIRROR_MIRROR : 0)
1064 		      | (thp7312->vflip->val ? THP7312_REG_FLIP_MIRROR_FLIP : 0);
1065 
1066 		cci_write(thp7312->regmap, THP7312_REG_FLIP_MIRROR, value, &ret);
1067 		break;
1068 
1069 	case V4L2_CID_THP7312_NOISE_REDUCTION_AUTO:
1070 	case V4L2_CID_THP7312_NOISE_REDUCTION_ABSOLUTE:
1071 		value = thp7312->noise_reduction_auto->val ? 0
1072 		      : THP7312_REG_NOISE_REDUCTION_FIXED |
1073 			thp7312->noise_reduction_absolute->val;
1074 
1075 		cci_write(thp7312->regmap, THP7312_REG_NOISE_REDUCTION, value,
1076 			  &ret);
1077 		break;
1078 
1079 	case V4L2_CID_AUTO_WHITE_BALANCE:
1080 		value = ctrl->val ? THP7312_WB_MODE_AUTO : THP7312_WB_MODE_MANUAL;
1081 
1082 		cci_write(thp7312->regmap, THP7312_REG_WB_MODE, value, &ret);
1083 		break;
1084 
1085 	case V4L2_CID_RED_BALANCE:
1086 		cci_write(thp7312->regmap, THP7312_REG_MANUAL_WB_RED_GAIN,
1087 			  ctrl->val, &ret);
1088 		break;
1089 
1090 	case V4L2_CID_BLUE_BALANCE:
1091 		cci_write(thp7312->regmap, THP7312_REG_MANUAL_WB_BLUE_GAIN,
1092 			  ctrl->val, &ret);
1093 		break;
1094 
1095 	case V4L2_CID_AUTO_EXPOSURE_BIAS:
1096 		cci_write(thp7312->regmap, THP7312_REG_AE_EXPOSURE_COMPENSATION,
1097 			  ctrl->val, &ret);
1098 		break;
1099 
1100 	case V4L2_CID_POWER_LINE_FREQUENCY:
1101 		if (ctrl->val == V4L2_CID_POWER_LINE_FREQUENCY_60HZ) {
1102 			value = THP7312_AE_FLICKER_MODE_60;
1103 		} else if (ctrl->val == V4L2_CID_POWER_LINE_FREQUENCY_50HZ) {
1104 			value = THP7312_AE_FLICKER_MODE_50;
1105 		} else {
1106 			if (thp7312->fw_version == THP7312_FW_VERSION(40, 3)) {
1107 				/* THP7312_AE_FLICKER_MODE_DISABLE is not supported */
1108 				value = THP7312_AE_FLICKER_MODE_50;
1109 			} else {
1110 				value = THP7312_AE_FLICKER_MODE_DISABLE;
1111 			}
1112 		}
1113 
1114 		cci_write(thp7312->regmap, THP7312_REG_AE_FLICKER_MODE,
1115 			  value, &ret);
1116 		break;
1117 
1118 	case V4L2_CID_SATURATION:
1119 		cci_write(thp7312->regmap, THP7312_REG_SATURATION,
1120 			  ctrl->val, &ret);
1121 		break;
1122 
1123 	case V4L2_CID_CONTRAST:
1124 		cci_write(thp7312->regmap, THP7312_REG_CONTRAST,
1125 			  ctrl->val, &ret);
1126 		break;
1127 
1128 	case V4L2_CID_SHARPNESS:
1129 		cci_write(thp7312->regmap, THP7312_REG_SHARPNESS,
1130 			  ctrl->val, &ret);
1131 		break;
1132 
1133 	default:
1134 		break;
1135 	}
1136 
1137 	pm_runtime_mark_last_busy(thp7312->dev);
1138 	pm_runtime_put_autosuspend(thp7312->dev);
1139 
1140 	return ret;
1141 }
1142 
1143 static const struct v4l2_ctrl_ops thp7312_ctrl_ops = {
1144 	.s_ctrl = thp7312_s_ctrl,
1145 };
1146 
1147 /*
1148  * Refer to Documentation/userspace-api/media/drivers/thp7312.rst for details.
1149  */
1150 static const struct v4l2_ctrl_config thp7312_ctrl_focus_method_cdaf = {
1151 	.ops = &thp7312_ctrl_ops,
1152 	.id = V4L2_CID_THP7312_AUTO_FOCUS_METHOD,
1153 	.name = "Auto-Focus Method",
1154 	.type = V4L2_CTRL_TYPE_INTEGER,
1155 	.min = THP7312_FOCUS_METHOD_CONTRAST,
1156 	.def = THP7312_FOCUS_METHOD_CONTRAST,
1157 	.max = THP7312_FOCUS_METHOD_CONTRAST,
1158 	.step = 1,
1159 };
1160 
1161 static const struct v4l2_ctrl_config thp7312_ctrl_focus_method_pdaf = {
1162 	.ops = &thp7312_ctrl_ops,
1163 	.id = V4L2_CID_THP7312_AUTO_FOCUS_METHOD,
1164 	.name = "Auto-Focus Method",
1165 	.type = V4L2_CTRL_TYPE_INTEGER,
1166 	.min = THP7312_FOCUS_METHOD_CONTRAST,
1167 	.def = THP7312_FOCUS_METHOD_HYBRID,
1168 	.max = THP7312_FOCUS_METHOD_HYBRID,
1169 	.step = 1,
1170 };
1171 
1172 static const struct v4l2_ctrl_config thp7312_v4l2_ctrls_custom[] = {
1173 	{
1174 		.ops = &thp7312_ctrl_ops,
1175 		.id = V4L2_CID_THP7312_LOW_LIGHT_COMPENSATION,
1176 		.name = "Low Light Compensation",
1177 		.type = V4L2_CTRL_TYPE_BOOLEAN,
1178 		.min = 0,
1179 		.def = 1,
1180 		.max = 1,
1181 		.step = 1,
1182 	}, {
1183 		.ops = &thp7312_ctrl_ops,
1184 		.id = V4L2_CID_THP7312_NOISE_REDUCTION_AUTO,
1185 		.name = "Noise Reduction Auto",
1186 		.type = V4L2_CTRL_TYPE_BOOLEAN,
1187 		.min = 0,
1188 		.def = 1,
1189 		.max = 1,
1190 		.step = 1,
1191 	}, {
1192 		.ops = &thp7312_ctrl_ops,
1193 		.id = V4L2_CID_THP7312_NOISE_REDUCTION_ABSOLUTE,
1194 		.name = "Noise Reduction Level",
1195 		.type = V4L2_CTRL_TYPE_INTEGER,
1196 		.min = 0,
1197 		.def = 0,
1198 		.max = 10,
1199 		.step = 1,
1200 	},
1201 };
1202 
1203 static const s64 exp_bias_qmenu[] = {
1204 	-2000, -1667, -1333, -1000, -667, -333, 0, 333, 667, 1000, 1333, 1667, 2000
1205 };
1206 
1207 static int thp7312_init_controls(struct thp7312_device *thp7312)
1208 {
1209 	struct v4l2_ctrl_handler *hdl = &thp7312->ctrl_handler;
1210 	struct device *dev = thp7312->dev;
1211 	struct v4l2_fwnode_device_properties props;
1212 	struct v4l2_ctrl *link_freq;
1213 	unsigned int num_controls;
1214 	unsigned int i;
1215 	u8 af_support;
1216 	int ret;
1217 
1218 	/*
1219 	 * Check what auto-focus methods the connected sensor supports, if any.
1220 	 * Firmwares before v90.03 didn't expose the AF_SUPPORT register,
1221 	 * consider both CDAF and PDAF as supported in that case.
1222 	 */
1223 	if (thp7312->fw_version >= THP7312_FW_VERSION(90, 3)) {
1224 		u64 val;
1225 
1226 		ret = cci_read(thp7312->regmap, THP7312_REG_AF_SUPPORT, &val,
1227 			       NULL);
1228 		if (ret)
1229 			return ret;
1230 
1231 		af_support = val & (THP7312_AF_SUPPORT_PDAF |
1232 				    THP7312_AF_SUPPORT_CONTRAST);
1233 	} else {
1234 		af_support = THP7312_AF_SUPPORT_PDAF
1235 			   | THP7312_AF_SUPPORT_CONTRAST;
1236 	}
1237 
1238 	num_controls = 14 + ARRAY_SIZE(thp7312_v4l2_ctrls_custom)
1239 		     + (af_support ? 4 : 0);
1240 
1241 	v4l2_ctrl_handler_init(hdl, num_controls);
1242 
1243 	if (af_support) {
1244 		const struct v4l2_ctrl_config *af_method;
1245 
1246 		af_method = af_support & THP7312_AF_SUPPORT_PDAF
1247 			  ? &thp7312_ctrl_focus_method_pdaf
1248 			  : &thp7312_ctrl_focus_method_cdaf;
1249 
1250 		thp7312->focus_state = THP7312_FOCUS_STATE_MANUAL;
1251 
1252 		thp7312->focus_auto =
1253 			v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops,
1254 					  V4L2_CID_FOCUS_AUTO,
1255 					  0, 1, 1, 1);
1256 		thp7312->focus_absolute =
1257 			v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops,
1258 					  V4L2_CID_FOCUS_ABSOLUTE,
1259 					  0, ARRAY_SIZE(thp7312_focus_values),
1260 					  1, 0);
1261 		thp7312->focus_method =
1262 			v4l2_ctrl_new_custom(hdl, af_method, NULL);
1263 		thp7312->focus_start =
1264 			v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops,
1265 					  V4L2_CID_AUTO_FOCUS_START,
1266 					  1, 1, 1, 1);
1267 
1268 		v4l2_ctrl_cluster(4, &thp7312->focus_auto);
1269 	}
1270 
1271 	v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops, V4L2_CID_AUTO_WHITE_BALANCE,
1272 			  0, 1, 1, 1);
1273 	/* 32: 1x, 255: 7.95x */
1274 	v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops, V4L2_CID_RED_BALANCE,
1275 			  32, 255, 1, 64);
1276 	/* 32: 1x, 255: 7.95x */
1277 	v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops, V4L2_CID_BLUE_BALANCE,
1278 			  32, 255, 1, 50);
1279 
1280 	v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops, V4L2_CID_BRIGHTNESS,
1281 			  -10, 10, 1, 0);
1282 	v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops, V4L2_CID_SATURATION,
1283 			  0, 31, 1, 10);
1284 	v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops, V4L2_CID_CONTRAST,
1285 			  0, 20, 1, 10);
1286 	v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops, V4L2_CID_SHARPNESS,
1287 			  0, 31, 1, 8);
1288 
1289 	thp7312->hflip = v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops,
1290 					   V4L2_CID_HFLIP, 0, 1, 1, 0);
1291 	thp7312->vflip = v4l2_ctrl_new_std(hdl, &thp7312_ctrl_ops,
1292 					   V4L2_CID_VFLIP, 0, 1, 1, 0);
1293 
1294 	v4l2_ctrl_cluster(2, &thp7312->hflip);
1295 
1296 	v4l2_ctrl_new_int_menu(hdl, &thp7312_ctrl_ops,
1297 			       V4L2_CID_AUTO_EXPOSURE_BIAS,
1298 			       ARRAY_SIZE(exp_bias_qmenu) - 1,
1299 			       ARRAY_SIZE(exp_bias_qmenu) / 2, exp_bias_qmenu);
1300 
1301 	v4l2_ctrl_new_std_menu(hdl, &thp7312_ctrl_ops,
1302 			       V4L2_CID_POWER_LINE_FREQUENCY,
1303 			       V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0,
1304 			       V4L2_CID_POWER_LINE_FREQUENCY_50HZ);
1305 
1306 	link_freq = v4l2_ctrl_new_int_menu(hdl, &thp7312_ctrl_ops,
1307 					   V4L2_CID_LINK_FREQ, 0, 0,
1308 					   &thp7312->link_freq);
1309 
1310 	/* Set properties from fwnode (e.g. rotation, orientation). */
1311 	ret = v4l2_fwnode_device_parse(dev, &props);
1312 	if (ret) {
1313 		dev_err(dev, "Failed to parse fwnode: %d\n", ret);
1314 		goto error;
1315 	}
1316 
1317 	ret = v4l2_ctrl_new_fwnode_properties(hdl, &thp7312_ctrl_ops, &props);
1318 	if (ret) {
1319 		dev_err(dev, "Failed to create new v4l2 ctrl for fwnode properties: %d\n", ret);
1320 		goto error;
1321 	}
1322 
1323 	for (i = 0; i < ARRAY_SIZE(thp7312_v4l2_ctrls_custom); i++) {
1324 		const struct v4l2_ctrl_config *ctrl_cfg =
1325 			&thp7312_v4l2_ctrls_custom[i];
1326 		struct v4l2_ctrl *ctrl;
1327 
1328 		ctrl = v4l2_ctrl_new_custom(hdl, ctrl_cfg, NULL);
1329 
1330 		if (ctrl_cfg->id == V4L2_CID_THP7312_NOISE_REDUCTION_AUTO)
1331 			thp7312->noise_reduction_auto = ctrl;
1332 		else if (ctrl_cfg->id == V4L2_CID_THP7312_NOISE_REDUCTION_ABSOLUTE)
1333 			thp7312->noise_reduction_absolute = ctrl;
1334 	}
1335 
1336 	v4l2_ctrl_cluster(2, &thp7312->noise_reduction_auto);
1337 
1338 	if (hdl->error) {
1339 		dev_err(dev, "v4l2_ctrl_handler error\n");
1340 		ret = hdl->error;
1341 		goto error;
1342 	}
1343 
1344 	link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY;
1345 
1346 	return ret;
1347 
1348 error:
1349 	v4l2_ctrl_handler_free(hdl);
1350 	return ret;
1351 }
1352 
1353 /* -----------------------------------------------------------------------------
1354  * Firmware Update
1355  */
1356 
1357 /*
1358  * The firmware data is made of 128kB of RAM firmware, followed by a
1359  * variable-size "header". Both are stored in flash memory.
1360  */
1361 #define THP7312_FW_RAM_SIZE			(128 * 1024)
1362 #define THP7312_FW_MIN_SIZE			(THP7312_FW_RAM_SIZE + 4)
1363 #define THP7312_FW_MAX_SIZE			(THP7312_FW_RAM_SIZE + 64 * 1024)
1364 
1365 /*
1366  * Data is first uploaded to the THP7312 128kB SRAM, and then written to flash.
1367  * The SRAM is exposed over I2C as 32kB banks, and up to 4kB of data can be
1368  * transferred in a single I2C write.
1369  */
1370 #define THP7312_RAM_BANK_SIZE			(32 * 1024)
1371 #define THP7312_FW_DOWNLOAD_UNIT		(4 * 1024)
1372 
1373 #define THP7312_FLASH_MEMORY_ERASE_TIMEOUT	40
1374 
1375 #define THP7312_FLASH_MAX_REG_READ_SIZE		10
1376 #define THP7312_FLASH_MAX_REG_DATA_SIZE		10
1377 
1378 static const u8 thp7312_cmd_config_flash_mem_if[] = {
1379 	0xd5, 0x18, 0x00, 0x00, 0x00, 0x80
1380 };
1381 
1382 static const u8 thp7312_cmd_write_to_reg[] = {
1383 	0xd5, 0x0c, 0x80, 0x00, 0x00, 0x00
1384 };
1385 
1386 static const u8 thp7312_cmd_read_reg[] = {
1387 	0xd5, 0x04
1388 };
1389 
1390 /*
1391  * THP7312 Write data from RAM to Flash Memory
1392  * Command ID FF700F
1393  * Format: FF700F AA AA AA BB BB BB
1394  * AA AA AA: destination start address
1395  * BB BB BB: (write size - 1)
1396  * Source address always starts from 0
1397  */
1398 static const u8 thp7312_cmd_write_ram_to_flash[] = { 0xff, 0x70, 0x0f };
1399 
1400 /*
1401  * THP7312 Calculate CRC command
1402  * Command ID: FF70 09
1403  * Format: FF70 09 AA AA AA BB BB BB
1404  * AA AA AA: Start address of calculation
1405  * BB BB BB: (calculate size - 1)
1406  */
1407 static const u8 thp7312_cmd_calc_crc[] = { 0xff, 0x70, 0x09 };
1408 
1409 static const u8 thp7312_jedec_rdid[] = { SPINOR_OP_RDID, 0x00, 0x00, 0x00 };
1410 static const u8 thp7312_jedec_rdsr[] = { SPINOR_OP_RDSR, 0x00, 0x00, 0x00 };
1411 static const u8 thp7312_jedec_wen[] = { SPINOR_OP_WREN };
1412 
1413 static int thp7312_read_firmware_version(struct thp7312_device *thp7312)
1414 {
1415 	u64 val = 0;
1416 	int ret = 0;
1417 	u8 major;
1418 	u8 minor;
1419 
1420 	cci_read(thp7312->regmap, THP7312_REG_FIRMWARE_VERSION_1, &val, &ret);
1421 	major = val;
1422 
1423 	cci_read(thp7312->regmap, THP7312_REG_FIRMWARE_VERSION_2, &val, &ret);
1424 	minor = val;
1425 
1426 	thp7312->fw_version = THP7312_FW_VERSION(major, minor);
1427 	return ret;
1428 }
1429 
1430 static int thp7312_write_buf(struct thp7312_device *thp7312,
1431 			     const u8 *write_buf, u16 write_size)
1432 {
1433 	struct i2c_client *client = to_i2c_client(thp7312->dev);
1434 	int ret;
1435 
1436 	ret = i2c_master_send(client, write_buf, write_size);
1437 	return ret >= 0 ? 0 : ret;
1438 }
1439 
1440 static int __thp7312_flash_reg_write(struct thp7312_device *thp7312,
1441 				     const u8 *write_buf, u16 write_size)
1442 {
1443 	struct device *dev = thp7312->dev;
1444 	u8 temp_write_buf[THP7312_FLASH_MAX_REG_DATA_SIZE + 2];
1445 	int ret;
1446 
1447 	if (write_size > THP7312_FLASH_MAX_REG_DATA_SIZE) {
1448 		dev_err(dev, "%s: Write size error size = %d\n",
1449 			__func__, write_size);
1450 		return -EINVAL;
1451 	}
1452 
1453 	ret = thp7312_write_buf(thp7312, thp7312_cmd_config_flash_mem_if,
1454 				sizeof(thp7312_cmd_config_flash_mem_if));
1455 	if (ret < 0) {
1456 		dev_err(dev, "%s: Failed to config flash memory IF: %d\n",
1457 			__func__, ret);
1458 		return ret;
1459 	}
1460 
1461 	temp_write_buf[0] = 0xd5;
1462 	temp_write_buf[1] = 0x00;
1463 	memcpy((temp_write_buf + 2), write_buf, write_size);
1464 	ret = thp7312_write_buf(thp7312, temp_write_buf, write_size + 2);
1465 	if (ret < 0)
1466 		return ret;
1467 
1468 	thp7312_write_buf(thp7312, thp7312_cmd_write_to_reg,
1469 			  sizeof(thp7312_cmd_write_to_reg));
1470 
1471 	return 0;
1472 }
1473 
1474 static int __thp7312_flash_reg_read(struct thp7312_device *thp7312,
1475 				    const u8 *write_buf, u16 write_size,
1476 				    u8 *read_buf, u16 read_size)
1477 {
1478 	struct i2c_client *client = to_i2c_client(thp7312->dev);
1479 	struct i2c_msg msgs[2];
1480 	int ret;
1481 
1482 	ret = __thp7312_flash_reg_write(thp7312, write_buf, write_size);
1483 	if (ret)
1484 		return ret;
1485 
1486 	msgs[0].addr = client->addr;
1487 	msgs[0].flags = 0;
1488 	msgs[0].len = sizeof(thp7312_cmd_read_reg),
1489 	msgs[0].buf = (u8 *)thp7312_cmd_read_reg;
1490 
1491 	msgs[1].addr = client->addr;
1492 	msgs[1].flags = I2C_M_RD;
1493 	msgs[1].len = read_size;
1494 	msgs[1].buf = read_buf;
1495 
1496 	ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
1497 	return ret >= 0 ? 0 : ret;
1498 }
1499 
1500 #define thp7312_flash_reg_write(thp7312, wrbuf) \
1501 	__thp7312_flash_reg_write(thp7312, wrbuf, sizeof(wrbuf))
1502 
1503 #define thp7312_flash_reg_read(thp7312, wrbuf, rdbuf) \
1504 	__thp7312_flash_reg_read(thp7312, wrbuf, sizeof(wrbuf), \
1505 				 rdbuf, sizeof(rdbuf))
1506 
1507 static enum fw_upload_err thp7312_fw_prepare_config(struct thp7312_device *thp7312)
1508 {
1509 	struct device *dev = thp7312->dev;
1510 	int ret;
1511 
1512 	ret = cci_write(thp7312->regmap, THP7312_REG_FW_MEMORY_IO_SETTING,
1513 			THP7312_FW_MEMORY_IO_GPIO0, NULL);
1514 	if (ret) {
1515 		dev_err(dev, "Failed to set flash memory I/O\n");
1516 		return FW_UPLOAD_ERR_HW_ERROR;
1517 	}
1518 
1519 	/* Set max drivability. */
1520 	ret = cci_write(thp7312->regmap, THP7312_REG_FW_DRIVABILITY, 0x00777777,
1521 			NULL);
1522 	if (ret) {
1523 		dev_err(dev, "Failed to set drivability: %d\n", ret);
1524 		return FW_UPLOAD_ERR_HW_ERROR;
1525 	}
1526 
1527 	return FW_UPLOAD_ERR_NONE;
1528 }
1529 
1530 static enum fw_upload_err thp7312_fw_prepare_check(struct thp7312_device *thp7312)
1531 {
1532 	struct device *dev = thp7312->dev;
1533 	u8 read_buf[3] = { 0 };
1534 	int ret;
1535 
1536 	/* Get JEDEC ID */
1537 	ret = thp7312_flash_reg_read(thp7312, thp7312_jedec_rdid, read_buf);
1538 	if (ret) {
1539 		dev_err(dev, "Failed to get JEDEC ID: %d\n", ret);
1540 		return FW_UPLOAD_ERR_HW_ERROR;
1541 	}
1542 
1543 	dev_dbg(dev, "Flash Memory: JEDEC ID = 0x%x 0x%x 0x%x\n",
1544 		read_buf[0], read_buf[1], read_buf[2]);
1545 
1546 	return FW_UPLOAD_ERR_NONE;
1547 }
1548 
1549 static enum fw_upload_err thp7312_fw_prepare_reset(struct thp7312_device *thp7312)
1550 {
1551 	struct device *dev = thp7312->dev;
1552 	int ret;
1553 
1554 	ret = cci_write(thp7312->regmap, THP7312_REG_FW_RESET_FLASH, 0x81, NULL);
1555 	if (ret) {
1556 		dev_err(dev, "Failed to reset flash memory: %d\n", ret);
1557 		return FW_UPLOAD_ERR_HW_ERROR;
1558 	}
1559 
1560 	return FW_UPLOAD_ERR_NONE;
1561 }
1562 
1563 /* TODO: Erase only the amount of blocks necessary */
1564 static enum fw_upload_err thp7312_flash_erase(struct thp7312_device *thp7312)
1565 {
1566 	struct device *dev = thp7312->dev;
1567 	u8 read_buf[1] = { 0 };
1568 	unsigned int i;
1569 	u8 block;
1570 	int ret;
1571 
1572 	for (block = 0; block < 3; block++) {
1573 		const u8 jedec_se[] = { SPINOR_OP_SE, block, 0x00, 0x00 };
1574 
1575 		ret = thp7312_flash_reg_write(thp7312, thp7312_jedec_wen);
1576 		if (ret < 0) {
1577 			dev_err(dev, "Failed to enable flash for writing\n");
1578 			return FW_UPLOAD_ERR_RW_ERROR;
1579 		}
1580 
1581 		ret = thp7312_flash_reg_write(thp7312, jedec_se);
1582 		if (ret < 0) {
1583 			dev_err(dev, "Failed to erase flash sector\n");
1584 			return FW_UPLOAD_ERR_RW_ERROR;
1585 		}
1586 
1587 		for (i = 0; i < THP7312_FLASH_MEMORY_ERASE_TIMEOUT; i++) {
1588 			usleep_range(100000, 101000);
1589 			thp7312_flash_reg_read(thp7312, thp7312_jedec_rdsr,
1590 					       read_buf);
1591 
1592 			/* Check Busy bit. Busy == 0x0 means erase complete. */
1593 			if (!(read_buf[0] & SR_WIP))
1594 				break;
1595 		}
1596 
1597 		if (i == THP7312_FLASH_MEMORY_ERASE_TIMEOUT)
1598 			return FW_UPLOAD_ERR_TIMEOUT;
1599 	}
1600 
1601 	thp7312_flash_reg_read(thp7312, thp7312_jedec_rdsr, read_buf);
1602 
1603 	/* Check WEL bit. */
1604 	if (read_buf[0] & SR_WEL)
1605 		return FW_UPLOAD_ERR_HW_ERROR;
1606 
1607 	return FW_UPLOAD_ERR_NONE;
1608 }
1609 
1610 static enum fw_upload_err
1611 thp7312_write_download_data_by_unit(struct thp7312_device *thp7312,
1612 				    unsigned int addr, const u8 *data,
1613 				    unsigned int size)
1614 {
1615 	struct device *dev = thp7312->dev;
1616 	u8 *write_buf = thp7312->fw_write_buf;
1617 	int ret;
1618 
1619 	dev_dbg(dev, "%s: addr = 0x%04x, data = 0x%p, size = %u\n",
1620 		__func__, addr, data, size);
1621 
1622 	write_buf[0] = (addr >> 8) & 0xff;
1623 	write_buf[1] = (addr >> 0) & 0xff;
1624 	memcpy(&write_buf[2], data, size);
1625 
1626 	/*
1627 	 * THP7312 Firmware download to RAM
1628 	 * Command ID (address to download): 0x0000 - 0x7fff
1629 	 * Format:: 0000 XX XX XX ........ XX
1630 	 */
1631 	ret = thp7312_write_buf(thp7312, write_buf, size + 2);
1632 	if (ret < 0)
1633 		dev_err(dev, "Unit transfer ERROR %s(): ret = %d\n", __func__, ret);
1634 
1635 	return ret >= 0 ? FW_UPLOAD_ERR_NONE : FW_UPLOAD_ERR_RW_ERROR;
1636 }
1637 
1638 static enum fw_upload_err thp7312_fw_load_to_ram(struct thp7312_device *thp7312,
1639 						 const u8 *data, u32 size)
1640 {
1641 	struct device *dev = thp7312->dev;
1642 	enum fw_upload_err ret;
1643 	unsigned int num_banks;
1644 	unsigned int i, j;
1645 
1646 	num_banks = DIV_ROUND_UP(size, THP7312_RAM_BANK_SIZE);
1647 
1648 	dev_dbg(dev, "%s: loading %u bytes in SRAM (%u banks)\n", __func__,
1649 		size, num_banks);
1650 
1651 	for (i = 0; i < num_banks; i++) {
1652 		const u32 bank_addr = 0x10000000 | (i * THP7312_RAM_BANK_SIZE);
1653 		unsigned int bank_size;
1654 		unsigned int num_chunks;
1655 
1656 		ret = cci_write(thp7312->regmap, THP7312_REG_FW_DEST_BANK_ADDR,
1657 				bank_addr, NULL);
1658 		if (ret)
1659 			return FW_UPLOAD_ERR_HW_ERROR;
1660 
1661 		bank_size = min_t(u32, size, THP7312_RAM_BANK_SIZE);
1662 		num_chunks = DIV_ROUND_UP(bank_size, THP7312_FW_DOWNLOAD_UNIT);
1663 
1664 		dev_dbg(dev, "%s: loading %u bytes in SRAM bank %u (%u chunks)\n",
1665 			__func__, bank_size, i, num_chunks);
1666 
1667 		for (j = 0 ; j < num_chunks; j++) {
1668 			unsigned int chunk_addr;
1669 			unsigned int chunk_size;
1670 
1671 			chunk_addr = j * THP7312_FW_DOWNLOAD_UNIT;
1672 			chunk_size = min_t(u32, size, THP7312_FW_DOWNLOAD_UNIT);
1673 
1674 			ret = thp7312_write_download_data_by_unit(thp7312, chunk_addr,
1675 								  data, chunk_size);
1676 			if (ret != FW_UPLOAD_ERR_NONE) {
1677 				dev_err(dev, "Unit transfer ERROR at bank transfer %s(): %d\n",
1678 					__func__, j);
1679 				return ret;
1680 			}
1681 
1682 			data += chunk_size;
1683 			size -= chunk_size;
1684 		}
1685 	}
1686 
1687 	return FW_UPLOAD_ERR_NONE;
1688 }
1689 
1690 static enum fw_upload_err thp7312_fw_write_to_flash(struct thp7312_device *thp7312,
1691 						    u32 dest, u32 write_size)
1692 {
1693 	u8 command[sizeof(thp7312_cmd_write_ram_to_flash) + 6];
1694 	static const u32 cmd_size = sizeof(thp7312_cmd_write_ram_to_flash);
1695 	u64 val;
1696 	int ret;
1697 
1698 	memcpy(command, thp7312_cmd_write_ram_to_flash, cmd_size);
1699 
1700 	command[cmd_size] = (dest & 0xff0000) >> 16;
1701 	command[cmd_size + 1] = (dest & 0x00ff00) >> 8;
1702 	command[cmd_size + 2] = (dest & 0x0000ff);
1703 	command[cmd_size + 3] = ((write_size - 1) & 0xff0000) >> 16;
1704 	command[cmd_size + 4] = ((write_size - 1) & 0x00ff00) >> 8;
1705 	command[cmd_size + 5] = ((write_size - 1) & 0x0000ff);
1706 
1707 	ret = thp7312_write_buf(thp7312, command, sizeof(command));
1708 	if (ret < 0)
1709 		return FW_UPLOAD_ERR_RW_ERROR;
1710 
1711 	usleep_range(8000000, 8100000);
1712 
1713 	ret = cci_read(thp7312->regmap, THP7312_REG_FW_VERIFY_RESULT, &val,
1714 		       NULL);
1715 	if (ret < 0)
1716 		return FW_UPLOAD_ERR_RW_ERROR;
1717 
1718 	return val ?  FW_UPLOAD_ERR_HW_ERROR : FW_UPLOAD_ERR_NONE;
1719 }
1720 
1721 static enum fw_upload_err thp7312_fw_check_crc(struct thp7312_device *thp7312,
1722 					       const u8 *fw_data, u32 fw_size)
1723 {
1724 	struct device *dev = thp7312->dev;
1725 	u16 header_size = fw_size - THP7312_FW_RAM_SIZE;
1726 	u8 command[sizeof(thp7312_cmd_calc_crc) + 6];
1727 	static const u32 cmd_size = sizeof(thp7312_cmd_calc_crc);
1728 	u32 size = THP7312_FW_RAM_SIZE - 4;
1729 	u32 fw_crc;
1730 	u64 crc;
1731 	int ret;
1732 
1733 	memcpy(command, thp7312_cmd_calc_crc, cmd_size);
1734 
1735 	command[cmd_size] = 0;
1736 	command[cmd_size + 1] = (header_size >> 8) & 0xff;
1737 	command[cmd_size + 2] = header_size & 0xff;
1738 
1739 	command[cmd_size + 3] = (size >> 16) & 0xff;
1740 	command[cmd_size + 4] = (size >> 8) & 0xff;
1741 	command[cmd_size + 5] = size & 0xff;
1742 
1743 	ret = thp7312_write_buf(thp7312, command, sizeof(command));
1744 	if (ret < 0)
1745 		return FW_UPLOAD_ERR_RW_ERROR;
1746 
1747 	usleep_range(2000000, 2100000);
1748 
1749 	fw_crc = get_unaligned_be32(&fw_data[fw_size - 4]);
1750 
1751 	ret = cci_read(thp7312->regmap, THP7312_REG_FW_CRC_RESULT, &crc, NULL);
1752 	if (ret < 0)
1753 		return FW_UPLOAD_ERR_RW_ERROR;
1754 
1755 	if (fw_crc != crc) {
1756 		dev_err(dev, "CRC mismatch: firmware 0x%08x, flash 0x%08llx\n",
1757 			fw_crc, crc);
1758 		return FW_UPLOAD_ERR_HW_ERROR;
1759 	}
1760 
1761 	return FW_UPLOAD_ERR_NONE;
1762 }
1763 
1764 static enum fw_upload_err thp7312_fw_prepare(struct fw_upload *fw_upload,
1765 					     const u8 *data, u32 size)
1766 {
1767 	struct thp7312_device *thp7312 = fw_upload->dd_handle;
1768 	struct device *dev = thp7312->dev;
1769 	enum fw_upload_err ret;
1770 
1771 	mutex_lock(&thp7312->fw_lock);
1772 	thp7312->fw_cancel = false;
1773 	mutex_unlock(&thp7312->fw_lock);
1774 
1775 	if (size < THP7312_FW_MIN_SIZE || size > THP7312_FW_MAX_SIZE) {
1776 		dev_err(dev, "%s: Invalid firmware size %d; must be between %d and %d\n",
1777 			__func__, size, THP7312_FW_MIN_SIZE, THP7312_FW_MAX_SIZE);
1778 		return FW_UPLOAD_ERR_INVALID_SIZE;
1779 	}
1780 
1781 	ret = thp7312_fw_prepare_config(thp7312);
1782 	if (ret != FW_UPLOAD_ERR_NONE)
1783 		return ret;
1784 
1785 	ret = thp7312_fw_prepare_check(thp7312);
1786 	if (ret != FW_UPLOAD_ERR_NONE)
1787 		return ret;
1788 
1789 	ret = thp7312_fw_prepare_reset(thp7312);
1790 	if (ret != FW_UPLOAD_ERR_NONE)
1791 		return ret;
1792 
1793 	mutex_lock(&thp7312->fw_lock);
1794 	ret = thp7312->fw_cancel ? FW_UPLOAD_ERR_CANCELED : FW_UPLOAD_ERR_NONE;
1795 	mutex_unlock(&thp7312->fw_lock);
1796 
1797 	return ret;
1798 }
1799 
1800 static enum fw_upload_err thp7312_fw_write(struct fw_upload *fw_upload,
1801 					   const u8 *data, u32 offset,
1802 					   u32 size, u32 *written)
1803 {
1804 	struct thp7312_device *thp7312 = fw_upload->dd_handle;
1805 	struct device *dev = thp7312->dev;
1806 	u16 header_size = size - THP7312_FW_RAM_SIZE;
1807 	enum fw_upload_err ret;
1808 	bool cancel;
1809 
1810 	mutex_lock(&thp7312->fw_lock);
1811 	cancel = thp7312->fw_cancel;
1812 	mutex_unlock(&thp7312->fw_lock);
1813 
1814 	if (cancel)
1815 		return FW_UPLOAD_ERR_CANCELED;
1816 
1817 	ret = thp7312_flash_erase(thp7312);
1818 	if (ret != FW_UPLOAD_ERR_NONE)
1819 		return ret;
1820 
1821 	ret = thp7312_fw_load_to_ram(thp7312, data, THP7312_FW_RAM_SIZE);
1822 	if (ret != FW_UPLOAD_ERR_NONE)
1823 		return ret;
1824 
1825 	ret = thp7312_fw_write_to_flash(thp7312, 0, 0x1ffff);
1826 	if (ret != FW_UPLOAD_ERR_NONE)
1827 		return ret;
1828 
1829 	ret = thp7312_fw_load_to_ram(thp7312, data + THP7312_FW_RAM_SIZE, header_size);
1830 	if (ret != FW_UPLOAD_ERR_NONE)
1831 		return ret;
1832 
1833 	ret = thp7312_fw_write_to_flash(thp7312, 0x20000, header_size - 1);
1834 	if (ret != FW_UPLOAD_ERR_NONE)
1835 		return ret;
1836 
1837 	ret = thp7312_fw_check_crc(thp7312, data, size);
1838 	if (ret != FW_UPLOAD_ERR_NONE)
1839 		return ret;
1840 
1841 	dev_info(dev, "Successfully wrote firmware\n");
1842 
1843 	*written = size;
1844 	return FW_UPLOAD_ERR_NONE;
1845 }
1846 
1847 static enum fw_upload_err thp7312_fw_poll_complete(struct fw_upload *fw_upload)
1848 {
1849 	return FW_UPLOAD_ERR_NONE;
1850 }
1851 
1852 /*
1853  * This may be called asynchronously with an on-going update.  All other
1854  * functions are called sequentially in a single thread. To avoid contention on
1855  * register accesses, only update the cancel_request flag. Other functions will
1856  * check this flag and handle the cancel request synchronously.
1857  */
1858 static void thp7312_fw_cancel(struct fw_upload *fw_upload)
1859 {
1860 	struct thp7312_device *thp7312 = fw_upload->dd_handle;
1861 
1862 	mutex_lock(&thp7312->fw_lock);
1863 	thp7312->fw_cancel = true;
1864 	mutex_unlock(&thp7312->fw_lock);
1865 }
1866 
1867 static const struct fw_upload_ops thp7312_fw_upload_ops = {
1868 	.prepare = thp7312_fw_prepare,
1869 	.write = thp7312_fw_write,
1870 	.poll_complete = thp7312_fw_poll_complete,
1871 	.cancel = thp7312_fw_cancel,
1872 };
1873 
1874 static int thp7312_register_flash_mode(struct thp7312_device *thp7312)
1875 {
1876 	struct device *dev = thp7312->dev;
1877 	struct fw_upload *fwl;
1878 	u64 val;
1879 	int ret;
1880 
1881 	dev_info(dev, "booted in flash mode\n");
1882 
1883 	mutex_init(&thp7312->fw_lock);
1884 
1885 	thp7312->fw_write_buf = devm_kzalloc(dev, THP7312_FW_DOWNLOAD_UNIT + 2,
1886 					     GFP_KERNEL);
1887 	if (!thp7312->fw_write_buf)
1888 		return -ENOMEM;
1889 
1890 	ret = __thp7312_power_on(thp7312);
1891 	if (ret < 0)
1892 		return dev_err_probe(dev, ret, "Failed to power on\n");
1893 
1894 	ret = cci_read(thp7312->regmap, THP7312_REG_FW_STATUS, &val, NULL);
1895 	if (ret) {
1896 		dev_err_probe(dev, ret, "Camera status read failed\n");
1897 		goto error;
1898 	}
1899 
1900 	fwl = firmware_upload_register(THIS_MODULE, dev, "thp7312-firmware",
1901 				       &thp7312_fw_upload_ops, thp7312);
1902 	if (IS_ERR(fwl)) {
1903 		ret = PTR_ERR(fwl);
1904 		dev_err_probe(dev, ret, "Failed to register firmware upload\n");
1905 		goto error;
1906 	}
1907 
1908 	thp7312->fwl = fwl;
1909 	return 0;
1910 
1911 error:
1912 	__thp7312_power_off(thp7312);
1913 	return ret;
1914 }
1915 
1916 /* -----------------------------------------------------------------------------
1917  * Probe & Remove
1918  */
1919 
1920 static int thp7312_get_regulators(struct thp7312_device *thp7312)
1921 {
1922 	unsigned int i;
1923 
1924 	for (i = 0; i < ARRAY_SIZE(thp7312->supplies); i++)
1925 		thp7312->supplies[i].supply = thp7312_supply_name[i];
1926 
1927 	return devm_regulator_bulk_get(thp7312->dev,
1928 				       ARRAY_SIZE(thp7312->supplies),
1929 				       thp7312->supplies);
1930 }
1931 
1932 static int thp7312_sensor_parse_dt(struct thp7312_device *thp7312,
1933 				   struct fwnode_handle *node)
1934 {
1935 	struct device *dev = thp7312->dev;
1936 	struct thp7312_sensor *sensor;
1937 	const char *model;
1938 	u8 data_lanes[4];
1939 	u32 values[4];
1940 	unsigned int i;
1941 	u32 reg;
1942 	int ret;
1943 
1944 	/* Retrieve the sensor index from the reg property. */
1945 	ret = fwnode_property_read_u32(node, "reg", &reg);
1946 	if (ret < 0) {
1947 		dev_err(dev, "'reg' property missing in sensor node\n");
1948 		return -EINVAL;
1949 	}
1950 
1951 	if (reg >= ARRAY_SIZE(thp7312->sensors)) {
1952 		dev_err(dev, "Out-of-bounds 'reg' value %u\n", reg);
1953 		return -EINVAL;
1954 	}
1955 
1956 	sensor = &thp7312->sensors[reg];
1957 	if (sensor->info) {
1958 		dev_err(dev, "Duplicate entry for sensor %u\n", reg);
1959 		return -EINVAL;
1960 	}
1961 
1962 	ret = fwnode_property_read_string(node, "thine,model", &model);
1963 	if (ret < 0) {
1964 		dev_err(dev, "'thine,model' property missing in sensor node\n");
1965 		return -EINVAL;
1966 	}
1967 
1968 	for (i = 0; i < ARRAY_SIZE(thp7312_sensor_info); i++) {
1969 		const struct thp7312_sensor_info *info =
1970 			&thp7312_sensor_info[i];
1971 
1972 		if (!strcmp(info->model, model)) {
1973 			sensor->info = info;
1974 			break;
1975 		}
1976 	}
1977 
1978 	if (!sensor->info) {
1979 		dev_err(dev, "Unsupported sensor model %s\n", model);
1980 		return -EINVAL;
1981 	}
1982 
1983 	ret = fwnode_property_read_u32_array(node, "data-lanes", values,
1984 					     ARRAY_SIZE(values));
1985 	if (ret < 0) {
1986 		dev_err(dev, "Failed to read property data-lanes: %d\n", ret);
1987 		return ret;
1988 	}
1989 
1990 	for (i = 0; i < ARRAY_SIZE(data_lanes); ++i)
1991 		data_lanes[i] = values[i];
1992 
1993 	ret = thp7312_map_data_lanes(&sensor->lane_remap, data_lanes,
1994 				     ARRAY_SIZE(data_lanes));
1995 	if (ret) {
1996 		dev_err(dev, "Invalid sensor@%u data-lanes value\n", reg);
1997 		return ret;
1998 	}
1999 
2000 	return 0;
2001 }
2002 
2003 static int thp7312_parse_dt(struct thp7312_device *thp7312)
2004 {
2005 	struct v4l2_fwnode_endpoint ep = {
2006 		.bus_type = V4L2_MBUS_CSI2_DPHY,
2007 	};
2008 	struct device *dev = thp7312->dev;
2009 	struct fwnode_handle *endpoint;
2010 	struct fwnode_handle *sensors;
2011 	unsigned int num_sensors = 0;
2012 	struct fwnode_handle *node;
2013 	int ret;
2014 
2015 	endpoint = fwnode_graph_get_next_endpoint(dev_fwnode(dev), NULL);
2016 	if (!endpoint)
2017 		return dev_err_probe(dev, -EINVAL, "Endpoint node not found\n");
2018 
2019 	ret = v4l2_fwnode_endpoint_parse(endpoint, &ep);
2020 	fwnode_handle_put(endpoint);
2021 	if (ret)
2022 		return dev_err_probe(dev, ret, "Could not parse endpoint\n");
2023 
2024 	ret = thp7312_map_data_lanes(&thp7312->lane_remap,
2025 				     ep.bus.mipi_csi2.data_lanes,
2026 				     ep.bus.mipi_csi2.num_data_lanes);
2027 	if (ret) {
2028 		dev_err(dev, "Invalid data-lanes value\n");
2029 		return ret;
2030 	}
2031 
2032 	/*
2033 	 * The thine,boot-mode property is optional and default to
2034 	 * THP7312_BOOT_MODE_SPI_MASTER (1).
2035 	 */
2036 	thp7312->boot_mode = THP7312_BOOT_MODE_SPI_MASTER;
2037 	ret = device_property_read_u32(dev, "thine,boot-mode",
2038 				       &thp7312->boot_mode);
2039 	if (ret && ret != -EINVAL)
2040 		return dev_err_probe(dev, ret, "Property '%s' is invalid\n",
2041 				     "thine,boot-mode");
2042 
2043 	if (thp7312->boot_mode != THP7312_BOOT_MODE_2WIRE_SLAVE &&
2044 	    thp7312->boot_mode != THP7312_BOOT_MODE_SPI_MASTER)
2045 		return dev_err_probe(dev, -EINVAL, "Invalid '%s' value %u\n",
2046 				     "thine,boot-mode", thp7312->boot_mode);
2047 
2048 	/* Sensors */
2049 	sensors = device_get_named_child_node(dev, "sensors");
2050 	if (!sensors) {
2051 		dev_err(dev, "'sensors' child node not found\n");
2052 		return -EINVAL;
2053 	}
2054 
2055 	fwnode_for_each_available_child_node(sensors, node) {
2056 		if (fwnode_name_eq(node, "sensor")) {
2057 			if (!thp7312_sensor_parse_dt(thp7312, node))
2058 				num_sensors++;
2059 		}
2060 	}
2061 
2062 	fwnode_handle_put(sensors);
2063 
2064 	if (!num_sensors) {
2065 		dev_err(dev, "No sensor found\n");
2066 		return -EINVAL;
2067 	}
2068 
2069 	return 0;
2070 }
2071 
2072 static int thp7312_probe(struct i2c_client *client)
2073 {
2074 	struct device *dev = &client->dev;
2075 	struct v4l2_subdev_state *sd_state;
2076 	struct thp7312_device *thp7312;
2077 	int ret;
2078 
2079 	thp7312 = devm_kzalloc(dev, sizeof(*thp7312), GFP_KERNEL);
2080 	if (!thp7312)
2081 		return -ENOMEM;
2082 
2083 	thp7312->dev = dev;
2084 
2085 	thp7312->regmap = devm_cci_regmap_init_i2c(client, 16);
2086 	if (IS_ERR(thp7312->regmap))
2087 		return dev_err_probe(dev, PTR_ERR(thp7312->regmap),
2088 				     "Unable to initialize I2C\n");
2089 
2090 	ret = thp7312_parse_dt(thp7312);
2091 	if (ret < 0)
2092 		return ret;
2093 
2094 	ret = thp7312_get_regulators(thp7312);
2095 	if (ret)
2096 		return dev_err_probe(dev, ret, "Failed to get regulators\n");
2097 
2098 	thp7312->iclk = devm_clk_get(dev, NULL);
2099 	if (IS_ERR(thp7312->iclk))
2100 		return dev_err_probe(dev, PTR_ERR(thp7312->iclk),
2101 				     "Failed to get iclk\n");
2102 
2103 	thp7312->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_HIGH);
2104 	if (IS_ERR(thp7312->reset_gpio))
2105 		return dev_err_probe(dev, PTR_ERR(thp7312->reset_gpio),
2106 				     "Failed to get reset gpio\n");
2107 
2108 	if (thp7312->boot_mode == THP7312_BOOT_MODE_2WIRE_SLAVE)
2109 		return thp7312_register_flash_mode(thp7312);
2110 
2111 	v4l2_i2c_subdev_init(&thp7312->sd, client, &thp7312_subdev_ops);
2112 	thp7312->sd.internal_ops = &thp7312_internal_ops;
2113 	thp7312->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS;
2114 	thp7312->pad.flags = MEDIA_PAD_FL_SOURCE;
2115 	thp7312->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR;
2116 
2117 	ret = media_entity_pads_init(&thp7312->sd.entity, 1, &thp7312->pad);
2118 	if (ret)
2119 		return ret;
2120 
2121 	/*
2122 	 * Enable power management. The driver supports runtime PM, but needs to
2123 	 * work when runtime PM is disabled in the kernel. To that end, power
2124 	 * the device manually here.
2125 	 */
2126 	ret = thp7312_power_on(thp7312);
2127 	if (ret)
2128 		goto err_entity_cleanup;
2129 
2130 	ret = thp7312_read_firmware_version(thp7312);
2131 	if (ret < 0) {
2132 		dev_err(dev, "Camera is not found\n");
2133 		goto err_power_off;
2134 	}
2135 
2136 	ret = thp7312_init_controls(thp7312);
2137 	if (ret) {
2138 		dev_err(dev, "Failed to initialize controls\n");
2139 		goto err_power_off;
2140 	}
2141 
2142 	thp7312->sd.ctrl_handler = &thp7312->ctrl_handler;
2143 	thp7312->sd.state_lock = thp7312->ctrl_handler.lock;
2144 
2145 	ret = v4l2_subdev_init_finalize(&thp7312->sd);
2146 	if (ret < 0) {
2147 		dev_err(dev, "Subdev active state initialization failed\n");
2148 		goto err_free_ctrls;
2149 	}
2150 
2151 	sd_state = v4l2_subdev_lock_and_get_active_state(&thp7312->sd);
2152 	thp7312->current_mode = &thp7312_mode_info_data[0];
2153 	thp7312_set_frame_rate(thp7312, &thp7312->current_mode->rates[0]);
2154 	v4l2_subdev_unlock_state(sd_state);
2155 
2156 	/*
2157 	 * Enable runtime PM with autosuspend. As the device has been powered
2158 	 * manually, mark it as active, and increase the usage count without
2159 	 * resuming the device.
2160 	 */
2161 	pm_runtime_set_active(dev);
2162 	pm_runtime_get_noresume(dev);
2163 	pm_runtime_enable(dev);
2164 	pm_runtime_set_autosuspend_delay(dev, 1000);
2165 	pm_runtime_use_autosuspend(dev);
2166 
2167 	ret = v4l2_async_register_subdev(&thp7312->sd);
2168 	if (ret < 0) {
2169 		dev_err(dev, "Subdev registration failed\n");
2170 		goto err_pm;
2171 	}
2172 
2173 	/*
2174 	 * Decrease the PM usage count. The device will get suspended after the
2175 	 * autosuspend delay, turning the power off.
2176 	 */
2177 	pm_runtime_mark_last_busy(dev);
2178 	pm_runtime_put_autosuspend(dev);
2179 
2180 	dev_info(dev, "THP7312 firmware version %02u.%02u\n",
2181 		 THP7312_FW_VERSION_MAJOR(thp7312->fw_version),
2182 		 THP7312_FW_VERSION_MINOR(thp7312->fw_version));
2183 
2184 	return 0;
2185 
2186 err_pm:
2187 	pm_runtime_disable(dev);
2188 	pm_runtime_put_noidle(dev);
2189 	v4l2_subdev_cleanup(&thp7312->sd);
2190 err_free_ctrls:
2191 	v4l2_ctrl_handler_free(&thp7312->ctrl_handler);
2192 err_power_off:
2193 	thp7312_power_off(thp7312);
2194 err_entity_cleanup:
2195 	media_entity_cleanup(&thp7312->sd.entity);
2196 	return ret;
2197 }
2198 
2199 static void thp7312_remove(struct i2c_client *client)
2200 {
2201 	struct v4l2_subdev *sd = i2c_get_clientdata(client);
2202 	struct thp7312_device *thp7312 = to_thp7312_dev(sd);
2203 
2204 	if (thp7312->boot_mode == THP7312_BOOT_MODE_2WIRE_SLAVE) {
2205 		firmware_upload_unregister(thp7312->fwl);
2206 		__thp7312_power_off(thp7312);
2207 		return;
2208 	}
2209 
2210 	v4l2_async_unregister_subdev(&thp7312->sd);
2211 	v4l2_subdev_cleanup(&thp7312->sd);
2212 	media_entity_cleanup(&thp7312->sd.entity);
2213 	v4l2_ctrl_handler_free(&thp7312->ctrl_handler);
2214 
2215 	/*
2216 	 * Disable runtime PM. In case runtime PM is disabled in the kernel,
2217 	 * make sure to turn power off manually.
2218 	 */
2219 	pm_runtime_disable(thp7312->dev);
2220 	if (!pm_runtime_status_suspended(thp7312->dev))
2221 		thp7312_power_off(thp7312);
2222 	pm_runtime_set_suspended(thp7312->dev);
2223 }
2224 
2225 static const struct of_device_id thp7312_dt_ids[] = {
2226 	{ .compatible = "thine,thp7312" },
2227 	{ /* sentinel */ }
2228 };
2229 MODULE_DEVICE_TABLE(of, thp7312_dt_ids);
2230 
2231 static struct i2c_driver thp7312_i2c_driver = {
2232 	.driver = {
2233 		.name  = "thp7312",
2234 		.pm = &thp7312_pm_ops,
2235 		.of_match_table	= thp7312_dt_ids,
2236 	},
2237 	.probe = thp7312_probe,
2238 	.remove = thp7312_remove,
2239 };
2240 
2241 module_i2c_driver(thp7312_i2c_driver);
2242 
2243 MODULE_DESCRIPTION("THP7312 MIPI Camera Subdev Driver");
2244 MODULE_LICENSE("GPL");
2245