/* SPDX-FileCopyrightText: 2024 2024 CERN (home.cern)
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 * Author: Vaibhav Gupta <vaibhav.gupta@cern.ch>
 */

#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/platform_data/i2c-ocores.h>
#include <uapi/linux/ipmi/fru.h>
#include "fmc-adc-100m14b4cha-private.h"

/* Si570 registers */
#define SI570_DIV_OFFSET_7PPM	6

#define HS_DIV_SHIFT		5
#define HS_DIV_MASK		0xe0
#define HS_DIV_OFFSET		4
#define N1_6_2_MASK		0x1f
#define N1_1_0_MASK		0xc0
#define RFREQ_37_32_MASK	0x3f

#define SI570_MIN_FREQ		10000000L
#define SI570_MAX_FREQ		1417500000L
#define SI598_MAX_FREQ		525000000L

#define FDCO_MIN		4850000000LL
#define FDCO_MAX		5670000000LL

#define SI570_CNTRL_RECALL	(1 << 0)
#define SI570_CNTRL_FREEZE_M	(1 << 5)
#define SI570_CNTRL_NEWFREQ	(1 << 6)

#define SI570_FREEZE_DCO	(1 << 4)

#define SI570_I2C_MASTER_OFF 0x1600
#define SI570_I2C_MASTER_SIZE 0x100

#define SI570_I2C_OFF 0X57

#define SI570_FMC_ADC_FREQ	       100000000L
#define SI570_570BBC000876DG_INIT_FREQ 49870130L

struct clk_si570 {
	unsigned int div_offset;
	u64 fxtal;
	unsigned int n1;
	unsigned int hs_div;
	u64 rfreq;
	u64 frequency;
	struct fa_dev *fa;
};

static struct resource si570_i2c_master_res = {
	.name   = "si570_i2c_master_res",
	.start	= SI570_I2C_MASTER_OFF,
	.end	= SI570_I2C_MASTER_OFF + SI570_I2C_MASTER_SIZE - 1,
	.flags	= IORESOURCE_MEM,
};

#define SI570_I2C_MASTER_CLK_HZ 125000000
#define SI570_I2C_MASTER_CLK_KHZ (SI570_I2C_MASTER_CLK_HZ / 1000)

static struct ocores_i2c_platform_data si570_i2c_master_data = {
	.reg_shift	  = 2,		/* two bytes between registers */
	.reg_io_width     = 4,
	.clock_khz	  = SI570_I2C_MASTER_CLK_KHZ,
	.num_devices      = 0,
	.devices	  = NULL,
};

int fa_si570_i2c_read_reg(struct fa_dev *fa, u8 reg_addr, u8 *val)
{
	struct i2c_msg msg[2];
	struct i2c_adapter *adap = fa->si570_i2c_adapter;

	msg[0].addr = SI570_I2C_OFF;
	msg[0].flags = 0x0;
	msg[0].len = 1;
	msg[0].buf = &reg_addr;

	msg[1].addr = SI570_I2C_OFF;
	msg[1].flags = I2C_M_RD;
	msg[1].len   = 1;
	msg[1].buf   = val;

	return i2c_transfer(adap, msg, 2);
}

int fa_si570_i2c_write_reg(struct fa_dev *fa, u8 reg_addr, u8 val)
{
	struct i2c_msg msg[2];
	struct i2c_adapter *adap = fa->si570_i2c_adapter;

	msg[0].addr = SI570_I2C_OFF;
	msg[0].flags = 0x0;
	msg[0].len = 1;
	msg[0].buf = &reg_addr;

	msg[1].addr = SI570_I2C_OFF;
	msg[1].flags = I2C_M_NOSTART | 0x0;
	msg[1].len = 1;
	msg[1].buf = &val;

	return i2c_transfer(adap, msg, 2);
}

/**
 * si570_get_divs() - Read clock dividers from HW
 * @data:	Pointer to struct clk_si570
 * @rfreq:	Fractional multiplier (output)
 * @n1:		Divider N1 (output)
 * @hs_div:	Divider HSDIV (output)
 * Returns 0 on success, negative errno otherwise.
 *
 * Retrieve clock dividers and multipliers from the HW.
 */
static int si570_get_divs(struct clk_si570 *data, u64 *rfreq,
		unsigned int *n1, unsigned int *hs_div)
{
	u8 reg[6];
	int i, err;
	u64 tmp;

	struct fa_dev *fa = data->fa;

	for (i = SI570_REG_HS_N1; i <= SI570_REG_RFREQ4; i++) {
		err = fa_si570_i2c_read_reg(fa, i,
						reg + i - SI570_REG_HS_N1);

		if (err < 0)
			return err;
	}

	*hs_div = ((reg[0] & HS_DIV_MASK) >> HS_DIV_SHIFT) + HS_DIV_OFFSET;
	*n1 = ((reg[0] & N1_6_2_MASK) << 2) + ((reg[1] & N1_1_0_MASK) >> 6) + 1;
	/* Handle invalid cases */
	if (*n1 > 1)
		*n1 &= ~1;

	tmp = reg[1] & RFREQ_37_32_MASK;
	tmp = (tmp << 8) + reg[2];
	tmp = (tmp << 8) + reg[3];
	tmp = (tmp << 8) + reg[4];
	tmp = (tmp << 8) + reg[5];
	*rfreq = tmp;

	return 0;
}

/**
 * si570_get_defaults() - Get default values
 * @data:	Driver data structure
 * @fout:	Factory frequency output
 * Returns 0 on success, negative errno otherwise.
 */
static int si570_get_defaults(struct clk_si570 *data, u64 fout)
{
	int err;
	u64 fdco;
	struct fa_dev *fa = data->fa;

	err = fa_si570_i2c_write_reg(fa, SI570_REG_CONTROL, SI570_CNTRL_RECALL);

	if (err < 0)
		return err;

	err = si570_get_divs(data, &data->rfreq, &data->n1, &data->hs_div);
	if (err)
		return err;

	/*
	 * Accept optional precision loss to avoid arithmetic overflows.
	 * Acceptable per Silicon Labs Application Note AN334.
	 */
	fdco = fout * data->n1 * data->hs_div;
	if (fdco >= (1LL << 36))
		data->fxtal = div64_u64(fdco << 24, data->rfreq >> 4);
	else
		data->fxtal = div64_u64(fdco << 28, data->rfreq);

	data->frequency = fout;

	return 0;
}

/**
 * si570_update_rfreq() - Update clock multiplier
 * @data:	Driver data structure
 * Passes on regmap_bulk_write() return value.
 */
static int si570_update_rfreq(struct clk_si570 *data)
{
	u8 reg[5];
	int i, err;
	struct fa_dev *fa = data->fa;

	reg[0] = ((data->n1 - 1) << 6) |
		((data->rfreq >> 32) & RFREQ_37_32_MASK);
	reg[1] = (data->rfreq >> 24) & 0xff;
	reg[2] = (data->rfreq >> 16) & 0xff;
	reg[3] = (data->rfreq >> 8) & 0xff;
	reg[4] = data->rfreq & 0xff;

	for (i = SI570_REG_N1_RFREQ0; i <= SI570_REG_RFREQ4; i++) {
		err = fa_si570_i2c_write_reg(fa, i,
					*(reg + i - SI570_REG_N1_RFREQ0));

		if (err < 0)
			return err;
	}

	return 0;
}

/**
 * si570_calc_divs() - Caluclate clock dividers
 * @frequency:	Target frequency
 * @data:	Driver data structure
 * @out_rfreq:	RFREG fractional multiplier (output)
 * @out_n1:	Clock divider N1 (output)
 * @out_hs_div:	Clock divider HSDIV (output)
 * Returns 0 on success, negative errno otherwise.
 *
 * Calculate the clock dividers (@out_hs_div, @out_n1) and clock multiplier
 * (@out_rfreq) for a given target @frequency.
 */
static int si570_calc_divs(unsigned long frequency, struct clk_si570 *data,
		u64 *out_rfreq, unsigned int *out_n1, unsigned int *out_hs_div)
{
	int i;
	unsigned int n1, hs_div;
	u64 fdco, best_fdco = ULLONG_MAX;
	static const uint8_t si570_hs_div_values[] = { 11, 9, 7, 6, 5, 4 };

	for (i = 0; i < ARRAY_SIZE(si570_hs_div_values); i++) {
		hs_div = si570_hs_div_values[i];
		/* Calculate lowest possible value for n1 */
		n1 = div_u64(div_u64(FDCO_MIN, hs_div), frequency);
		if (!n1 || (n1 & 1))
			n1++;
		while (n1 <= 128) {
			fdco = (u64)frequency * (u64)hs_div * (u64)n1;
			if (fdco > FDCO_MAX)
				break;
			if (fdco >= FDCO_MIN && fdco < best_fdco) {
				*out_n1 = n1;
				*out_hs_div = hs_div;
				*out_rfreq = div64_u64(fdco << 28, data->fxtal);
				best_fdco = fdco;
			}
			n1 += (n1 == 1 ? 1 : 2);
		}
	}

	if (best_fdco == ULLONG_MAX)
		return -EINVAL;

	return 0;
}

static unsigned long si570_recalc_rate(struct clk_si570 *data)
{
	int err;
	u64 rfreq, rate;
	unsigned int n1, hs_div;
	struct i2c_adapter *adap = data->fa->si570_i2c_adapter;

	err = si570_get_divs(data, &rfreq, &n1, &hs_div);
	if (err) {
		dev_err(&adap->dev, "unable to recalc rate of i2c clock\n");
		return data->frequency;
	}

	rfreq = div_u64(rfreq, hs_div * n1);
	rate = (data->fxtal * rfreq) >> 28;

	return rate;
}

/**
 * si570_set_frequency() - Adjust output frequency
 * @data:	Driver data structure
 * @frequency:	Target frequency
 * Returns 0 on success.
 *
 * Update output frequency for big frequency changes (> 3,500 ppm).
 */

static int si570_set_frequency(struct clk_si570 *data, unsigned long frequency)
{
	int err;
	struct fa_dev *fa = data->fa;

	err = si570_calc_divs(frequency, data, &data->rfreq, &data->n1,
			&data->hs_div);
	if (err)
		return err;

	/*
	 * The DCO reg should be accessed with a read-modify-write operation
	 * per AN334
	 */

	err = fa_si570_i2c_write_reg(fa, SI570_REG_FREEZE_DCO, SI570_FREEZE_DCO);
	if (err < 0)
		goto out;

	err = fa_si570_i2c_write_reg(fa, SI570_REG_HS_N1,
			((data->hs_div - HS_DIV_OFFSET) << HS_DIV_SHIFT) |
			(((data->n1 - 1) >> 2) & N1_6_2_MASK));
	if (err < 0)
		goto out;

	err = si570_update_rfreq(data);
	if (err < 0)
		goto out;

	err = fa_si570_i2c_write_reg(fa, SI570_REG_FREEZE_DCO, 0);
	if (err < 0)
		return err;

	err = fa_si570_i2c_write_reg(fa, SI570_REG_CONTROL, SI570_CNTRL_NEWFREQ);
	if (err < 0)
		return err;
	/* Applying a new frequency can take up to 10ms */
	usleep_range(10000, 12000);

	data->frequency = si570_recalc_rate(data);

	return 0;

out:
	fa_si570_i2c_write_reg(fa, SI570_REG_FREEZE_DCO, 0);
	/* There is no point in checking if the baove write failed as we
	 * are here because everything before this failed.
	 */
	return err;

}

static int si570_i2c_set_frequency(struct fa_dev *fa)
{
	int ret;
	void *fru = NULL;
	char *fmc_adc_part_number = NULL;
	struct clk_si570 clock_data;
	struct i2c_adapter *adap = fa->si570_i2c_adapter;

	fru = kmalloc(FRU_SIZE_MAX, GFP_KERNEL);
	if (!fru)
		return -ENOMEM;

	ret = fmc_slot_eeprom_read(fa->slot, fru, 0x0, FRU_SIZE_MAX);
	if (ret != FRU_SIZE_MAX) {
		dev_err(fa->msgdev, "Failed to read FRU header\n");
		//goto err;
	}

	//fmc_adc_part_number = fru_get_part_number(fru);
	//ret = strcmp(fmc_adc_part_number, "EDA-02063-v7-0");

	/* At the moment, we need to set the clock only for EDA-02063-v7-0.
	 * Previous versions already have 100MHz as their default value.
	 * But that will require more tweaks as this card is still under
	 * testing and does not have an FRU. So we will skip the part for
	 * checking FRU and make tests only on the new card.
	 */
	dev_info(&adap->dev, "Configuring Si570 clock.");

	clock_data.fa = fa;
	ret = si570_get_defaults(&clock_data, SI570_570BBC000876DG_INIT_FREQ);
	if (ret)
		goto err;

	ret = si570_set_frequency(&clock_data, SI570_FMC_ADC_FREQ);
	if (ret)
		goto err;

	dev_info(&adap->dev, "Configured Si570 clock to %lluHz.", clock_data.frequency);
	return 0;


err:
	return ret;
}

static int fa_si570_i2c_find_adapter(struct device *dev, void *data)
{
	struct i2c_adapter *adap;
	struct platform_device *pdev = data;

	if (dev->type != &i2c_adapter_type)
		return 0;

	adap = to_i2c_adapter(dev);

	if (adap->dev.parent != &pdev->dev)
		return 0;

	return adap->nr;
}

int fa_si570_i2c_init(struct fa_dev *fa)
{
	int idr, ret;
	struct platform_device *pdev;
	struct resource *rmem;

	rmem = platform_get_resource(fa->pdev, IORESOURCE_MEM,
				     ADC_MEM_BASE);
	if (!rmem) {
		dev_err(&fa->pdev->dev, "Missing memory resource\n");
		return -EINVAL;
	}

	si570_i2c_master_res.parent = rmem;
	si570_i2c_master_res.start  = rmem->start + SI570_I2C_MASTER_OFF;
	si570_i2c_master_res.end    = si570_i2c_master_res.start +
					SI570_I2C_MASTER_SIZE - 1;

	si570_i2c_master_data.big_endian = fa_is_flag_set(fa, FMC_ADC_BIG_ENDIAN);

	pdev = platform_device_alloc("ocores-i2c", PLATFORM_DEVID_AUTO);

	ret = platform_device_add_resources(pdev, &si570_i2c_master_res, 1);
	if (ret)
		goto out;

	ret = platform_device_add_data(pdev, &si570_i2c_master_data, sizeof(si570_i2c_master_data));
	if (ret)
		goto out;

	ret = platform_device_add(pdev);
	if (ret)
		goto out;

	idr = i2c_for_each_dev(pdev, fa_si570_i2c_find_adapter);

	if (idr < 0) {
		dev_err(&fa->pdev->dev, "Could not acquire i2C Adapter\n");
		return idr;
	}

	fa->si570_i2c_adapter = i2c_get_adapter(idr);

	ret = si570_i2c_set_frequency(fa);

	if (ret)
		goto out;

	return 0;

out:
	platform_device_put(pdev);
	return -1;

}

void fa_si570_i2c_exit(struct fa_dev *fa)
{
	struct platform_device *pdev;
	struct i2c_adapter *adap = fa->si570_i2c_adapter;

	pdev = container_of(adap->dev.parent, struct platform_device,
			    dev);

	i2c_put_adapter(adap);

	platform_device_unregister(pdev);
}

