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