File Index
Files and directories
Sign in
FILE

thp7312.c

File preview with syntax highlighting.

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