onsemi-core.c 74.3 KB
Newer Older
Enrico Scholz's avatar
Enrico Scholz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
/* SPDX-License-Identifier: GPL-2.0-or-later */

/*
 * Generic part of ONSemi ARxxx sensor drivers.
 *
 * Copyright (C) 2018 Enrico Scholz <enrico.scholz@sigma-chemnitz.de>
 */

#include "onsemi-core.h"

#include <linux/module.h>
#include <linux/errno.h>
#include <linux/debugfs.h>
#include <linux/i2c.h>
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/regmap.h>
#include <linux/thermal.h>

#include <linux/of_graph.h>

#include <linux/regulator/consumer.h>
#include <linux/gpio/consumer.h>

#include <media/v4l2-ctrls.h>
#include <media/v4l2-fwnode.h>

#include "onsemi-regmap.h"
#include "onsemi-reg.h"

#define IS_PWR2(_v)	(((_v) & ((_v) - 1u)) == 0)

static s64 const	S64_ZERO;

static bool is_pwr2(unsigned long v)
{
	return (v & (v - 1lu)) == 0;
}

static int onsemi_get_regulator(struct device *dev, char const *name,
				struct regulator **reg)
{
	struct regulator		*res;
	int				rc;

	res = devm_regulator_get(dev, name);
	if (IS_ERR(reg)) {
		rc = PTR_ERR(reg);
		dev_probe_err(dev, rc, "failed to get %s regulator: %d\n",
			      name, rc);
		goto out;
	}

	*reg = res;
	rc = 0;

out:
	return rc;
}

static int onsemi_core_of_bus_init_ep(struct onsemi_core *onsemi,
				      struct device_node *np,
				      struct onsemi_businfo *info)
{
	struct v4l2_fwnode_endpoint	*endpoint = NULL;
	int				rc;
	int32_t				tmp;

	if (info->is_used) {
		dev_warn(onsemi->dev, "ep already initialized\n");
		return -EINVAL;
	}

	endpoint = v4l2_fwnode_endpoint_alloc_parse(of_fwnode_handle(np));
	rc = PTR_ERR_OR_ZERO(endpoint);
	if (rc < 0) {
		dev_warn(onsemi->dev, "failed to parse ep:%d\n", rc);
		return rc;
	}

	/* 'endpoint.bus.parallel.data_shift' can not be used because it is
	 * unsigned but we require signed */
	if (of_property_read_s32(np, "onsemi,data-shift", &tmp) < 0)
		info->dout_sft = 0;
	else
		info->dout_sft = tmp;

	if (of_property_read_s32(np, "onsemi,slew-rate-dat", &tmp) < 0)
		info->slew_rate_dat = ONSEMI_NO_SLEW_RATE;
	else
		info->slew_rate_dat = tmp;

	if (of_property_read_s32(np, "onsemi,slew-rate-clk", &tmp) < 0)
		info->slew_rate_clk = ONSEMI_NO_SLEW_RATE;
	else
		info->slew_rate_clk = tmp;

	info->bus_type = endpoint->bus_type;

	if (endpoint->nr_of_link_frequencies > 0)
		info->max_freq = endpoint->link_frequencies[0];
	else
		info->max_freq = 0;

	switch (endpoint->bus_type) {
	case V4L2_MBUS_PARALLEL:
		info->bus_width = endpoint->bus.parallel.bus_width;
		rc = 0;
		break;

	case V4L2_MBUS_CSI2:
		info->bus_width = endpoint->bus.mipi_csi2.num_data_lanes;
		rc = 0;
		break;

	default:
		dev_warn(onsemi->dev, "unsupported v4l bus type %d\n",
			 endpoint->bus_type);
		rc = -EINVAL;
		break;
	}

	if (rc < 0)
		goto out;

	info->is_used  = true;
	rc = 0;

out:
	v4l2_fwnode_endpoint_free(endpoint);
	return rc;
}

static int onsemi_core_of_bus_init(struct device *dev,
				   struct onsemi_core *onsemi)
{
	int			rc = 0;
	struct device_node	*np = NULL;
	bool			missing_reg_prop = false;
	bool			have_reg_prop = false;

	for (;;) {
		uint32_t		reg;

		np = of_graph_get_next_endpoint(dev->of_node, np);
		if (!np)
			break;

		if (of_property_read_u32(np->parent, "reg", &reg) >= 0) {
			have_reg_prop = true;
		} else {
			missing_reg_prop = true;
			reg = 0;
		}

		if (reg >= ARRAY_SIZE(onsemi->bus_info)) {
			dev_warn(dev, "endpoint reg %u out of range\n", reg);
			rc = -EINVAL;
			break;
		}

		rc = onsemi_core_of_bus_init_ep(onsemi, np,
						&onsemi->bus_info[reg]);
		if (rc < 0) {
			dev_warn(dev, "bad ep#%d", reg);
			break;
		}
	}

	of_node_put(np);

	if (missing_reg_prop && have_reg_prop)
		dev_warn(dev, "endpoint without reg property\n");

	return rc;
}

static int onsemi_core_of_init(struct device *dev, struct onsemi_core *onsemi)
{
	struct gpio_desc	*gpio;
	struct clk		*clk;
	int			rc;

	rc = onsemi_core_of_bus_init(dev, onsemi);
	if (rc < 0)
		goto out;

	rc = onsemi_get_regulator(dev, "vdd", &onsemi->reg_vdd);
	if (rc < 0)
		goto out;

	rc = onsemi_get_regulator(dev, "vddio", &onsemi->reg_vddio);
	if (rc < 0)
		goto out;

	rc = onsemi_get_regulator(dev, "vaa", &onsemi->reg_vaa);
	if (rc < 0)
		goto out;

	rc = onsemi_get_regulator(dev, "vaapix", &onsemi->reg_vaapix);
	if (rc < 0)
		goto out;

	gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH);
	rc = PTR_ERR_OR_ZERO(gpio);
	if (rc < 0) {
		dev_probe_err(dev, rc, "failed to get rst gpio: %d\n", rc);
		goto out;
	}
	onsemi->rst_gpio = gpio;

	clk = devm_clk_get(dev, "ext");
	rc = PTR_ERR_OR_ZERO(clk);
	if (rc < 0) {
		if (rc != -EPROBE_DEFER)
			dev_probe_err(dev, rc, "failed to get ext clock: %d\n", rc);
		goto out;
	}
	onsemi->extclk = clk;

	/* Support for 'synch' clock is hacky and required only for special
	 * hardware (e.g. Phytec Nunki Board with LVDS deserializer) */
	clk = devm_clk_get(dev, "synch");
	rc = PTR_ERR_OR_ZERO(clk);
	if (rc == -ENOENT) {
		clk = NULL;
	} else if (rc < 0) {
		if (rc != -EPROBE_DEFER)
			dev_probe_err(dev, rc, "failed to get synch clock: %d\n", rc);
		goto out;
	}
	onsemi->synchclk = clk;

	rc = 0;

out:
	return rc;
}

static bool in_range(char const *id, struct onsemi_range const *r, unsigned long v)
{
	if (!r)
		return true;

	if (v < r->min || v > r->max) {
		pr_debug("%s: '%s' (%lu) out of range [%lu, %lu]\n", __func__,
			 id, v, r->min, r->max);
		return false;
	}

	return true;
}

static int onsemi_core_pll_set(struct onsemi_core *onsemi,
			       struct onsemi_pll_cfg const *cfg,
			       struct onsemi_pll_freq const *freq)
{
	int				rc = 0;

	if (onsemi->synchclk &&
	    !test_and_clear_bit(ONSEMI_FLAG_SYNCCLK_ON, &onsemi->flags)) {
		int	rc;

		rc = clk_set_rate(onsemi->synchclk, onsemi->pll_freq->link_freq);
		if (rc < 0) {
			v4l2_warn(&onsemi->subdev,
				  "failed to set sync clk rate to %llu: %d\n",
				  onsemi->pll_freq->link_freq, rc);
			goto syncclk_out;
		}

		rc = clk_prepare_enable(onsemi->synchclk);
		if (rc < 0) {
			v4l2_warn(&onsemi->subdev,
				  "failed to enable sync clk: %d\n", rc);
			goto syncclk_out;
		}

	syncclk_out:
		if (rc < 0)
			clear_bit(ONSEMI_FLAG_SYNCCLK_ON, &onsemi->flags);

		/* ignore errors regarding synchclk setup */
		rc = 0;
	}

	if (onsemi->ops->pll_set)
		rc = onsemi->ops->pll_set(onsemi, cfg, freq);
	else
		rc = 0;

	if (rc < 0) {
		dev_warn(onsemi->dev, "failed to set PLL: %d\n", rc);
		goto out;
	}

	dev_dbg(onsemi->dev,
		"CLK: ext=%lu, vco=%lu, vt=[%lu, %lu, %lu], op=[%lu, %lu, %lu]\n",
		freq->ext,    freq->vco,
		freq->vt_sys, freq->vt_pix, freq->clk_pixel,
		freq->op_sys, freq->op_pix, freq->clk_op);

	rc = 0;


out:
	return rc;
}

static int _onsemi_power_reset(struct onsemi_core *sensor, bool do_assert)
{
	int			rc = 0;

	dbg_trace_pwr("%sasserting reset\n", do_assert ? "" : "de");

	if (sensor->rst_gpio) {
		gpiod_set_value_cansleep(sensor->rst_gpio, do_assert);
	} else if (!do_assert) {
		onsemi_write(&rc, sensor,
			     ONSEMI_REGMAP_8BIT_REG_TO_ADDR(0x3021), 1);

		if (rc < 0)
			dev_warn(sensor->dev,
				 "failed to initiate software reset: %d\n", rc);
	} else {
		rc = 0;
	}

	rc = 0;

	if (do_assert) {
		/* TODO: this is not really correct; we do not have an
		 * explicit STOP state */
		usleep_range(10, 10000); /* t_101 */
	} else {
		msleep(100);		/* t_5 = 45000 EXTCLKs */

		regcache_mark_dirty(sensor->regmap);
	}

	return rc;
}

static int _onsemi_power_off(struct onsemi_core *sensor)
{
	WARN_ON(sensor->pwr_state != ONSEMI_PWR_RST);

	clk_disable_unprepare(sensor->extclk);

	if (!sensor->ops->vaa_first) {
		regulator_disable(sensor->reg_vaapix);
		regulator_disable(sensor->reg_vaa);

		msleep(20);
	}

	regulator_disable(sensor->reg_vdd);

	msleep(20);

	regulator_disable(sensor->reg_vddio);

	msleep(20);

	if (sensor->ops->vaa_first) {
		regulator_disable(sensor->reg_vaapix);
		regulator_disable(sensor->reg_vaa);

		msleep(20);
	}

	return 0;
}

static int _onsemi_power_on(struct onsemi_core *sensor)
{
	int		rc;

	WARN_ON(sensor->pwr_state != ONSEMI_PWR_OFF);

	/* see Figure 15 "Power-Up Sequence" and Table 16 "Power-Up Sequence"
	 * for details */

	if (sensor->ops->vaa_first) {
		rc = regulator_enable(sensor->reg_vaa);
		if (rc < 0)
			goto err_vaa;

		rc = regulator_enable(sensor->reg_vaapix);
		if (rc < 0)
			goto err_vaapix;

		usleep_range(4*1500, 4*10000);
	}

	if (sensor->rst_gpio)
		gpiod_set_value_cansleep(sensor->rst_gpio, 1);

	rc = regulator_enable(sensor->reg_vddio);
	if (rc < 0)
		goto err_vddio;

	usleep_range(4*1500, 4*10000);

	rc = regulator_enable(sensor->reg_vdd);
	if (rc < 0)
		goto err_vdd;

	usleep_range(4*1500, 4*10000);

	if (!sensor->ops->vaa_first) {
		rc = regulator_enable(sensor->reg_vaa);
		if (rc < 0)
			goto err_vaa;

		rc = regulator_enable(sensor->reg_vaapix);
		if (rc < 0)
			goto err_vaapix;

		usleep_range(4*1500, 4*10000);
	}

	rc = clk_prepare_enable(sensor->extclk);
	if (rc < 0)
		goto err_extclk;

	sensor->ext_clk_freq = clk_get_rate(sensor->extclk);

	usleep_range(4*1500, 4*10000);
	regcache_mark_dirty(sensor->regmap);

	return 0;

err_extclk:

	regulator_disable(sensor->reg_vaapix);
err_vaapix:

	regulator_disable(sensor->reg_vaa);
err_vaa:

	regulator_disable(sensor->reg_vdd);
err_vdd:

	regulator_disable(sensor->reg_vddio);
err_vddio:

	return rc;
}

static int onsemi_power_change_unlocked(struct onsemi_core *sensor,
					enum onsemi_pwr_state state)
{
	enum onsemi_state_fn {
		ONSEMI_FN_NONE,
		ONSEMI_FN_ON,
		ONSEMI_FN_OFF,
		ONSEMI_FN_RST_ASSERT,
		ONSEMI_FN_RST_DEASSERT,
	};

	struct onsemi_state_transition {
		enum onsemi_state_fn	fn;
		enum onsemi_pwr_state	next;
	};

	static struct onsemi_state_transition const	STATES[3][3] = {
		[ONSEMI_PWR_OFF] = {
			[ONSEMI_PWR_OFF]	= {
				.fn	= ONSEMI_FN_NONE,
				.next	= ONSEMI_PWR_OFF,
			},
			[ONSEMI_PWR_ON]		= {
				.fn	= ONSEMI_FN_ON,
				.next	= ONSEMI_PWR_RST,
			},
			[ONSEMI_PWR_RST]	= {
				.fn	= ONSEMI_FN_ON,
				.next	= ONSEMI_PWR_RST,
			},
		},

		[ONSEMI_PWR_RST] = {
			[ONSEMI_PWR_OFF]	= {
				.fn	= ONSEMI_FN_OFF,
				.next	= ONSEMI_PWR_OFF,
			},
			[ONSEMI_PWR_ON]		= {
				.fn	= ONSEMI_FN_RST_DEASSERT,
				.next	= ONSEMI_PWR_ON,
			},
			[ONSEMI_PWR_RST]	= {
				.fn	= ONSEMI_FN_NONE,
				.next	= ONSEMI_PWR_RST,
			},
		},

		/* TODO: this violates "Figure 16 "Power-Down sequence which
		 * has an extra STOP state where clock is disabled and RESET
		 * deasserted */
		[ONSEMI_PWR_ON] = {
			[ONSEMI_PWR_OFF]	= {
				.fn	= ONSEMI_FN_RST_ASSERT,
				.next	= ONSEMI_PWR_RST,
			},
			[ONSEMI_PWR_ON]		= {
				.fn	= ONSEMI_FN_NONE,
				.next	= ONSEMI_PWR_ON,
			},
			[ONSEMI_PWR_RST]	= {
				.fn	= ONSEMI_FN_RST_ASSERT,
				.next	= ONSEMI_PWR_RST,
			},
		},
	};


	int		rc;

	dbg_trace_pwr("power-state %d -> %d\n", sensor->pwr_state, state);

	while (state != sensor->pwr_state) {
		struct onsemi_state_transition const	*trans =
			&STATES[sensor->pwr_state][state];

		switch (trans->fn) {
		case ONSEMI_FN_NONE:
			rc = 0;
			break;

		case ONSEMI_FN_ON:
			rc = _onsemi_power_on(sensor);
			break;

		case ONSEMI_FN_OFF:
			rc = _onsemi_power_off(sensor);
			break;

		case ONSEMI_FN_RST_ASSERT:
			rc = _onsemi_power_reset(sensor, true);
			break;

		case ONSEMI_FN_RST_DEASSERT:
			rc = _onsemi_power_reset(sensor, false);
			break;

		default:
			BUG();
			break;
		}

		if (rc < 0)
			break;

		sensor->pwr_state = trans->next;
	}

	if (rc < 0)
		goto out;

	rc = 0;

out:
	if (rc < 0) {
		dev_err(sensor->dev, "failed to change power (%d): %d\n",
			state, rc);
	}

	return rc;
}

static int onsemi_power_change(struct onsemi_core *sensor,
			       enum onsemi_pwr_state state)
{
	int		rc;

	mutex_lock(&sensor->lock);
	rc = onsemi_power_change_unlocked(sensor, state);
	mutex_unlock(&sensor->lock);

	return rc;
}

int onsemi_power_get(struct onsemi_core *sensor)
{
	int	rc;
	int	num_users;

	num_users = atomic_inc_return(&sensor->num_pwr_users);

	dbg_trace_pwr("num_users=%d\n", num_users);

	if (WARN_ON(num_users <= 0))
		rc = -EINVAL;
	else if (num_users == 1)
		rc = onsemi_power_change(sensor, ONSEMI_PWR_ON);
	else
		rc = 0;

	return rc;
}
EXPORT_SYMBOL_GPL(onsemi_power_get);

void onsemi_power_put(struct onsemi_core *sensor)
{
	int	num_users;

	num_users = atomic_dec_return(&sensor->num_pwr_users);

	WARN_ON(num_users < 0);

	if (num_users == 0)
		onsemi_power_change(sensor, ONSEMI_PWR_OFF);
}
EXPORT_SYMBOL_GPL(onsemi_power_put);

617 618 619 620 621 622 623 624
#define attribute_typeof(_struct, _attr)	__typeof__(&((_struct *)0)->_attr)
#define attribute_types_compatible(_type, _struct, _attr) \
	(__builtin_types_compatible_p(attribute_typeof(_struct, _attr), _type *))

#define offsetof_t(_type, _struct, _attr)				\
	(BUILD_BUG_ON_ZERO(!attribute_types_compatible(_type, _struct, _attr)) + \
	 offsetof(_struct, _attr))

Enrico Scholz's avatar
Enrico Scholz committed
625 626 627 628
#define DECL_LIMIT(_reg, _attr)						\
	{								\
		.reg = _reg,						\
		.name	= # _attr,					\
629 630
		.ofs	= offsetof_t(unsigned long,			\
				     struct onsemi_limits, _attr),	\
Enrico Scholz's avatar
Enrico Scholz committed
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
	}

static struct {
	char const	*name;
	uint16_t	reg;
	size_t		ofs;
} const		ONSEMI_LIMITS[] = {
	DECL_LIMIT(0x1120, pll_vt_sys_clk_div.min),
	DECL_LIMIT(0x1122, pll_vt_sys_clk_div.max),
	DECL_LIMIT(0x1134, pll_vt_pix_clk_div.min),
	DECL_LIMIT(0x1136, pll_vt_pix_clk_div.max),

	DECL_LIMIT(0x1140, vlen.min),
	DECL_LIMIT(0x1142, vlen.max),
	DECL_LIMIT(0x1144, hlen.min),
	DECL_LIMIT(0x1146, hlen.max),
	DECL_LIMIT(0x1148, hblank_min),
	DECL_LIMIT(0x114a, vblank_min),

	DECL_LIMIT(0x1180, x.min),
	DECL_LIMIT(0x1182, y.min),
	DECL_LIMIT(0x1184, x.max),
	DECL_LIMIT(0x1186, y.max),

	DECL_LIMIT(0x1160, pll_op_sys_clk_div.min),
	DECL_LIMIT(0x1162, pll_op_sys_clk_div.max),
	DECL_LIMIT(0x116c, pll_op_pix_clk_div.min),
	DECL_LIMIT(0x116e, pll_op_pix_clk_div.max),

	DECL_LIMIT(0x1114, pre_pll_mul.min),
	DECL_LIMIT(0x1116, pre_pll_mul.max),
	DECL_LIMIT(0x1108, pre_pll_div.min),
	DECL_LIMIT(0x110a, pre_pll_div.max),

	DECL_LIMIT(0xffff, pix_clk.min),
	DECL_LIMIT(0xffff, pix_clk.max),

	DECL_LIMIT(0xffff, pix_clk.min),
	DECL_LIMIT(0xffff, pix_clk.max),
};

#undef DECL_LIMIT

static void onsemi_core_debugfs_release(struct device *dev, void *dentry_)
{
	struct dentry	**dentry = dentry_;

	debugfs_remove_recursive(*dentry);
}

static int onsemi_core_debugfs_init(struct onsemi_core *onsemi)
{
	struct dentry	**d_top_ctx;
	struct dentry	*d_top;
	struct dentry	*d_limits;
	size_t		i;
	int		rc;

	if (!IS_ENABLED(CONFIG_DEBUG_FS))
		return 0;

	d_top_ctx = devres_alloc(onsemi_core_debugfs_release, sizeof *d_top_ctx,
				 GFP_KERNEL);
	if (!d_top_ctx)
		return -ENOMEM;

	d_top = debugfs_create_dir(dev_name(onsemi->dev), NULL);
	rc = PTR_ERR_OR_ZERO(d_top);
	if (rc < 0) {
		dev_err(onsemi->dev, "failed to create toplevel debugfs: %d\n",
			rc);
		d_top = NULL;
		goto out;
	}

	d_limits = debugfs_create_dir("limits", d_top);
	rc = PTR_ERR_OR_ZERO(d_limits);
	if (rc < 0) {
		dev_err(onsemi->dev, "failed to create 'limits' debugfs: %d\n",
			rc);
		goto out;
	}

	for (i = 0; i < ARRAY_SIZE(ONSEMI_LIMITS); ++i) {
		uintptr_t	tmp = (uintptr_t)onsemi->limits;

		tmp += ONSEMI_LIMITS[i].ofs;

		debugfs_create_ulong(ONSEMI_LIMITS[i].name, 0444, d_limits,
				     (unsigned long *)tmp);
	}

	onsemi->debugfs_top = d_top;
	onsemi->debugfs_limits = d_limits;

	*d_top_ctx = d_top;
	devres_add(onsemi->dev, d_top_ctx);

	rc = 0;

out:
	if (rc < 0) {
		debugfs_remove_recursive(d_top);
		devres_free(d_top_ctx);
	}

	return rc;
}

#undef DECL_LIMIT

void onsemi_core_release(struct onsemi_core *onsemi)
{
	v4l2_async_unregister_subdev(&onsemi->subdev);
	media_entity_cleanup(&onsemi->subdev.entity);
	v4l2_ctrl_handler_free(&onsemi->ctrls);
}
EXPORT_SYMBOL_GPL(onsemi_core_release);

int onsemi_core_init(struct i2c_client *i2c,
		     struct onsemi_core *onsemi,
		     struct onsemi_dev_cfg const *cfg)
{
	int		rc;

	if (WARN_ON(!cfg || !cfg->ops || !cfg->regmap_config)) {
		dev_err(&i2c->dev, "missing/bad device config\n");
		rc = -EINVAL;
		goto out;
	}

#if 0
	if (WARN_ON(!cfg->ops->get_v4l_parm)) {
		dev_err(&i2c->dev, "bad device ops\n");
		rc = -EINVAL;
		goto out;
	}
#endif

	*onsemi = (struct onsemi_core) {
		.dev		= &i2c->dev,
		.pwr_state	= ONSEMI_PWR_OFF,
		.num_pwr_users	= ATOMIC_INIT(0),
		.num_v4lpwr_users = ATOMIC_INIT(0),
		.ops		= cfg->ops,
		.limits		= cfg->limits,
		.lock		= __MUTEX_INITIALIZER(onsemi->lock),
	};

	if (!onsemi->limits) {
		struct onsemi_limits	*limits = cfg->limits_buf;

		if (!limits)
			limits = devm_kzalloc(onsemi->dev, sizeof *limits,
					      GFP_KERNEL);

		if (!limits) {
			dev_err(onsemi->dev,
				"failed to allocate buffer for limits\n");
			rc = -ENOMEM;
			goto out;
		}

		onsemi->limits = limits;
		onsemi->dyn_limits = limits;
	}

	rc = onsemi_core_of_init(onsemi->dev, onsemi);
	if (rc < 0) {
		dev_err(onsemi->dev, "bad/missing dtree setup: %d\n", rc);
		goto out;
	}

	onsemi->regmap = devm_regmap_init_onsemi(i2c, cfg->regmap_config);
	rc = PTR_ERR_OR_ZERO(onsemi->regmap);
	if (rc < 0) {
		dev_err(onsemi->dev, "failed to initialized regmap: %d\n", rc);
		goto out;
	}

	rc = onsemi_core_debugfs_init(onsemi);
	if (rc < 0) {
		dev_err(onsemi->dev, "failed to create debugfs: %d\n", rc);
		goto out;
	};

	rc = 0;

out:
	return rc;
}
EXPORT_SYMBOL_GPL(onsemi_core_init);

#define DECL_LIMIT(_reg, _fld)						\
	{								\
		.reg = _reg,						\
		.ofs = offsetof(struct onsemi_limits, _fld),		\
	}

static int onsemi_core_read_limits(struct onsemi_core *onsemi,
				   struct onsemi_limits *limits)
{
	size_t		i;
	int		rc = 0;

	for (i = 0; i < ARRAY_SIZE(ONSEMI_LIMITS); ++i) {
		unsigned long	tmp;
		uintptr_t	dst = (uintptr_t)(limits);

		if (ONSEMI_LIMITS[i].reg == 0xffff)
			continue;

		tmp = onsemi_read(&rc, onsemi, ONSEMI_LIMITS[i].reg);
		if (rc < 0)
			break;

		dst += ONSEMI_LIMITS[i].ofs;
		memcpy((void *)dst, &tmp, sizeof tmp);
	}

	if (rc < 0) {
		dev_warn(onsemi->dev, "failed to read sensor limits: %d\n", rc);
		goto out;
	}

	rc = 0;

out:
	return rc;
}

#undef DECL_LIMIT

static unsigned long onsemi_clk_div_mul(unsigned long freq,
					unsigned int div,
					unsigned int mul)
{
	uint64_t	res;

	if (WARN_ON(div == 0))
		return 0;

	res  = freq;
	res *= mul;
	res  = div_u64(res, div);

	return res;
}

static ssize_t onsemi_core_show_version_chip(
	struct device *dev, struct device_attribute *attr, char *buf)
{
	struct v4l2_subdev	*sd = dev_get_drvdata(dev);
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);

	return sprintf(buf, "0x%04x\n", onsemi->version.chip);
}

static ssize_t onsemi_core_show_version_rev(
	struct device *dev, struct device_attribute *attr, char *buf)
{
	struct v4l2_subdev	*sd = dev_get_drvdata(dev);
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);

	return sprintf(buf, "0x%04x\n", onsemi->version.rev);
}

static ssize_t onsemi_core_show_version_cust(
	struct device *dev, struct device_attribute *attr, char *buf)
{
	struct v4l2_subdev	*sd = dev_get_drvdata(dev);
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);

	return sprintf(buf, "0x%04x\n", onsemi->version.cust);
}


static struct device_attribute const	ONSEMI_CORE_DEV_ATTRS[] = {
	{
		.attr	= {
			.name	= "version-chip",
			.mode	= 0444,
		},
		.show	= onsemi_core_show_version_chip,
	}, {
		.attr	= {
			.name	= "version-rev",
			.mode	= 0444,
		},
		.show	= onsemi_core_show_version_rev,
	}, {
		.attr	= {
			.name	= "version-cust",
			.mode	= 0444,
		},
		.show	= onsemi_core_show_version_cust,
	},
};

static struct attribute const * const	ONSEMI_CORE_ATTRS[] = {
	&ONSEMI_CORE_DEV_ATTRS[0].attr,
	&ONSEMI_CORE_DEV_ATTRS[1].attr,
	&ONSEMI_CORE_DEV_ATTRS[2].attr,

	NULL,
};

static struct attribute_group const	ONSEMI_CORE_ATTR_GRP = {
	.name		= NULL,
	.attrs		= (struct attribute **)(ONSEMI_CORE_ATTRS),
};

static struct onsemi_core_thermal *
onsemi_core_get_thermal(struct onsemi_core *onsemi)
{
#if IS_ENABLED(CONFIG_THERMAL)
	return &onsemi->thermal;
#else
	return NULL;
#endif
}

static int onsemi_core_get_temp(void *onsemi_, int *res)
{
	struct onsemi_core			*onsemi = onsemi_;
	struct onsemi_core_thermal const	*thermal = onsemi_core_get_thermal(onsemi);
	int			rc;
	uint16_t		ctrl_reg;
	uint16_t		val;

	rc = onsemi_power_get(onsemi);
	if (rc < 0)
		return rc;

	mutex_lock(&onsemi->lock);
	ctrl_reg  = onsemi_read(&rc, onsemi, 0x30b4);

	if ((ctrl_reg & BIT(0)) != 0) {
		val = onsemi_read(&rc, onsemi, 0x30b2);
	} else {
		/* clear conversion + start bits */
		ctrl_reg &= ~(BIT(5) | BIT(4));

		/* power thermal sensor on and clear old value */
		onsemi_write(&rc, onsemi, 0x30b4, ctrl_reg | BIT(0) | BIT(5));
		/* start conversion */
		onsemi_write(&rc, onsemi, 0x30b4, ctrl_reg | BIT(0) | BIT(4));

		/* wait some time */
		udelay(500);
		val = onsemi_read(&rc, onsemi, 0x30b2);

		onsemi_write(&rc, onsemi, 0x30b4, ctrl_reg);
	}

	mutex_unlock(&onsemi->lock);

	dev_dbg(onsemi->dev, "%s: ctrl=%04x, val=%04x\n", __func__,
		ctrl_reg, val);

	if (rc < 0)
		return rc;

	/* first multiplication implies '* 1000 / 1000' scaling */
	*res = thermal->slope * val + thermal->t0;

	return 0;
}

static struct thermal_zone_of_device_ops const	ONSEMI_CORE_THERMAL_OPS = {
	.get_temp	= onsemi_core_get_temp,
};

static int onsemi_core_thermal_init(struct onsemi_core *onsemi)
{
	struct device_node		*np = onsemi->dev->of_node;
	struct onsemi_core_thermal	*thermal = onsemi_core_get_thermal(onsemi);
	struct thermal_zone_device	*tdev;
	int				rc;
	uint16_t			cal;
	int32_t				slope;
	int32_t				t_ref;
	signed long			t0;

	if (!IS_ENABLED(CONFIG_THERMAL))
		return 0;

	rc = 0;
	cal = onsemi_read(&rc, onsemi, 0x30c6);
	if (rc < 0)
		return rc;

	if (of_property_read_s32(np, "thermal,slope", &slope) < 0)
		slope =  700;

	if (of_property_read_s32(np, "thermal,tref", &t_ref) < 0)
		t_ref = 55000;

	if (slope == 0) {
		dev_err(onsemi->dev, "bad thermal slope parameter\n");
		return -EINVAL;
	}

	tdev = devm_thermal_zone_of_sensor_register(onsemi->dev, 0, onsemi,
						    &ONSEMI_CORE_THERMAL_OPS);
	rc = PTR_ERR_OR_ZERO(tdev);
	if (rc == -ENODEV) {
		/* not configured in dtree; ignore it */
		dev_dbg(onsemi->dev, "no thermal zone setup; skipping registration\n");
		return 0;
	}

	if (rc < 0) {
		if (rc != -EPROBE_DEFER)
			dev_err(onsemi->dev, "failed to register thermal device: %d\n", rc);
		return rc;
	}

	t0  = t_ref;
	t0 -= cal * slope;	/* implies '* 1000 / 1000' scaling */

	*thermal = (struct onsemi_core_thermal) {
		.tdev	= tdev,
		.t0	= t0,
		.slope	= slope,
	};

	dev_dbg(onsemi->dev, "thermal: cal=%u, slope=%d, t_ref=%d -> t_0=%ld\n",
		(int)cal, (int)slope, (int)t_ref, t0);

	return 0;
}

int onsemi_core_hw_init(struct onsemi_core *onsemi,
			struct onsemi_dev_cfg const *cfg)
{
	int				rc;
	struct onsemi_core_version	ver;

	rc = onsemi_power_get(onsemi);
	if (rc < 0)
		return rc;

	if (cfg->ops->has_smia_cfg) {
		ver.chip = onsemi_read(&rc, onsemi, 0x0000);
		ver.rev  = onsemi_read(&rc, onsemi,
				       ONSEMI_REGMAP_8BIT_REG_TO_ADDR(0x0002));
		ver.manu = onsemi_read(&rc, onsemi,
				       ONSEMI_REGMAP_8BIT_REG_TO_ADDR(0x0003));
		ver.smia = onsemi_read(&rc, onsemi,
				       ONSEMI_REGMAP_8BIT_REG_TO_ADDR(0x0004));
	} else {
		ver.chip = onsemi_read(&rc, onsemi, 0x3000); /* model_id */
		ver.rev  = onsemi_read(&rc, onsemi, 0x300e);
		ver.manu = 0;
		ver.smia = 0;
	}

	ver.cust = onsemi_read(&rc, onsemi, 0x31fe);

	if (rc < 0) {
		dev_err(onsemi->dev, "failed to read sensor information: %d\n",
			rc);
		goto out;
	}

	if (ver.chip != cfg->chip_version) {
		dev_err(onsemi->dev, "unexpected sensor %04x\n", ver.chip);
		rc = -ENOENT;
		goto out;
	}

	switch (cfg->is_color) {
	case -1:
		if (ver.cust & BIT(4))	/* TODO */
			/* TODO */
			onsemi->color_mode = ONSEMI_COLOR_BAYER;
		else
			onsemi->color_mode = ONSEMI_COLOR_MONOCHROME;

		break;

	case 0:
		onsemi->color_mode = ONSEMI_COLOR_MONOCHROME;
		break;

	case 1:
		onsemi->color_mode = ONSEMI_COLOR_BAYER;
		break;

	default:
		WARN_ON(1);
		rc = -ENOENT;
		goto out;
	}

	if (!onsemi->dyn_limits)
		/* static limits */
		rc = 0;
	else if (onsemi->ops->fill_limits)
		rc = onsemi->ops->fill_limits(onsemi, onsemi->dyn_limits,
					      onsemi_core_read_limits);
	else
		rc = onsemi_core_read_limits(onsemi, onsemi->dyn_limits);

	if (rc < 0) {
		dev_err(onsemi->dev, "failed to read sensor limits\n");
		goto out;
	}

	if (cfg->ops->has_smia_cfg) {
		dev_info(onsemi->dev, "device %04x, rev %d/%d/%d, cust %02x\n",
			 ver.chip, ver.rev, ver.manu, ver.smia, ver.cust);
	} else  {
		dev_info(onsemi->dev, "device %04x, cust %d\n",
			 ver.chip, ver.cust);
	}

	rc = devm_device_add_group(onsemi->dev, &ONSEMI_CORE_ATTR_GRP);
	if (rc < 0)
		goto out;

	rc = onsemi_core_thermal_init(onsemi);
	if (rc < 0)
		goto out;

	onsemi->version = ver;
	rc = 0;

out:
	onsemi_power_put(onsemi);

	return rc;
}
EXPORT_SYMBOL_GPL(onsemi_core_hw_init);

static int onsemi_querycap(struct onsemi_core *onsemi,
			   struct v4l2_capability *cap)
{
	strcpy(cap->driver, "onsemi-core");

	return 0;
}

static long onsemi_core_ioctl(struct v4l2_subdev *sd,
			      unsigned int cmd, void *arg)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);

	switch (cmd) {
	case VIDIOC_QUERYCAP:
		return onsemi_querycap(onsemi, arg);

	default:
		return -ENOTTY;
	}
}

static int __used onsemi_g_register(struct v4l2_subdev *sd,
				    struct v4l2_dbg_register *reg)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	int			rc = 0;
	unsigned int		addr;

	if (reg->size == 1)
		addr = ONSEMI_REGMAP_8BIT_REG_TO_ADDR(reg->reg);
	else
		addr = reg->reg;

	reg->val = onsemi_read(&rc, onsemi, addr);

	return rc;
}

static int __used onsemi_s_register(struct v4l2_subdev *sd,
				    struct v4l2_dbg_register const *reg)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	int			rc = 0;
	unsigned int		addr;

	if (reg->size == 1)
		addr = ONSEMI_REGMAP_8BIT_REG_TO_ADDR(reg->reg);
	else
		addr = reg->reg;

	onsemi_write(&rc, onsemi, addr, reg->val);

	return rc;
}

static int onsemi_s_power(struct v4l2_subdev *sd, int on)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	int			rc;
	int			num_users;

	num_users = atomic_add_return(on ? 1  : -1, &onsemi->num_v4lpwr_users);
	if (WARN_ON(num_users < 0)) {
		rc = -EINVAL;
		goto out;
	}

	if (on &&
	    test_and_set_bit(ONSEMI_FLAG_V4L_POWERED, &onsemi->flags)) {
		v4l2_warn(sd, "s_power(ON) called twice");
		/* noop; powered on through v4l2 api already */
		return 0;
	}

	if (!on &&
	    !test_and_clear_bit(ONSEMI_FLAG_V4L_POWERED, &onsemi->flags)) {
		v4l2_warn(sd, "s_power(OFF) called twice");
		/* noop; already powered down through v4l2 api */
		return 0;
	}

	if (on) {
		rc = onsemi_power_get(onsemi);

		if (rc == 0 && onsemi->ops->prepare)
			rc = onsemi->ops->prepare(onsemi);
		if (rc < 0)
			clear_bit(ONSEMI_FLAG_V4L_POWERED, &onsemi->flags);
	} else {
		onsemi_power_put(onsemi);
		rc = 0;
	}

out:
	if (rc < 0)
		atomic_add(on ? -1 : 1, &onsemi->num_v4lpwr_users);

	return rc;
}

static int onsemi_g_parm(struct v4l2_subdev *sd, struct v4l2_streamparm *p)
{
	switch (p->type) {
	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
		p->parm.capture = (struct v4l2_captureparm) {
			.capability	= 0,
			.capturemode	= 0,
		};

		return 0;

	default:
		return -EINVAL;
	};
}

static int onsemi_g_mbus_config(struct v4l2_subdev *sd,
				struct v4l2_mbus_config *cfg)
{
	cfg->flags  = (V4L2_MBUS_MASTER |
		       V4L2_MBUS_HSYNC_ACTIVE_HIGH |
		       V4L2_MBUS_VSYNC_ACTIVE_HIGH |
		       V4L2_MBUS_DATA_ACTIVE_HIGH);

	/* TODO */

	return 0;
}

static void onsemi_get_frame_size(struct onsemi_core const *onsemi,
				  struct onsemi_v4l_parm const *parm,
				  unsigned int *h_size_out,
				  unsigned int *v_size_out)
{
	struct onsemi_limits const	*limits = onsemi->limits;
	unsigned int			h_size;
	unsigned int			v_size;

	if (!parm)
		parm = onsemi->v4l_parm;

	h_size  = parm->crop.width;
	h_size += parm->hblank;
Enrico Scholz's avatar
Enrico Scholz committed
1311
	h_size  = clamp_t(unsigned int, (h_size + 1) / 2 * 2,
Enrico Scholz's avatar
Enrico Scholz committed
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
			  limits->hlen.min, limits->hlen.max);

	v_size  = parm->crop.height;
	v_size += parm->vblank;
	v_size  = clamp_t(unsigned int, v_size,
			  limits->vlen.min, limits->vlen.max);

	*h_size_out = h_size;
	*v_size_out = v_size;
}

static unsigned long onsemi_frame_time_us(struct onsemi_core const *onsemi,
					  struct onsemi_v4l_parm const *parm,
					  struct onsemi_pll_freq const *freq)
{
	unsigned int			h_size;
	unsigned int			v_size;
	unsigned long			clk_pixel;
	uint64_t			res;

	clk_pixel = freq->clk_pixel;
	onsemi_get_frame_size(onsemi, parm, &h_size, &v_size);

	if (WARN_ON(h_size == 0 || v_size == 0 || clk_pixel == 0))
		return 0;

	res     = h_size * v_size;
	res    *= 1000000;

	return div64_ul(res, clk_pixel);
}

static void onsemi_enter_standby(struct onsemi_core *onsemi,
				 bool do_wait, int *err)
{
	unsigned int	timeout = do_wait ? 1000 : 0;
	bool		is_first = true;
	int		rc = err ? *err : 0;
	bool		is_smia;

	/* check whether serial mode was enabled */
	is_smia = (onsemi_read(&rc, onsemi, 0x301a) &
		   (ONSEMI_FLD_RESET_REGISTER_SMIA_DIS |
		    ONSEMI_FLD_RESET_REGISTER_PARALLEL_EN)) == 0;

	while (rc >= 0) {
		uint16_t	status;

		status = onsemi_read(&rc, onsemi, ONSEMI_REG_FRAME_STATUS);
		if (rc < 0)
			break;

		if (status & ONSEMI_FLD_FRAME_STATUS_STANDBY)
			break;

		if (timeout == 0) {
			v4l2_warn(&onsemi->subdev, "timeout while trying to enter standby\n");
			rc = -ETIMEDOUT;
			break;
		}

		if (is_first) {
			/* when called the first time, ensure that standby
			 * mode has been activated.  Disable GPIO input to
			 * avoid staying alive because of asserted TRIGGER */
			onsemi_update_bits(&rc, onsemi, 0x301a,
					   ONSEMI_FLD_RESET_REGISTER_STREAM |
					   ONSEMI_FLD_RESET_REGISTER_GPI_EN,
					   0);

			is_first = false;
		}

		--timeout;

		usleep_range(2000, 3000);
	}

	if (is_smia) {
		/* wait one frame before disabling MIPI interface */
		msleep(onsemi_frame_time_us(onsemi, NULL, onsemi->pll_freq) / 1000);

		onsemi_update_bits(&rc, onsemi, 0x301a,
				   ONSEMI_FLD_RESET_REGISTER_SMIA_DIS,
				   ONSEMI_FLD_RESET_REGISTER_SMIA_DIS);
	}

	if (test_and_clear_bit(ONSEMI_FLAG_SYNCCLK_ON, &onsemi->flags))
		clk_disable_unprepare(onsemi->synchclk);

	if (err)
		*err = rc;
}

static void onsemi_params_group_hold(struct onsemi_core *onsemi, bool ena, int *err)
{
	unsigned int const	addr = ONSEMI_REGMAP_8BIT_REG_TO_ADDR(0x3022);

	onsemi_write(err, onsemi, addr, ena ? 1 : 0);
}

static void onsemi_params_write_frame(struct onsemi_core *onsemi, int *err)
{
	struct onsemi_v4l_parm const	*parm = onsemi->v4l_parm;
1416
	struct onsemi_businfo const	*bus_info = onsemi->active_bus;
Enrico Scholz's avatar
Enrico Scholz committed
1417 1418 1419 1420 1421 1422 1423 1424
	unsigned int			h_size;
	unsigned int			v_size;

	if (*err < 0)
		return;

	onsemi_get_frame_size(onsemi, NULL, &h_size, &v_size);

1425 1426 1427 1428 1429 1430 1431
	if (onsemi->ops->hclk_mul_2 && bus_info) {
		/* HACK: this smells ugly and is based upon experiments with
		 * the register wizard */
		if (bus_info->bus_type == V4L2_MBUS_CSI2 &&
		    bus_info->bus_width < 4)
			h_size *= 2;
	}
Enrico Scholz's avatar
Enrico Scholz committed
1432 1433 1434 1435 1436

	onsemi_write(err, onsemi, 0x300a, v_size); /* frame_length_line */
	onsemi_write(err, onsemi, 0x300c, h_size); /* line_length_pck */

	if (onsemi->ops->has_smia_cfg) {
1437 1438 1439 1440
		/* x_output_size */
		onsemi_write(err, onsemi, 0x034c, parm->frame.width);
		/* y_output_size */
		onsemi_write(err, onsemi, 0x034e, parm->frame.height);
Enrico Scholz's avatar
Enrico Scholz committed
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
	}
}

static void onsemi_params_write_crop(struct onsemi_core *onsemi,
				     struct onsemi_v4l_parm const *parm,
				     bool write_back, int *err)
{
	if (WARN_ON(!parm && write_back))
		return;

	if (*err < 0)
		return;

	if (!parm)
		parm = onsemi->v4l_parm;

	onsemi_write(err, onsemi, 0x3002, parm->crop.top);
	onsemi_write(err, onsemi, 0x3004, parm->crop.left);
	onsemi_write(err, onsemi, 0x3006, parm->crop.top + parm->crop.height - 1);
	onsemi_write(err, onsemi, 0x3008, parm->crop.left + parm->crop.width - 1);

	if (*err < 0)
		return;

	if (write_back)
		onsemi->v4l_parm->crop = parm->crop;
}

static void onsemi_params_write_parallel(struct onsemi_core *onsemi, int *err)
{
	onsemi_write(err, onsemi, 0x31ae, 0x0200);
	onsemi_update_bits(err, onsemi, 0x301a,
			   ONSEMI_FLD_RESET_REGISTER_SMIA_DIS |
			   ONSEMI_FLD_RESET_REGISTER_PARALLEL_EN |
			   ONSEMI_FLD_RESET_REGISTER_DRIVE_PINS,

			   ONSEMI_FLD_RESET_REGISTER_SMIA_DIS |
			   ONSEMI_FLD_RESET_REGISTER_PARALLEL_EN |
			   ONSEMI_FLD_RESET_REGISTER_DRIVE_PINS);

}

static void onsemi_params_write_mipi(struct onsemi_core *onsemi, int *err)
{
	struct onsemi_businfo const	*info = onsemi->active_bus;

	if (WARN_ON(!info || info->bus_width < 1 || info->bus_width >= 16)) {
		*err = -EINVAL;
		return;
	}

1492
	onsemi_write(err, onsemi, 0x31ae, (2 << 8) | info->bus_width);
Enrico Scholz's avatar
Enrico Scholz committed
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139
	onsemi_update_bits(err, onsemi, 0x301a,
			   ONSEMI_FLD_RESET_REGISTER_SMIA_DIS |
			   ONSEMI_FLD_RESET_REGISTER_PARALLEL_EN |
			   ONSEMI_FLD_RESET_REGISTER_DRIVE_PINS,
			   0);
}

static void onsemi_params_write_pll(struct onsemi_core *onsemi, int *err)
{
	unsigned int	bpp = onsemi->v4l_parm->bpp;

	if (*err < 0)
		return;

	/* TODO: add a way to force LSB alignung; e.g. AR0144's 0x3736[5]
	 * bit? */
	if (onsemi->active_bus->bus_type == V4L2_MBUS_PARALLEL)
		bpp = 12;

	onsemi_enter_standby(onsemi, true, err);
	if (*err < 0)
		goto out;

	*err = onsemi_core_pll_set(onsemi, onsemi->pll_cfg, onsemi->pll_freq);
	if (*err < 0)
		goto out;

	if (!onsemi->ops->has_smia_cfg)
		onsemi_write(err, onsemi, 0x31ac, (bpp << 8) | bpp);
	else
		onsemi_write(err, onsemi, 0x0112, (bpp << 8) | bpp);

out:
	if (*err < 0)
		v4l2_err(&onsemi->subdev, "failed to set PLL: %d\n", *err);
}

static int _onsemi_s_stream_on(struct onsemi_core *onsemi)
{
	int			rc;

	rc = onsemi_power_get(onsemi);
	if (rc < 0)
		return rc;

	mutex_lock(&onsemi->lock);

	rc = onsemi->ops->pll_calculate(onsemi);
	if (rc < 0)
		goto out;

	onsemi_params_write_pll(onsemi, &rc);

	switch (onsemi->active_bus->bus_type) {
	case V4L2_MBUS_PARALLEL:
		onsemi_params_write_parallel(onsemi, &rc);
		break;

	case V4L2_MBUS_CSI2:
		onsemi_params_write_mipi(onsemi, &rc);
		break;

	default:
		WARN_ON(1);
		rc = -EINVAL;
	}

	if (!IS_ENABLED(CONFIG_THERMAL)) {
		/* enable thermal sensor and clear previous results (for
		 * sanity) */
		onsemi_update_bits(&rc, onsemi, 0x30b4,
				   BIT(0) | BIT(5) | BIT(4),
				   BIT(0) | BIT(5) | BIT(4));
	}

	onsemi_update_bits(&rc, onsemi, 0x301a,
			   ONSEMI_FLD_RESET_REGISTER_LOCK_REG, 0);
	onsemi_write(&rc, onsemi, 0x301e, onsemi->v4l_parm->data_pedestal);

	onsemi_params_group_hold(onsemi, true, &rc);

	onsemi_params_write_frame(onsemi, &rc);
	onsemi_params_write_crop(onsemi, NULL, false, &rc);

	if (rc >= 0 && onsemi->ops->stream_on)
		rc = onsemi->ops->stream_on(onsemi);

	onsemi_params_group_hold(onsemi, false, &rc);

	onsemi_write(&rc, onsemi, ONSEMI_REG_MASK_CORRUPTED_FRAMES, 1);
	onsemi_write(&rc, onsemi, ONSEMI_REG_MOD_SELECT, 1);

	if (rc < 0)
		goto out;

	rc = 0;

out:
	mutex_unlock(&onsemi->lock);

	if (rc < 0)
		onsemi_power_put(onsemi);

	return rc;
}

static int _onsemi_s_stream_off(struct onsemi_core *onsemi)
{
	int		rc = 0;

	mutex_lock(&onsemi->lock);

	if (!IS_ENABLED(CONFIG_THERMAL)) {
		onsemi_update_bits(&rc, onsemi, 0x30b4,
				   BIT(0) | BIT(5) | BIT(4),
				   BIT(5));
	}

	if (rc >= 0 && onsemi->ops->stream_off)
		rc = onsemi->ops->stream_off(onsemi);

	/* TODO: this is hacky but required for LP-11 required on iMX6 */
	if (rc == 0)
		onsemi_enter_standby(onsemi, true, &rc);

	/* TODO: improve error handling! */
	rc = 0;

	if (rc < 0)
		goto out;

	/* TODO: ignore errors... */
	rc = 0;

out:
	mutex_unlock(&onsemi->lock);

	onsemi_power_put(onsemi);

	return rc;
}

static int onsemi_s_stream(struct v4l2_subdev *sd, int enable)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	int			rc;

	if (!onsemi->active_bus) {
		dev_dbg(onsemi->dev, "no active bus\n");
		return -EPIPE;
	}

	if (enable &&
	    test_and_set_bit(ONSEMI_FLAG_V4L_STREAMING, &onsemi->flags)) {
		return -EBUSY;
	}

	if (!enable &&
	    !test_and_clear_bit(ONSEMI_FLAG_V4L_STREAMING, &onsemi->flags)) {
		return -EBADF;
	}

	if (enable) {
		rc = _onsemi_s_stream_on(onsemi);
		if (rc < 0)
			clear_bit(ONSEMI_FLAG_V4L_STREAMING, &onsemi->flags);
	} else {
		rc = _onsemi_s_stream_off(onsemi);
		if (rc < 0)
			set_bit(ONSEMI_FLAG_V4L_STREAMING, &onsemi->flags);
	}

	return rc;
}

static int _onsemi_enum_mbus_code_bayer(struct onsemi_core *onsemi,
					struct onsemi_businfo const *info,
					unsigned int idx,
					unsigned int *code)
{
	static unsigned int const	FMT8[] = {
		[0] = MEDIA_BUS_FMT_SBGGR8_1X8,
		[1] = MEDIA_BUS_FMT_SGBRG8_1X8,
		[2] = MEDIA_BUS_FMT_SGRBG8_1X8,
		[3] = MEDIA_BUS_FMT_SRGGB8_1X8,
	};

	static unsigned int const	FMT10[] = {
		[0] = MEDIA_BUS_FMT_SBGGR10_1X10,
		[1] = MEDIA_BUS_FMT_SGBRG10_1X10,
		[2] = MEDIA_BUS_FMT_SGRBG10_1X10,
		[3] = MEDIA_BUS_FMT_SRGGB10_1X10,
	};

	static unsigned int const	FMT12[] = {
		[0] = MEDIA_BUS_FMT_SBGGR12_1X12,
		[1] = MEDIA_BUS_FMT_SGBRG12_1X12,
		[2] = MEDIA_BUS_FMT_SGRBG12_1X12,
		[3] = MEDIA_BUS_FMT_SRGGB12_1X12,
	};

	unsigned long const	KNOWN_FMT = BIT(8) | BIT(10) | BIT(12);

	unsigned long		supported_bpp = onsemi->ops->supported_bpp;
	unsigned int		bit;
	unsigned int		bpp = 0;

	for_each_set_bit(bit, &supported_bpp, 16) {
		unsigned int	tmp;

		if (WARN_ON(abs(info->dout_sft) > bit))
			/* should be checked in _init()... */
			continue;

		tmp = bit + info->dout_sft;

		/* filter out unsupported formats; e.g. when Y10 gets shifted
		 * 4 bits */
		if (!test_bit(tmp, &KNOWN_FMT))
			/* do *not* decrease 'idx' */
			continue;

		if (idx < 4) {
			bpp = tmp;
			break;
		}

		idx -= 4;
	}

	if (bpp == 0) {
		dev_dbg(onsemi->dev, "bayer mbus code not found\n");
		return -EINVAL;
	}

	switch (bpp) {
	case 8:
		*code = FMT8[idx % 4];
		break;
	case 10:
		*code = FMT10[idx % 4];
		break;
	case 12:
		*code = FMT12[idx % 4];
		break;
	default:
		v4l2_warn(&onsemi->subdev, "unsupported bpp %d\n", bpp);
		return -EINVAL;
	}

	return 0;
}

static int _onsemi_enum_mbus_code_mono(struct onsemi_core *onsemi,
				       struct onsemi_businfo const *info,
				       unsigned int idx,
				       unsigned int *code)
{
	unsigned long const	KNOWN_FMT = BIT(8) | BIT(10) | BIT(12) | BIT(16);
	unsigned long		supported_bpp = onsemi->ops->supported_bpp;
	unsigned int		bit;
	unsigned int		bpp = 0;

	for_each_set_bit(bit, &supported_bpp, 16) {
		unsigned int	tmp;

		if (WARN_ON(abs(info->dout_sft) > bit))
			/* should be checked in _init()... */
			continue;

		tmp = bit + info->dout_sft;

		/* filter out unsupported formats; e.g. when Y10 gets shifted
		 * 4 bits */
		if (!test_bit(tmp, &KNOWN_FMT))
			/* do *not* decrease 'idx' */
			continue;

		if (idx == 0) {
			bpp = tmp;
			break;
		}

		--idx;
	}

	if (bpp == 0) {
		dev_dbg(onsemi->dev, "mono mbus code not found\n");
		return -EINVAL;
	}

	switch (bpp) {
	case 8:
		*code = MEDIA_BUS_FMT_Y8_1X8;
		break;
	case 10:
		*code = MEDIA_BUS_FMT_Y10_1X10;
		break;
	case 12:
		*code = MEDIA_BUS_FMT_Y12_1X12;
		break;
#ifdef MEDIA_BUS_FMT_Y16_1X16
	case 16:
		*code = MEDIA_BUS_FMT_Y16_1X16;
		break;
#endif
	default:
		v4l2_warn(&onsemi->subdev, "unsupported bpp %d\n", bpp);
		return -EINVAL;
	}

	return 0;
}

static int onsemi_enum_mbus_code(struct v4l2_subdev *sd,
				 struct v4l2_subdev_pad_config *cfg,
				 struct v4l2_subdev_mbus_code_enum *code)
{
	struct onsemi_core		*onsemi = sd_to_onsemi(sd);
	struct onsemi_businfo const	*info;
	unsigned int			fmt_code;
	int				rc;

	if (onsemi->ops->enum_mbus_code)
		return onsemi->ops->enum_mbus_code(onsemi, cfg, code);

	info = onsemi_get_businfo(onsemi, code->pad);
	if (!info)
		return -EINVAL;

	switch (onsemi->color_mode) {
	case ONSEMI_COLOR_MONOCHROME:
		rc = _onsemi_enum_mbus_code_mono(onsemi, info, code->index, &fmt_code);
		break;
	case ONSEMI_COLOR_BAYER:
		rc = _onsemi_enum_mbus_code_bayer(onsemi, info, code->index, &fmt_code);
		break;
	default:
		WARN_ON(1);
		return -EINVAL;
	}

	if (rc < 0)
		return rc;

	code->code = fmt_code;

	return 0;
}

static int onsemi_mbus_to_bpp(struct onsemi_core const *onsemi,
			      struct onsemi_businfo const *info,
			      unsigned int code, unsigned int *bpp)
{
	int		rc = 0;
	signed int	raw_bpp;

	switch (onsemi->color_mode) {
	case ONSEMI_COLOR_MONOCHROME:
		switch (code) {
		case MEDIA_BUS_FMT_Y8_1X8:
			raw_bpp = 8;
			break;
		case MEDIA_BUS_FMT_Y10_1X10:
			raw_bpp = 10;
			break;
		case MEDIA_BUS_FMT_Y12_1X12:
			raw_bpp = 12;
			break;
#ifdef MEDIA_BUS_FMT_Y16_1X16
		case MEDIA_BUS_FMT_Y16_1X16:
			raw_bpp = 16;
			break;
#endif
		default:
			v4l2_warn(&onsemi->subdev,
				  "unsupported mbus fmt %04x for mono sensor\n",
				  code);
			rc = -EINVAL;
			break;
		}
		break;

	case ONSEMI_COLOR_BAYER:
		switch (code) {
		case MEDIA_BUS_FMT_SBGGR8_1X8:
		case MEDIA_BUS_FMT_SGBRG8_1X8:
		case MEDIA_BUS_FMT_SGRBG8_1X8:
		case MEDIA_BUS_FMT_SRGGB8_1X8:
			raw_bpp = 8;
			break;
		case MEDIA_BUS_FMT_SBGGR10_1X10:
		case MEDIA_BUS_FMT_SGBRG10_1X10:
		case MEDIA_BUS_FMT_SGRBG10_1X10:
		case MEDIA_BUS_FMT_SRGGB10_1X10:
			raw_bpp = 10;
			break;
		case MEDIA_BUS_FMT_SBGGR12_1X12:
		case MEDIA_BUS_FMT_SGBRG12_1X12:
		case MEDIA_BUS_FMT_SGRBG12_1X12:
		case MEDIA_BUS_FMT_SRGGB12_1X12:
			raw_bpp = 12;
			break;
		default:
			v4l2_warn(&onsemi->subdev,
				  "unsupported mbus fmt %04x for mono sensor\n",
				  code);
			rc = -EINVAL;
			break;
		}
		break;

	default:
		/* TODO: implement color mode */
		WARN_ON(1);
		rc = -ENOTTY;
	}

	if (rc < 0) {
		v4l2_warn(&onsemi->subdev, "unsupported color format %04x\n",
			  code);
		goto out;
	}

	raw_bpp -= info->dout_sft;
	if (raw_bpp < 0 || raw_bpp > 16) {
		v4l2_warn(&onsemi->subdev, "bad bpp/sft %d\n", raw_bpp);
		rc = -EINVAL;
		goto out;
	}

	if (!test_bit(raw_bpp, &onsemi->ops->supported_bpp)) {
		v4l2_warn(&onsemi->subdev, "bad bpp %d\n", raw_bpp);
		rc = -EINVAL;
		goto out;
	}

	*bpp = raw_bpp;
	rc = 0;

out:
	return rc;
}

static int onsemi_set_fmt(struct v4l2_subdev *sd,
			  struct v4l2_subdev_pad_config *cfg,
			  struct v4l2_subdev_format *format)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	struct onsemi_v4l_parm	*parm = onsemi->v4l_parm;
	struct onsemi_businfo const	*info;
	unsigned int		w;
	unsigned int		h;
	unsigned int		bpp;
	unsigned int		max_w;
	unsigned int		max_h;
	int			rc;
	struct onsemi_pll_cfg		*pll_cfg;
	struct onsemi_pll_freq		*pll_freq;
	bool				bad_again = false;

	info = onsemi_get_businfo(onsemi, format->pad);
	if (!info)
		return -EINVAL;

	if (test_bit(ONSEMI_FLAG_V4L_STREAMING, &onsemi->flags) &&
	    format->which == V4L2_SUBDEV_FORMAT_ACTIVE)
		return -EBUSY;

again:
	w = format->format.width;
	h = format->format.height;

	if (format->format.field == V4L2_FIELD_ANY)
		format->format.field = V4L2_FIELD_NONE;

	if (format->format.colorspace == V4L2_COLORSPACE_DEFAULT)
		format->format.colorspace = V4L2_COLORSPACE_RAW;

	if (format->format.xfer_func == V4L2_XFER_FUNC_DEFAULT)
		format->format.xfer_func = V4L2_XFER_FUNC_NONE;

	rc = onsemi_mbus_to_bpp(onsemi, info, format->format.code, &bpp);
	if (rc < 0)
		goto bad_parm;

	/* TODO: some OnSemi sensors might support other values... */
	if (format->format.field != V4L2_FIELD_NONE ||
	    format->format.xfer_func != V4L2_XFER_FUNC_NONE ||
	    format->format.colorspace != V4L2_COLORSPACE_RAW) {
		v4l2_warn(sd, "unsupported params (%d, %d, %d)",
			  format->format.field, format->format.xfer_func,
			  format->format.colorspace);
		goto bad_parm;
	}

	max_w  = onsemi->limits->x.max - onsemi->limits->x.min + 1;
	max_h  = onsemi->limits->y.max - onsemi->limits->y.min + 1;
	max_w /= parm->x_scale;
	max_h /= parm->y_scale;

	if (w > max_w || h > max_h) {
		v4l2_warn(sd, "frame %dx%d too large (max %dx%d)\n",
			  w, h, max_w, max_h);
		goto bad_parm;
	}

	format->format.width  = w;
	format->format.height = h;

	if (onsemi->ops->set_fmt) {
		rc = onsemi->ops->set_fmt(onsemi, cfg, format, bpp);
		if (rc < 0)
			goto bad_parm;
	}

	if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE &&
	    info == onsemi->active_bus) {
		pll_cfg  = onsemi->pll_cfg;
		pll_freq = onsemi->pll_freq;
	} else {
		pll_cfg  = NULL;
		pll_freq = NULL;
	}

	rc = onsemi_calculate_pll(onsemi, info, bpp, pll_cfg, pll_freq);
	if (rc < 0)
		goto bad_parm;

	if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
		struct onsemi_v4l_parm	*parm = onsemi->v4l_parm;

		parm->frame.height = format->format.height;
		parm->frame.width  = format->format.width;
		parm->code         = format->format.code;
		parm->bpp          = bpp;
	}

	return 0;

bad_parm:
	if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE || bad_again)
		return -EINVAL;

	bad_again = true;

	format->format = (struct v4l2_mbus_framefmt) {
		.field		= V4L2_FIELD_NONE,
		.xfer_func	= V4L2_XFER_FUNC_NONE,
		.colorspace	= V4L2_COLORSPACE_RAW,
		.height		= onsemi->v4l_parm->frame.height,
		.width		= onsemi->v4l_parm->frame.width,
		.code		= onsemi->v4l_parm->code,
	};

	goto again;
}

static int onsemi_get_fmt(struct v4l2_subdev *sd,
			  struct v4l2_subdev_pad_config *cfg,
			  struct v4l2_subdev_format *format)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	struct onsemi_v4l_parm	*parm = onsemi->v4l_parm;

	format->pad = 0;
	format->format = (struct v4l2_mbus_framefmt) {
		.width		= parm->frame.width,
		.height		= parm->frame.height,
		.code		= parm->code,
		.field		= V4L2_FIELD_NONE,
		.colorspace	= V4L2_COLORSPACE_RAW,
		.xfer_func	= V4L2_XFER_FUNC_NONE,
	};

	return 0;
}

static int onsemi_check_sel_bayer(struct onsemi_core const *onsemi,
				  struct v4l2_subdev_selection const *s)
{
	struct onsemi_v4l_parm const	*parm = onsemi->v4l_parm;
	unsigned int			idx;
	unsigned int			x_mod;
	unsigned int			y_mod;

	switch (parm->code) {
	case MEDIA_BUS_FMT_SBGGR8_1X8:
	case MEDIA_BUS_FMT_SBGGR10_1X10:
	case MEDIA_BUS_FMT_SBGGR12_1X12:
		idx = 0x10;		/* y+1, x+0 */
		break;
	case MEDIA_BUS_FMT_SGBRG8_1X8:
	case MEDIA_BUS_FMT_SGBRG10_1X10:
	case MEDIA_BUS_FMT_SGBRG12_1X12:
		idx = 0x11;		/* y+1, x+1 */
		break;
	case MEDIA_BUS_FMT_SGRBG8_1X8:
	case MEDIA_BUS_FMT_SGRBG10_1X10:
	case MEDIA_BUS_FMT_SGRBG12_1X12:
		idx = 0x00;		/* y+0, x+0 */
		break;
	case MEDIA_BUS_FMT_SRGGB8_1X8:
	case MEDIA_BUS_FMT_SRGGB10_1X10:
	case MEDIA_BUS_FMT_SRGGB12_1X12:
		idx = 0x01;		/* y+0, x+1 */
		break;
	default:
		WARN_ON(1);
		return -EINVAL;
	}

	x_mod = parm->x_skip;
	y_mod = parm->y_skip;

	if (WARN_ON(x_mod == 0) || WARN_ON(y_mod == 0))
		return -EINVAL;

	if ((s->r.left + x_mod - ((idx >> 0) & 0xf)) % x_mod != 0 ||
	    (s->r.top  + y_mod - ((idx >> 4) & 0xf)) % y_mod != 0) {
		v4l2_info(&onsemi->subdev,
			  "oddly aligned crop area (%dx%d %% %dx%d)\n",
			  s->r.left, s->r.top, x_mod, y_mod);
		return -EINVAL;
	}

	return 0;
}

static int onsemi_set_selection(struct v4l2_subdev *sd,
				struct v4l2_subdev_pad_config *cfg,
				struct v4l2_subdev_selection *s)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	struct onsemi_v4l_parm	*parm = onsemi->v4l_parm;
	struct onsemi_limits const *limits = onsemi->limits;
	bool			is_try = s->which == V4L2_SUBDEV_FORMAT_TRY;
	bool			is_streaming;
	int			rc;

	if (s->target != V4L2_SEL_TGT_CROP)
		return -EINVAL;

	if (s->r.left < limits->x.min ||
	    s->r.top < limits->y.min ||
	    s->r.width > limits->x.max - onsemi->limits->x.min + 1 ||
	    s->r.height > limits->y.max - onsemi->limits->y.min + 1) {
		v4l2_warn(sd, "bad selection %dx%d+%dx%d\n",
			  s->r.left, s->r.top, s->r.width, s->r.height);

		/* TODO: implement V4L2_SEL_FLAG_GE/LE handling? */
		return -EINVAL;
	}

	if (is_try)
		return 0;

	mutex_lock(&onsemi->lock);

	switch (onsemi->color_mode) {
	case ONSEMI_COLOR_MONOCHROME:
		/* no extra checks */
		break;
	case ONSEMI_COLOR_BAYER:
		rc = onsemi_check_sel_bayer(onsemi, s);
		break;
	default:
		WARN_ON(1);
		rc = -EINVAL;
		break;
	}

	is_streaming = test_bit(ONSEMI_FLAG_V4L_STREAMING, &onsemi->flags);

	if ((s->r.width != parm->crop.width) ||
	    (s->r.height != parm->crop.height)) {
		if (is_streaming) {
			rc = -EBUSY;
			goto out;
		}
	}

	if (!is_streaming) {
		parm->crop = s->r;
		rc = 0;
	} else {
		struct onsemi_v4l_parm	tmp_parm = *parm;

		tmp_parm.crop = s->r;

		rc = 0;

		onsemi_params_group_hold(onsemi, 1, &rc);
		onsemi_params_write_crop(onsemi, &tmp_parm, true, &rc);
		onsemi_params_group_hold(onsemi, 0, &rc);
	}

	if (rc < 0) {
		v4l2_warn(sd, "failed to set crop params: %d\n", rc);
		goto out;
	}

	rc = 0;


out:
	mutex_unlock(&onsemi->lock);

	return rc;
}

static int onsemi_get_selection(struct v4l2_subdev *sd,
				struct v4l2_subdev_pad_config *cfg,
				struct v4l2_subdev_selection *s)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	struct onsemi_v4l_parm	*parm = onsemi->v4l_parm;
	struct onsemi_limits const *limits = onsemi->limits;

	switch (s->target) {
	case V4L2_SEL_TGT_CROP:
		mutex_lock(&onsemi->lock);
		s->r = parm->crop;
		mutex_unlock(&onsemi->lock);
		break;

	case V4L2_SEL_TGT_CROP_BOUNDS:
		s->r = (struct v4l2_rect) {
			.left	= limits->x.min,
			.top	= limits->y.min,
			.width	= limits->x.max - limits->x.min + 1,
			.height = limits->y.max - limits->y.min + 1,
		};
		break;

	default:
		return -EINVAL;
	}

	return 0;
}

static int onsemi_g_frame_interval(struct v4l2_subdev *sd,
				   struct v4l2_subdev_frame_interval *interval)
{
	struct onsemi_core		*onsemi = sd_to_onsemi(sd);
	struct onsemi_businfo const	*info;
	struct onsemi_pll_freq		freq;
	int				rc;
	unsigned long			tm;

	info = onsemi_get_businfo(onsemi, interval->pad);
	if (!info)
		return -EINVAL;

	mutex_lock(&onsemi->lock);

	rc = onsemi_calculate_pll(onsemi, info, onsemi->v4l_parm->bpp,
				  NULL, &freq);
	if (rc < 0)
		goto out;

	tm = onsemi_frame_time_us(onsemi, NULL, &freq);

	/* TODO: add extra exposure times */

	interval->interval = (struct v4l2_fract) {
		.numerator	= tm,
		.denominator	= 1000000,
	};

	rc = 0;

out:
	mutex_unlock(&onsemi->lock);

	return rc;
}

struct onsemi_interval_search_parm {
	struct onsemi_core const	*onsemi;
	struct v4l2_fract const		*interval;
	struct onsemi_pll_freq		freq;
	struct onsemi_v4l_parm		parm;
};

/**
 *  run a binary search of 'val' between 'min' and 'max' until delta is
 *  below 'epsilon'
 *
 *  @parm object with static/constant search parameters
 *  @min  lower border of search
 *  @max  upper border of esearch
 *  @val  value to be searched; the actual input value will be tested first
 *  @epsilon allowed delta in number of pixels
 */
static int _onsemi_interval_search(struct onsemi_interval_search_parm const *parm,
				   unsigned long min, unsigned long max,
				   unsigned int *val,
				   unsigned int epsilon)
{
	/* we will scale 'min', 'max' + '*val' in the binary search to ensure
	 * that the loop terminates **and** finds an element; 'epsilon' must
	 * be large enough (e.g. a whole row) so that we can find the
	 * middle.
	 *
	 * This parameter does NOT increase the number of loops but just
	 * compensates rounding effects */
	static unsigned int const	V_SCALE = 4;

	uint64_t		e = epsilon;
	uint64_t		num = parm->interval->numerator;
	unsigned long		denom = parm->interval->denominator;
	unsigned long		v = *val;

	if (WARN_ON(parm->freq.clk_pixel == 0))
		return -EINVAL;

	/* adjust existing 'val' to limits */
	if (v < min)
		v = min;

	if (v > max)
		v = max;

	/* scale interval because we are working with us internally */
	num *= 1000000;

	/* scale/transform epsilon from number of pixels to time for them in
	 * us */
	e *= 1000000;
	e  = div64_ul(e, parm->freq.clk_pixel);
	e += 5;				/* some arbitrary adjustment... */

	/* at the end we try to satisfy
	 *
	 *    abs(tm - num/denom) < epsilon
	 *
	 * which will be transformed to
	 *
	 *    abs(tm * denom - num) < epsilon * denom
	 *
	 * Right side is an invariant which can be calculated here, outside
	 * the loop
	 */
	e *= denom;

	min *= V_SCALE;
	max *= V_SCALE;
	v   *= V_SCALE;

	pr_debug("%s  : [%lu,%lu]/%lu -> e=%llu\n", __func__, min, max, v, e);

	do {
		unsigned long		tm;
		uint64_t		tm_s;
		uint64_t		delta;

		/* revert scaling and write back the real value so it will be
		 * used in onsemi_frame_time_us() call below */
		*val = v / V_SCALE;

		tm    = onsemi_frame_time_us(parm->onsemi,
					     &parm->parm, &parm->freq);
		tm_s  = tm;
		tm_s *= denom;

		if (tm_s < num) {
			delta = num - tm_s;
			min   = v;
		} else {
			delta = tm_s - num;
			max   = v;
		}

		pr_debug("  %s: [%lu,%lu]/%lu -> tm=%llu, delta=%llu\n",
			 __func__, min, max, v, tm_s, delta);

		if (delta < e)
			return tm;

		v = (min + max) / 2;
	} while (min + V_SCALE - 1 < max);

	return -ERANGE;
}

static int onsemi_s_frame_interval(struct v4l2_subdev *sd,
				   struct v4l2_subdev_frame_interval *interval)
{
	struct onsemi_core		*onsemi = sd_to_onsemi(sd);
	struct onsemi_businfo const	*info;
	struct v4l2_ctrl		*vblank_ctrl;
	signed long			rc;

	struct onsemi_interval_search_parm	parm = {
		.onsemi		= onsemi,
		.interval	= &interval->interval,
	};

	/* used to reflect changes in the v4l2 ctrl */
	vblank_ctrl = v4l2_ctrl_find(&onsemi->ctrls, V4L2_CID_VBLANK);

	mutex_lock(&onsemi->lock);

	/* TODO: although it would be possible to change frame interval while
	 * streaming, it is not supported atm */
	if (onsemi_is_streaming(onsemi)) {
		rc = -EBUSY;
		goto out;
	}

	info = onsemi_get_businfo(onsemi, interval->pad);
	if (!info) {
		rc = -EINVAL;
		goto out;
	}

	rc = onsemi_calculate_pll(onsemi, info, onsemi->v4l_parm->bpp,
				  NULL, &parm.freq);
	if (rc < 0)
		goto out;

	parm.parm = *onsemi->v4l_parm;

	/* calculate a matching 'vblank' value with an epsilon which can be
	 * compensated by EXTRA_DELAY (not implemented yet!) */
	rc = _onsemi_interval_search(&parm,
				     onsemi->limits->vblank_min,
				     onsemi->limits->vlen.max -
				     parm.parm.crop.height,
				     &parm.parm.vblank,
				     0xffff);
	if (rc < 0) {
		v4l2_warn(sd, "failed to find matching parameters for given interval\n");
		goto out;
	}

	/* write back the calculated time */
	interval->interval = (struct v4l2_fract) {
		.numerator	= rc,
		.denominator	= 1000000,
	};

	*onsemi->v4l_parm = parm.parm;

	if (vblank_ctrl)
		vblank_ctrl->cur.val = onsemi->v4l_parm->vblank;

	rc = 0;

out:
	mutex_unlock(&onsemi->lock);

	return rc;
}

static int onsemi_link_validate(struct v4l2_subdev *sink,
				struct media_link *link,
				struct v4l2_subdev_format *source_fmt,
				struct v4l2_subdev_format *sink_fmt)
{
	return 0;
}

static int onsemi_s_ctrl(struct v4l2_ctrl *ctrl)
{
	struct onsemi_core		*onsemi = ctrl->priv;
	struct onsemi_v4l_parm		*parm = onsemi->v4l_parm;
	int				rc = 0;

	mutex_lock(&onsemi->lock);

	if (onsemi->ops->ctrl_set &&
	    onsemi->ops->ctrl_set(onsemi, ctrl, &rc))
		goto out;

	switch (ctrl->id) {
	case V4L2_CID_VBLANK:
		if (onsemi_is_streaming(onsemi)) {
			rc = -EBUSY;
			goto out;
		}
		parm->vblank = ctrl->val;
		break;

	case V4L2_CID_HBLANK:
		if (onsemi_is_streaming(onsemi)) {
			rc = -EBUSY;
			goto out;
		}
		parm->hblank = ctrl->val;
		break;

	case V4L2_CID_HFLIP:
		onsemi_update_bits(&rc, onsemi, 0x3040, BIT(14),
				   ctrl->val ? BIT(14) : 0);
		break;
	case V4L2_CID_VFLIP:
		onsemi_update_bits(&rc, onsemi, 0x3040, BIT(15),
				   ctrl->val ? BIT(15) : 0);
		break;
	case V4L2_CID_EXPOSURE:
		/* TODO: implement EXPOSURE -> 100us * conversion and combine
		 * with V4L2_CID_X_EXPOSURE_FINE*/
		onsemi_write(&rc, onsemi, 0x3012, ctrl->val);
		break;
	case V4L2_CID_X_EXPOSURE_FINE:
		/* TODO: remove me; see V4L2_CID_EXPOSURE */
		onsemi_write(&rc, onsemi, 0x3014, ctrl->val);
		break;
	case V4L2_CID_TEST_PATTERN_RED:
		onsemi_write(&rc, onsemi, 0x3072, ctrl->val);
		break;
	case V4L2_CID_TEST_PATTERN_GREENR:
		onsemi_write(&rc, onsemi, 0x3074, ctrl->val);
		break;
	case V4L2_CID_TEST_PATTERN_BLUE:
		onsemi_write(&rc, onsemi, 0x3076, ctrl->val);
		break;
	case V4L2_CID_TEST_PATTERN_GREENB:
		onsemi_write(&rc, onsemi, 0x3078, ctrl->val);
		break;
	default:
		dev_dbg(onsemi->dev, "unhandled control %08x (%s)\n", ctrl->id,
			v4l2_ctrl_get_name(ctrl->id));
		rc = -ENOTTY;
		break;
	}

out:
	mutex_unlock(&onsemi->lock);

	return rc;
}

static int onsemi_g_ctrl(struct v4l2_ctrl *ctrl)
{
	struct onsemi_core		*onsemi = ctrl->priv;
	int				rc = 0;

	mutex_lock(&onsemi->lock);

	if (onsemi->ops->ctrl_get &&
	    onsemi->ops->ctrl_get(onsemi, ctrl, &rc))
		goto out;

	switch (ctrl->id) {
	default:
		dev_dbg(onsemi->dev, "unhandled control %08x (%s)\n", ctrl->id,
			v4l2_ctrl_get_name(ctrl->id));
		rc = -ENOTTY;
		break;
	}

out:
	mutex_unlock(&onsemi->lock);

	return rc;
}

struct v4l2_ctrl_ops const		onsemi_core_ctrl_ops = {
	.s_ctrl			= onsemi_s_ctrl,
	.g_volatile_ctrl	= onsemi_g_ctrl,
};
EXPORT_SYMBOL_GPL(onsemi_core_ctrl_ops);

static struct v4l2_ctrl_config const	onsemi_core_ctrls[] = {
	{
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_VBLANK,
		.type		= V4L2_CTRL_TYPE_INTEGER,
		.min		= 0,
		.max		= 65535,
		.step		= 1,
		.def		= 1,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_HBLANK,
		.type		= V4L2_CTRL_TYPE_INTEGER,
		.min		= 0,
		.max		= 65535,
		.step		= 1,
		.def		= 1,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_HFLIP,
		.type		= V4L2_CTRL_TYPE_BOOLEAN,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_VFLIP,
		.type		= V4L2_CTRL_TYPE_BOOLEAN,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_EXPOSURE,
		.type		= V4L2_CTRL_TYPE_INTEGER,
		.min		= 0,
		.max		= 65535,
		.step		= 1,
		.def		= 800,
	}, {
		/* TODO: remove me and replace by EXPOSURE -> 100us
		 * conversion */
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_X_EXPOSURE_FINE,
		.type		= V4L2_CTRL_TYPE_INTEGER,
		.name		= "exposure fine",
		.min		= 0,
		.max		= 65535,
		.step		= 1,
		.def		= 10,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_TEST_PATTERN_RED,
		.type		= V4L2_CTRL_TYPE_INTEGER,
		.min		= 0,
		.max		= 65535,
		.step		= 1,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_TEST_PATTERN_GREENR,
		.type		= V4L2_CTRL_TYPE_INTEGER,
		.min		= 0,
		.max		= 65535,
		.step		= 1,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_TEST_PATTERN_GREENB,
		.type		= V4L2_CTRL_TYPE_INTEGER,
		.min		= 0,
		.max		= 65535,
		.step		= 1,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_TEST_PATTERN_BLUE,
		.type		= V4L2_CTRL_TYPE_INTEGER,
		.min		= 0,
		.max		= 65535,
		.step		= 1,
	}, {
		.ops		= &onsemi_core_ctrl_ops,
		.id		= V4L2_CID_LINK_FREQ,
		.type		= V4L2_CTRL_TYPE_INTEGER_MENU,
		.flags		= (V4L2_CTRL_FLAG_READ_ONLY |
				   V4L2_CTRL_FLAG_VOLATILE),
		.min		= 0,
		.max		= 0,
	},
};


static struct v4l2_subdev_core_ops const	onsemi_subdev_core_ops = {
	.ioctl			= onsemi_core_ioctl,
	.s_power		= onsemi_s_power,

#ifdef CONFIG_VIDEO_ADV_DEBUG
	.s_register		= onsemi_s_register,
	.g_register		= onsemi_g_register,
#endif
};

static struct v4l2_subdev_video_ops const	onsemi_subdev_video_ops = {
	.g_parm			= onsemi_g_parm,
	.g_mbus_config		= onsemi_g_mbus_config,
	.s_stream		= onsemi_s_stream,
	.g_frame_interval	= onsemi_g_frame_interval,
	.s_frame_interval	= onsemi_s_frame_interval,
};

static struct v4l2_subdev_pad_ops const		onsemi_subdev_pad_ops = {
	.enum_mbus_code		= onsemi_enum_mbus_code,
	.set_fmt		= onsemi_set_fmt,
	.get_fmt		= onsemi_get_fmt,
	.set_selection		= onsemi_set_selection,
	.get_selection		= onsemi_get_selection,
	.link_validate		= onsemi_link_validate,
};

static struct v4l2_subdev_ops const		onsemi_subdev_ops = {
	.core			= &onsemi_subdev_core_ops,
	.video			= &onsemi_subdev_video_ops,
	.pad			= &onsemi_subdev_pad_ops,
};

static int onsemi_setup_single_ctrl(struct onsemi_core *onsemi,
				    struct v4l2_ctrl_config const *ctrl_tmpl)
{
	struct onsemi_limits const	*limits = onsemi->limits;
	struct v4l2_ctrl_config		ctrl = *ctrl_tmpl;
	struct v4l2_ctrl		*cptr;
	int				rc;

	rc = onsemi->ctrls.error;
	if (WARN_ON_ONCE(rc < 0))
		return rc;

	switch (ctrl.id) {
	case V4L2_CID_HBLANK:
		ctrl.min = limits->hblank_min;
		ctrl.def = ctrl.min;
		break;
	case V4L2_CID_VBLANK:
		ctrl.min = limits->vblank_min;
		ctrl.def = ctrl.min;
		break;
	case V4L2_CID_LINK_FREQ:
		ctrl.qmenu_int = &onsemi->pll_freq->link_freq;
		break;
	default:
		break;
	}

	if (onsemi->ops->ctrl_setup_pre &&
	    !onsemi->ops->ctrl_setup_pre(onsemi, &ctrl))
		/* control filtered out */
		return 0;

	dev_dbg(onsemi->dev, "%s: adding '%s'\n", __func__, ctrl.name);

	cptr = v4l2_ctrl_new_custom(&onsemi->ctrls, &ctrl, onsemi);
	rc = onsemi->ctrls.error;
	if (rc < 0) {
		v4l2_warn(&onsemi->subdev,
			  "failed to register control '%s' (%x): %d\n",
			  ctrl.name ? ctrl.name : v4l2_ctrl_get_name(ctrl.id),
			  ctrl.id, rc);
		goto out;
	}

	if (onsemi->ops->ctrl_setup_post)
		onsemi->ops->ctrl_setup_post(onsemi, cptr);

	rc = 0;

out:
	return rc;
}

static int onsemi_setup_ctrls(struct onsemi_core *onsemi)
{
	size_t			i;
	int			rc = 0;

	for (i = 0; i < ARRAY_SIZE(onsemi_core_ctrls) && !(rc < 0); ++i)
		rc = onsemi_setup_single_ctrl(onsemi, &onsemi_core_ctrls[i]);

	for (i = 0; i < onsemi->ops->num_ctrls && !(rc < 0); ++i)
		rc = onsemi_setup_single_ctrl(onsemi, &onsemi->ops->ctrls[i]);

	return rc;
}

static int onsemi_subdev_registered(struct v4l2_subdev *sd)
{
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	int			rc;

	rc = v4l2_ctrl_handler_setup(&onsemi->ctrls);
	if (rc < 0) {
		v4l2_err(sd, "failed to setup controls: %d\n", rc);
		goto out;
	}

	rc = 0;

out:
	return rc;
}

static struct v4l2_subdev_internal_ops const	onsemi_subdev_internal_ops = {
	.registered		= onsemi_subdev_registered,
};

static int onsemi_fill_v4l_parm(struct onsemi_core *onsemi,
				 struct onsemi_v4l_parm *parm)
{
	int			rc;
	unsigned int		x[2];
	unsigned int		y[2];
	size_t			i;
	struct v4l2_subdev_mbus_code_enum	mbus_code = {
		.index	= 0,
	};

	for (i = 0; i < ARRAY_SIZE(onsemi->bus_info); ++i) {
		if (onsemi->bus_info[i].is_used) {
			mbus_code.pad = i;
			break;
		}
	}

	rc = 0;
	y[0] = onsemi_read(&rc, onsemi, 0x3002); /* x_addr_start */
	x[0] = onsemi_read(&rc, onsemi, 0x3004); /* y_addr_start */
	y[1] = onsemi_read(&rc, onsemi, 0x3006); /* x_addr_end */
	x[1] = onsemi_read(&rc, onsemi, 0x3008); /* y_addr_end */

	if (rc < 0) {
		dev_err(onsemi->dev, "failed to read active window: %d\n", rc);
		goto out;
	}

	if (x[0] > x[1] || y[0] > y[1] ||
	    x[1] - x[0]  <  onsemi->limits->x.min ||
	    y[1] - y[0]  <  onsemi->limits->y.min ||
	    x[1] - x[0] >=  onsemi->limits->x.max ||
	    y[1] - y[0] >=  onsemi->limits->y.max) {
		dev_warn(onsemi->dev, "unexpected window (%d,%d)-(%d, %d)\n",
			 x[0], y[0], x[1], y[1]);
		rc = -EINVAL;
		goto out;
	}

	parm->frame = (struct v4l2_frmsize_discrete) {
		.width  = x[1] - x[0] + 1,
		.height = y[1] - y[0] + 1,
	};

	parm->crop = (struct v4l2_rect) {
		.left	= x[0],
		.top	= y[0],
		.width  = x[1] - x[0] + 1,
		.height = y[1] - y[0] + 1,
	};

	parm->bpp     = 8;
	parm->x_scale = 1;
	parm->y_scale = 1;
	parm->hblank = onsemi->limits->hblank_min;
	parm->vblank = onsemi->limits->vblank_min;
	parm->x_skip = 1;
	parm->y_skip = 1;
	parm->data_pedestal = onsemi_read(&rc, onsemi, 0x301e);

	rc = onsemi_enum_mbus_code(&onsemi->subdev, NULL, &mbus_code);
	if (rc < 0)
		goto out;

	parm->code = mbus_code.code;

	rc = 0;

out:
	return rc;
}

static int onsemi_subdev_link_validate(struct media_link *link)
{
	return 0;
}

static int onsemi_subdev_link_setup(struct media_entity *entity,
				    struct media_pad const *local,
				    struct media_pad const *remote,
				    u32 flags)
{
	struct v4l2_subdev	*sd =
		media_entity_to_v4l2_subdev(entity);
	struct onsemi_core	*onsemi = sd_to_onsemi(sd);
	struct onsemi_businfo const	*bus_info =
		onsemi_get_businfo(onsemi, local->index);
	int				rc = 0;

	if (WARN_ON(!bus_info || !onsemi->v4l_parm))
		return -EINVAL;

	if (onsemi_is_streaming(onsemi)) {
		dev_dbg(onsemi->dev, "device is streaming; can not setup links\n");
		return -EBUSY;
	}

	if (WARN_ON(test_bit(ONSEMI_FLAG_V4L_POWERED, &onsemi->flags)))
		return -EBUSY;

	if (flags & MEDIA_LNK_FL_ENABLED) {
		if (onsemi->active_bus && onsemi->active_bus != bus_info) {
			dev_dbg(onsemi->dev, "another link is already active\n");
			return -EBUSY;
		}

		rc = onsemi_calculate_pll(onsemi, bus_info, onsemi->v4l_parm->bpp,
					  onsemi->pll_cfg, onsemi->pll_freq);
		if (rc < 0) {
			dev_dbg(onsemi->dev, "bad PLL setup: %d\n", rc);
			goto out;
		}

		onsemi->active_bus = bus_info;
	} else {
		if (onsemi->active_bus == bus_info) {
			onsemi->active_bus = NULL;
			onsemi->pll_freq->link_freq = 0;
		}
	}

out:
	return rc;
}

static struct media_entity_operations const	onsemi_entity_ops = {
	.link_validate	= onsemi_subdev_link_validate,
	.link_setup	= onsemi_subdev_link_setup,
};

int onsemi_core_v4l_init(struct onsemi_core *onsemi,
			 struct onsemi_v4l_parm *parm,
			 struct onsemi_dev_cfg const *cfg)
{
	/* HACK: we need this below in v4l2_i2c_subdev_init() although rest of
	 * code uses regmap */
	struct i2c_client	*i2c = to_i2c_client(onsemi->dev);
	struct v4l2_subdev	*sd = &onsemi->subdev;
	int			rc;
	size_t			i;
	unsigned int		pad_cnt;

	rc = onsemi_power_get(onsemi);
	if (rc < 0)
		return rc;

	v4l2_i2c_subdev_init(sd, i2c, &onsemi_subdev_ops);

	rc = onsemi_fill_v4l_parm(onsemi, parm);
	if (rc < 0)
		goto out;

	sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
	sd->internal_ops = &onsemi_subdev_internal_ops;

	pad_cnt = 0;
	for (i = 0; i < ARRAY_SIZE(onsemi->bus_info); ++i) {
		if (onsemi->bus_info[i].is_used) {
			onsemi->pad[i].flags = MEDIA_PAD_FL_SOURCE;
			pad_cnt = i + 1;
		}
	}

	rc = media_entity_pads_init(&sd->entity, pad_cnt, onsemi->pad);
	if (rc < 0)
		goto out;

	sd->entity.ops = &onsemi_entity_ops;
	sd->entity.function = MEDIA_ENT_F_CAM_SENSOR;

	rc = v4l2_ctrl_handler_init(&onsemi->ctrls,
				    ARRAY_SIZE(onsemi_core_ctrls) +
				    onsemi->ops->num_ctrls);
	if (rc < 0) {
		media_entity_cleanup(&sd->entity);
		dev_err(onsemi->dev,
			"failed to initialize v4l ctrl handle: %d\n", rc);
		goto out;
	}
	sd->ctrl_handler = &onsemi->ctrls;

	rc = onsemi_setup_ctrls(onsemi);
	if (rc < 0)
		goto out;

	rc = v4l2_async_register_subdev(sd);
	if (rc < 0) {
		media_entity_cleanup(&sd->entity);
		dev_err(onsemi->dev, "failed to register v4l2 subdev: %d\n", rc);
		goto out;
	}

	rc = 0;

out:
	onsemi_power_put(onsemi);

	return rc;
}
EXPORT_SYMBOL_GPL(onsemi_core_v4l_init);

int onsemi_timing_pair_read_of(struct onsemi_core const *onsemi,
			       char const *name,
			       struct onsemi_timing_map *map)
{
	struct device_node	*np;
	int			cnt;
	uint32_t		data[16 * 2];
	int			i;
	unsigned long		last_freq = 0;

	if (WARN_ON(map->tm != NULL))
		return -EINVAL;

	np = of_get_child_by_name(onsemi->dev->of_node, "timings");
	if (!np) {
		dev_warn(onsemi->dev, "missing 'timings' node\n");
		return -ENOENT;
	}

	cnt = of_property_count_elems_of_size(np, name, sizeof data[0]);
	if (cnt < 0) {
		dev_warn(onsemi->dev, "bad/missing 'timings/%s' property\n", name);
		return -ENOENT;
	}

	if (cnt == 0 || cnt % 2 || cnt > ARRAY_SIZE(data)) {
		dev_warn(onsemi->dev, "odd/bad 'timings/%s' property\n", name);
		return -ENOENT;
	}

	cnt /= 2;
	map->tm = devm_kcalloc(onsemi->dev, cnt, sizeof (map->tm)[0],
			       GFP_KERNEL);
	if (!map->tm)
		return -ENOMEM;

	of_property_read_u32_array(np, name, data, cnt * 2);
	of_node_put(np);

	for (i = 0; i < cnt; ++i) {
		unsigned long	freq = data[i * 2];
		unsigned long	val  = data[i * 2 + 1];

		dev_dbg(onsemi->dev, "%s#%d: %lu -> %lu\n", name, i, freq, val);

		if (freq <= last_freq) {
			dev_warn(onsemi->dev,
				 "bad 'timings/%s#%d' order (%lu <= %lu)\n",
				 name, i, freq, last_freq);
			devm_kfree(onsemi->dev, map->tm);
			map->tm = NULL;
			return -EINVAL;
		}

		map->tm[i] = (struct onsemi_timing) {
			.freq	= freq,
			.val	= val,
		};
	}

	map->num = cnt;

	return 0;
}
EXPORT_SYMBOL_GPL(onsemi_timing_pair_read_of);

int onsemi_timing_pair_find(struct onsemi_timing_map const *map,
			    unsigned long freq, unsigned int *val)
{
	size_t				i;
	struct onsemi_timing const	*tm = NULL;

	for (i = 0; i < map->num && !tm; ++i) {
		if (map->tm[i].freq >= freq)
			tm = &map->tm[i];
	}

	if (!tm)
		return -EINVAL;

	*val = tm->val;

	return 0;
}
EXPORT_SYMBOL_GPL(onsemi_timing_pair_find);

static int onsemi_calculate_vco(unsigned int *pll_div,
				unsigned int *pll_mul,
				struct onsemi_limits const *limits,
				unsigned long ext_hz,
				unsigned long vco_hz)
{
	struct pll_setup {
		unsigned int	div;
		unsigned int	mul;
		unsigned long	freq;
		unsigned long	delta;
	};
	struct pll_setup	best = {
		.div	= *pll_div,
		.mul	= *pll_mul,
	};

	unsigned int		div;
	unsigned int		mul;

	if (!in_range("VCO", &limits->pll_vco, vco_hz)) {
		pr_warn("%s: requested VCO %lu out of range [%lu..%lu]\n",
			__func__, vco_hz,
			limits->pll_vco.min, limits->pll_vco.max);
		return -EINVAL;
	}


	if (best.div == 0)
		best.freq = 0;
	else
		best.freq  = onsemi_clk_div_mul(ext_hz, best.div, best.div);

	if (best.freq < vco_hz)
		best.delta = vco_hz - best.freq;
	else
		best.delta = best.freq - vco_hz;

	for (div = limits->pre_pll_div.min;
	     div < limits->pre_pll_div.max && best.freq != vco_hz;
	     ++div) {
		unsigned long	freq = 0;

		for (mul = round_up(limits->pre_pll_mul.min, 2);
		     mul < limits->pre_pll_mul.max &&
			     freq < limits->pll_vco.max &&
			     best.freq != vco_hz;
		     mul += 2) {
			uint64_t	delta;

			freq = onsemi_clk_div_mul(ext_hz, div, mul);

			if (freq < limits->pll_vco.min ||
			    freq > limits->pll_vco.max)
				continue;

			if (freq < vco_hz)
				delta = vco_hz - freq;
			else
				delta = freq - vco_hz;

			if (delta < best.delta) {
				best.div = div;
				best.mul = mul;
				best.freq = freq;
				best.delta = delta;
			}
		}
	}

	pr_debug("%s: %lu / %u * %u = %llu (%lu)\n", __func__,