/*
 * (C) Copyright 2009, 2010
 * Allied Telesis <www.alliedtelesis.com>
 * Marvell Semiconductor <www.marvell.com>
 * Written-by: Prafulla Wadaskar <prafulla@marvell.com>
 *
 * See file CREDITS for list of people who contributed to this
 * project.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 */

/* based on cpu/arm926ejs/kirkwood/cpu.c */

#include <common.h>
#include <netdev.h>
#include <asm/cache.h>
#include <u-boot/md5.h>
#include <asm/arch/discovery.h>
#include <hush.h>

#define BUFLEN	16

void reset_cpu(unsigned long ignored)
{
	struct discocpu_registers *cpureg =
	    (struct discocpu_registers *)DISCO_CPU_REG_BASE;

	writel(readl(&cpureg->rstoutn_mask) | (1 << 2),
		&cpureg->rstoutn_mask);
	writel(readl(&cpureg->sys_soft_rst) | 1,
		&cpureg->sys_soft_rst);
	while (1) ;
}

/*
 * Generates Ramdom hex number reading some time varient system registers
 * and using md5 algorithm
 */
unsigned char get_random_hex(void)
{
	int i;
	u32 inbuf[BUFLEN];
	u8 outbuf[BUFLEN];

	/*
	 * in case of 88F6281/88F6192 A0,
	 * Bit7 need to reset to generate random values in DISCO_REG_UNDOC_0x1470
	 * SoC reg offsets DISCO_REG_UNDOC_0x1470 and DISCO_REG_UNDOC_0x1478 are reserved regs and
	 * Does not have names at this moment (no errata available)
	 */
	writel(readl(DISCO_REG_UNDOC_0x1478) & ~(1 << 7), DISCO_REG_UNDOC_0x1478);
	for (i = 0; i < BUFLEN; i++) {
		inbuf[i] = readl(DISCO_REG_UNDOC_0x1470);
	}
	md5((u8 *) inbuf, (BUFLEN * sizeof(u32)), outbuf);
	return outbuf[outbuf[7] % 0x0f];
}

/*
 * Window Size
 * Used with the Base register to set the address window size and location.
 * Must be programmed from LSB to MSB as sequence of ones followed by
 * sequence of zeros. The number of ones specifies the size of the window in
 * 64 KByte granularity (e.g., a value of 0x00FF specifies 256 = 16 MByte).
 * NOTE: A value of 0x0 specifies 64-KByte size.
 */
unsigned int disco_winctrl_calcsize(unsigned int sizeval)
{
	int i;
	unsigned int j = 0;
#ifdef __ATL_CHANGE__
	u32 val = sizeval;
#else
	u32 val = sizeval >> 1;
#endif /* __ATL_CHANGE__ */

	for (i = 0; val > 0x10000; i++) {
		j |= (1 << i);
		val = val >> 1;
	}
	return (0x0000ffff & j);
}

/*
 * disco_config_adr_windows - Configure address Windows
 *
 * There are 14 address windows supported by Discovery SoC to addess different
 * devices. Each window can be configured for size, BAR and remap addr
 * Below configuration is standard for most of the cases
 *
 * If remap function not used, remap_lo must be set as base
 *
 * Reference Documentation:
 * Mbus-L to Mbus Bridge Registers Configuration.
 * (Sec 3.1 and 3.2 of Datasheet)
 */
int disco_config_adr_windows(void)
{
	struct discowin_remap_registers *win0_7_remapregs =
		(struct discowin_remap_registers *)DISCO_CPU_WIN_BASE;
	struct discowin_nonremap_registers *win8_13_nonremapregs =
		(struct discowin_nonremap_registers *)(DISCO_CPU_WIN_BASE + 0x900);

	/* Window 0-7: Disabled */
	writel(DISCOCPU_WIN_DISABLE, &win0_7_remapregs[0].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win0_7_remapregs[1].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win0_7_remapregs[2].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win0_7_remapregs[3].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win0_7_remapregs[4].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win0_7_remapregs[5].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win0_7_remapregs[6].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win0_7_remapregs[7].ctrl);

	/* Window 8-12: Disabled */
	writel(DISCOCPU_WIN_DISABLE, &win8_13_nonremapregs[8 - 8].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win8_13_nonremapregs[9 - 8].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win8_13_nonremapregs[10 - 8].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win8_13_nonremapregs[11 - 8].ctrl);
	writel(DISCOCPU_WIN_DISABLE, &win8_13_nonremapregs[12 - 8].ctrl);

	/* Window 13: BOOT Memory address space */
	writel(DISCOCPU_WIN_CTRL_DATA(1024 * 1024 * 128, DISCOCPU_TARGET_MEMORY,
		DISCOCPU_ATTR_BOOTCS, DISCOCPU_WIN_ENABLE), &win8_13_nonremapregs[13 - 8].ctrl);
	writel(DISCO_DEFADR_BOOTROM, &win8_13_nonremapregs[13 - 8].base);

	return 0;
}

/*
 * SYSRSTn Duration Counter Support
 *
 * Discovery SoC implements a hardware-based SYSRSTn duration counter.
 * When SYSRSTn is asserted low, a SYSRSTn duration counter is running.
 * The SYSRSTn duration counter is useful for implementing a manufacturer
 * or factory reset. Upon a long reset assertion that is greater than a
 * pre-configured environment variable value for sysrstdelay,
 * The counter value is stored in the SYSRSTn Length Counter Register
 * The counter is based on the 25-MHz reference clock (40ns)
 * It is a 29-bit counter, yielding a maximum counting duration of
 * 2^29/25 MHz (21.4 seconds). When the counter reach its maximum value,
 * it remains at this value until counter reset is triggered by setting
 * bit 31 of DISCO_REG_SYSRST_CNT
 */
static void disco_sysrst_action(void)
{
	int ret;
	char *s = getenv("sysrstcmd");

	if (!s) {
		debug("Error.. %s failed, check sysrstcmd\n",
			__FUNCTION__);
		return;
	}

	debug("Starting %s process...\n", __FUNCTION__);
#if !defined(CONFIG_SYS_HUSH_PARSER)
	ret = run_command (s, 0);
#else
	ret = parse_string_outer(s, FLAG_PARSE_SEMICOLON
				  | FLAG_EXIT_FROM_LOOP);
#endif
	if (ret < 0)
		debug("Error.. %s failed\n", __FUNCTION__);
	else
		debug("%s process finished\n", __FUNCTION__);
}

static void disco_sysrst_check(void)
{
	u32 sysrst_cnt, sysrst_dly;
	char *s;

	/*
	 * no action if sysrstdelay environment variable is not defined
	 */
	s = getenv("sysrstdelay");
	if (s == NULL)
		return;

	/* read sysrstdelay value */
	sysrst_dly = (u32) simple_strtoul(s, NULL, 10);

	/* read SysRst Length counter register (bits 28:0) */
	sysrst_cnt = (0x1fffffff & readl(DISCO_REG_SYSRST_CNT));
	debug("H/W Rst hold time: %d.%d secs\n",
		sysrst_cnt / SYSRST_CNT_1SEC_VAL,
		sysrst_cnt % SYSRST_CNT_1SEC_VAL);

	/* clear the counter for next valid read*/
	writel(1 << 31, DISCO_REG_SYSRST_CNT);

	/*
	 * sysrst_action:
	 * if H/w Reset key is pressed and hold for time
	 * more than sysrst_dly in seconds
	 */
	if (sysrst_cnt >= SYSRST_CNT_1SEC_VAL * sysrst_dly)
		disco_sysrst_action();
}

#if defined(CONFIG_DISPLAY_CPUINFO)
int print_cpuinfo(void)
{
	char *name = "Unknown";
	unsigned int devrev;

	devrev = readl(DISCO_REG_DEVVEN_ID) & 0xffff0000;
	devrev |= readl(DISCO_REG_CLASSREV_ID) & 0x000000ff;

	switch (devrev) {
	case 0x78100001:
		name = "MV78100_A0";
		break;
	case 0x78100002:
		name = "MV78100_A1";
		break;
	default:
		printf("SoC:   Unsupported Discovery (%08x)\n", devrev);
		return -1;
	}
	printf("SoC:   Discovery %s\n", name);
	return 0;
}
#endif /* CONFIG_DISPLAY_CPUINFO */

#ifdef CONFIG_ARCH_CPU_INIT
int arch_cpu_init(void)
{
	u32 reg;
	struct discocpu_registers *cpureg =
		(struct discocpu_registers *)DISCO_CPU_REG_BASE;

	/* Linux expects the internal registers to be at 0xf1000000 */
	writel(DISCO_REGS_PHY_BASE, DISCO_OFFSET_REG);

	/* Enable and invalidate L2 cache in write through mode */
	writel(readl(&cpureg->l2_cfg) | 0x18, &cpureg->l2_cfg);
	invalidate_l2_cache();

	disco_config_adr_windows();

#ifdef CONFIG_DISCOVERY_RGMII_PAD_1V8
	/*
	 * Configures the I/O voltage of the pads connected to Egigabit
	 * Ethernet interface to 1.8V
	 * By defult it is set to 3.3V
	 */
	reg = readl(DISCO_REG_MPP_OUT_DRV_REG);
	reg |= (1 << 7);
	writel(reg, DISCO_REG_MPP_OUT_DRV_REG);
#endif
#ifdef CONFIG_DISCOVERY_EGIGA_INIT
	/*
	 * Set egiga port0/1 in normal functional mode
	 * This is required becasue on discovery by default ports are in reset mode
	 * OS egiga driver may not have provision to set them in normal mode
	 * and if u-boot is build without network support, network may fail at OS level
	 */
	reg = readl(DISCOGBE_PORT_SERIAL_CONTROL1_REG(0));
	reg &= ~(1 << 4);	/* Clear PortReset Bit */
	writel(reg, (DISCOGBE_PORT_SERIAL_CONTROL1_REG(0)));
	reg = readl(DISCOGBE_PORT_SERIAL_CONTROL1_REG(1));
	reg &= ~(1 << 4);	/* Clear PortReset Bit */
	writel(reg, (DISCOGBE_PORT_SERIAL_CONTROL1_REG(1)));
#endif
#ifdef CONFIG_DISCOVERY_PCIE_INIT
	/*
	 * Enable PCI Express Port0 and Port1
	 */
	reg = readl(&cpureg->ctrl_stat);
	reg |= (1 << 0);	/* Set PEX0En Bit */
	reg |= (1 << 1);	/* Set PEX1En Bit */
	writel(reg, &cpureg->ctrl_stat);
#endif
	return 0;
}
#endif /* CONFIG_ARCH_CPU_INIT */

/*
 * SOC specific misc init
 */
// TODO: Do we need to enable this for DISCO ???
#if defined(CONFIG_ARCH_MISC_INIT)
int arch_misc_init(void)
{
	volatile u32 temp;

	/*CPU streaming & write allocate */
	temp = readfr_extra_feature_reg();
	temp &= ~(1 << 28);	/* disable wr alloc */
	writefr_extra_feature_reg(temp);

	temp = readfr_extra_feature_reg();
	temp &= ~(1 << 29);	/* streaming disabled */
	writefr_extra_feature_reg(temp);

#if defined(CONFIG_L2_CACHE)
	/* L2Cache settings */
	temp = readfr_extra_feature_reg();
	/* Disable L2C pre fetch - Set bit 24 */
	temp |= (1 << 24);
	/* enable L2C - Set bit 22 */
	temp |= (1 << 22);
	writefr_extra_feature_reg(temp);
#endif

	icache_enable();
	/* Change reset vector to address 0x0 */
	temp = get_cr();
	set_cr(temp & ~CR_V);

	/* checks and execute resset to factory event */
	disco_sysrst_check();

	return 0;
}
#endif /* CONFIG_ARCH_MISC_INIT */

#ifdef CONFIG_DISCOVERY_EGIGA
int cpu_eth_init(bd_t *bis)
{
	discovery_egiga_initialize(bis);
	return 0;
}
#endif
