/*
 * (C) Copyright 2001
 * Josh Huber <huber@mclx.com>, Mission Critical Linux, Inc.
 *
 * 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., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 */

/* sdram_init.c - automatic memory sizing */

#include <ppcboot.h>
#include <74xx_7xx.h>
#include <galileo/memory.h>
#include <galileo/pci.h>
#include <galileo/gt64260R.h>
#include <net.h>

#include "eth.h"
#include "mpsc.h"
#include "i2c.h"
#include "64260.h"

#undef	DEBUG
#define	MAP_PCI

#ifdef DEBUG
#define DP(x) x
#else
#define DP(x)
#endif

/* ------------------------------------------------------------------------- */

int
memory_map_bank(unsigned int bankNo,
		unsigned int bankBase,
		unsigned int bankLength) 
{
#ifdef DEBUG
	if (bankLength > 0) {
		printf("\nmapping bank %d at %08x - %08x",
		       bankNo, bankBase, bankBase + bankLength - 1);
	} else {
		printf("\nunmapping bank %d", bankNo);
	}
#endif

        switch(bankNo) {
        case 0:
                memoryMapBank0(bankBase, bankLength);
#ifdef MAP_PCI
		pci0MapMemoryBank0(bankBase, bankLength);
		pci1MapMemoryBank0(bankBase, bankLength);
#endif
                return(true);
                break;
        case 1:
                memoryMapBank1(bankBase, bankLength);
#ifdef MAP_PCI
		pci0MapMemoryBank1(bankBase, bankLength);
		pci1MapMemoryBank1(bankBase, bankLength);
#endif
                return(true);
                break;
        case 2:
                memoryMapBank2(bankBase, bankLength);
#ifdef MAP_PCI
		pci0MapMemoryBank2(bankBase, bankLength);
		pci1MapMemoryBank2(bankBase, bankLength);
#endif
                return(true);
                break;
        case 3:
                memoryMapBank3(bankBase, bankLength);
#ifdef MAP_PCI
		pci0MapMemoryBank3(bankBase, bankLength);
		pci1MapMemoryBank3(bankBase, bankLength);
#endif
                return(true);
                break;
        default:
                return(0);
        }
}

#define GB         (1 << 29)

/* much of this code is based on (or is) the code in the pip405 port */
/* thanks go to the authors of said port - Josh */

/* structure to store the relevant information about an sdram bank */
typedef struct sdram_info {
	uchar drb_size;
	uchar registered, ecc;
	uchar tpar;
	uchar tras_clocks;
	uchar burst_len;
	uchar banks, slot;
} sdram_info_t;

/*
 * translate ns.ns/10 coding of SPD timing values
 * into 10 ps unit values
 */

static unsigned short
NS10to10PS(unsigned char spd_byte)
{
	unsigned short ns, ns10;

	/* isolate upper nibble */
	ns = (spd_byte >> 4) & 0x0F;
	/* isolate lower nibble */
	ns10 = (spd_byte & 0x0F);

	return(ns*100 + ns10*10);
}

/*
 * translate ns coding of SPD timing values
 * into 10 ps unit values
 */

static unsigned short
NSto10PS(unsigned char spd_byte)
{
	return(spd_byte*100);
}

/* This code reads the SPD chip on the sdram and populates
 * the array which is passed in with the relevant information */
static int
check_dimm(uchar addr, uchar slot, sdram_info_t *info)
{
	int ret;
	uchar rows, cols, sdram_banks, supp_cal, width, cal_val;
	ulong memclk, tmemclk;
	uchar trp_clocks, trcd_clocks;
	uchar data[128];

	memclk = get_bus_freq(0);
 	tmemclk = 1000000000 / (memclk / 100);  /* in 10 ps units */

	DP(puts("before i2c read\n"));

	ret = i2c_read(addr, 0, 128, data, 0);

	DP(puts("after i2c read\n"));

	/* zero all the values */
	memset(info, 0, sizeof(*info));

	if (ret) {
		DP(printf("No DIMM in slot %d [err = %x]\n", slot, ret));
		return 0;
	}

	/* first, do some sanity checks */
	if (data[2] != 0x4) {
		printf("Not SDRAM in slot %d\n", slot);
		return 0;
	}

	/* get various information */
	rows = data[3];
	cols = data[4];
	info->banks = data[5];
	sdram_banks = data[17];
	width = data[13] & 0x7f;

	DP(printf("sdram_banks: %d, banks: %d\n", sdram_banks, info->banks));

	/* check if the memory is registered */
	if (data[21] & (BIT1 & BIT4))
		info->registered = 1;

#ifdef CONFIG_ECC
	/* check for ECC/parity [0 = none, 1 = parity, 2 = ecc] */
	info->ecc = (data[11] & 2) >> 1;
#endif

	/* bit 1 is CL2, bit 2 is CL3 */
	supp_cal = (data[18] & 0x6) >> 1;

	/* compute the relevant clock values */
	trp_clocks = (NSto10PS(data[27])+(tmemclk-1)) / tmemclk;
	trcd_clocks = (NSto10PS(data[29])+(tmemclk-1)) / tmemclk;
	info->tras_clocks = (NSto10PS(data[30])+(tmemclk-1)) / tmemclk;

	DP(printf("trp = %d\ntrcd_clocks = %d\ntras_clocks = %d\n",
		  trp_clocks, trcd_clocks, info->tras_clocks));

	/* try a CAS latency of 3 first... */
	cal_val = 0;
	if (supp_cal & 3) {
		if (NS10to10PS(data[9]) <= tmemclk)
			cal_val = 3;
	}

	/* then 2... */
	if (supp_cal & 2) {
		if (NS10to10PS(data[23]) <= tmemclk)
			cal_val = 2;
	}

	DP(printf("cal_val = %d\n", cal_val));

	/* bummer, did't work... */
	if (cal_val == 0) {
		DP(printf("Couldn't find a good CAS latency\n"));
		return 0;
	}

	/* get the largest delay -- these values need to all be the same
	 * see Res#6 */
	info->tpar = cal_val;
	if (trp_clocks > info->tpar)
		info->tpar = trp_clocks;
	if (trcd_clocks > info->tpar)
		info->tpar = trcd_clocks;

	DP(printf("tpar set to: %d\n", info->tpar));

	/* compute the module DRB size */
	info->drb_size = (((1 << (rows + cols)) * sdram_banks) * width) / _16M;

	/* find the burst len */
	info->burst_len = data[16] & 0xf;
	if ((info->burst_len & 8) == 8) {
		info->burst_len = 1;
	} else if ((info->burst_len & 4) == 4) {
		info->burst_len = 0;
	} else
		return 0;

	info->slot = slot;

	return 0;
}

/* sets up the GT properly with information passed in */
int
setup_sdram(sdram_info_t *info)
{
	ulong tmp, check;
	ulong *addr = 0;
	int i;

	/* sanity checking */
	if (! info->banks) {
		printf("setup_sdram called with 0 banks\n");
		return 1;
	}

	/* ---------------------------- */
	/* Program the GT with the discovered data */

	/* bank parameters */
	tmp = 0;

	DP(printf("drb_size: %d\n", info->drb_size));
	switch (info->drb_size) {
	case 1:
		tmp |= (1 << 14);
		break;
	case 4:
	case 8:
		tmp |= (2 << 14);
		break;
	case 16:
	case 32:
		tmp |= (3 << 14);
		break;
	default:
		printf("Error in dram size calculation\n");
		return 1;
	}

	/* SDRAM bank parameters */
	/* the param registers for slot 1 (banks 2+3) are offset by 0x8 */
	DP(printf("setting up slot %d config with: %08lx\n", info->slot, tmp));
	GT_REG_WRITE(SDRAM_BANK0PARAMETERS + (info->slot * 0x8), tmp);
	GT_REG_WRITE(SDRAM_BANK1PARAMETERS + (info->slot * 0x8), tmp);

	/* SDRAM configuration */
	tmp = GTREGREAD(SDRAM_CONFIGURATION);

	tmp |= (info->registered << 17);

	/* Use buffer 1 to return read data to the CPU 
	 * See Res #12 */
	tmp |= (1 << 26);

	GT_REG_WRITE(SDRAM_CONFIGURATION, tmp);

	DP(printf("sdram_conf: %08x\n", GTREGREAD(SDRAM_CONFIGURATION)));

	/* SDRAM timing */
	DP(printf("setting timing parameters to: %d\n", info->tpar));

	tmp = (((info->tpar == 3) ? 2 : 1) |
	       (((info->tpar == 3) ? 2 : 1) << 2) |
	       (((info->tpar == 3) ? 2 : 1) << 4) |
	       (info->tras_clocks << 8) |
	       (info->ecc << 13));

	DP(printf("setting up sdram_timing with: %08lx\n", tmp));
	GT_REG_WRITE(SDRAM_TIMING, tmp);

	/* SDRAM address decode register */
	/* program this with the default value */
	GT_REG_WRITE(SDRAM_ADDRESS_DECODE, 0x2);

	DP(printf("SDRAM address decode: %08x\n",
		  GTREGREAD(SDRAM_ADDRESS_DECODE)));

	/* set the SDRAM configuration for each bank */
	for (i = info->slot * 2; i < ((info->slot * 2) + info->banks); i++) {
		DP(printf("\n*** Running a MRS cycle for bank %d ***\n", i));

		/* map the bank */
		memory_map_bank(i, 0, GB/4);

		/* set SDRAM mode */
		GT_REG_WRITE(SDRAM_OPERATION_MODE, 0x3);
		check = GTREGREAD(SDRAM_OPERATION_MODE);

		/* dummy write */
		*addr = 0;

		/* wait for the command to complete */
		while ((GTREGREAD(SDRAM_OPERATION_MODE) & (1 << 31)) == 0)
			;

		/* switch back to normal operation mode */
		GT_REG_WRITE(SDRAM_OPERATION_MODE, 0);
		check = GTREGREAD(SDRAM_OPERATION_MODE);

		/* unmap the bank */
		memory_map_bank(i, 0, 0);
	}

	return 0;
}

/*
 * Check memory range for valid RAM. A simple memory test determines
 * the actually available RAM size between addresses `base' and
 * `base + maxsize'. Some (not all) hardware errors are detected:
 * - short between address lines
 * - short between data lines
 */
static long int
dram_size(long int *base, long int maxsize)
{
	volatile long int	 *addr;
	long int		  cnt, val;

	for (cnt = maxsize/sizeof(long); cnt > 0; cnt >>= 1) {
		addr = base + cnt;	/* pointer arith! */

		*addr = ~cnt;
	}

	/* write 0 to base address */
	addr = base;
	*addr = 0xDEADBEEF;

	/* check at base address */
	if ((val = *addr) != 0xDEADBEEF) {
		return 0;
	}

	for (cnt = 1; ; cnt <<= 1) {
		addr = base + cnt;	/* pointer arith! */

		val = *addr;

		if (val != (~cnt)) {
			return (cnt * sizeof(long));
		}
	}
	/* NOTREACHED */

	return 0;
}

/* ------------------------------------------------------------------------- */

/* ppcboot interface function to SDRAM init - this is where all the
 * controlling logic happens */
long int
initdram(int board_type)
{
	int s0 = 0, s1 = 0;
	int checkbank[4] = { [0 ... 3] = 0 };
        ulong bank_no, realsize, total, check;
	sdram_info_t dimm1, dimm2;
	int nhr;

	/* first, use the SPD to get info about the SDRAM */

	/* check the NHR bit and skip mem init if it's already done */
	nhr = get_hid0() & (1 << 16);

	if (nhr) {
		printf("Skipping SDRAM setup due to NHR bit being set\n");
	} else {
		/* DIMM0 */
		s0 = check_dimm(DIMM0_I2C_ADDR, 0, &dimm1);

		/* DIMM1 */
		s1 = check_dimm(DIMM1_I2C_ADDR, 1, &dimm2);

		memory_map_bank(0, 0, 0);
		memory_map_bank(1, 0, 0);
		memory_map_bank(2, 0, 0);
		memory_map_bank(3, 0, 0);

		/* Now, program the GT with the correct values */
		if (dimm1.tpar > dimm2.tpar)
			dimm2.tpar = dimm1.tpar;
		else if(dimm2.tpar > dimm1.tpar)
			dimm1.tpar = dimm2.tpar;

		if (dimm1.banks && setup_sdram(&dimm1)) {
			printf("Setup for DIMM1 failed.\n");
		}

		if (dimm2.banks && setup_sdram(&dimm2)) {
			printf("Setup for DIMM2 failed.\n");
		}

		/* set the NHR bit */
		set_hid0(get_hid0() | (1 << 16));
	}
	/* next, size the SDRAM banks */

	realsize = total = 0;
	check = GB/4;
	if (dimm1.banks > 0) checkbank[0] = 1;
	if (dimm1.banks > 1) checkbank[1] = 1;
	if (dimm1.banks > 2)
		printf("Error, SPD claims DIMM1 has >2 banks\n");

	if (dimm2.banks > 0) checkbank[2] = 1;
	if (dimm2.banks > 1) checkbank[3] = 1;
	if (dimm2.banks > 2)
		printf("Error, SPD claims DIMM2 has >2 banks\n");

	for (bank_no = 0; bank_no < CFG_DRAM_BANKS; bank_no++) {
		/* skip over banks that are not populated */
		if (! checkbank[bank_no])
			continue;

		if ((total + check) > CFG_GT_REGS)
			check -= CFG_GT_REGS - (total+check);

		memory_map_bank(bank_no, total, check);
		realsize = dram_size((long int *)total, check);

		if (realsize < 10)
			realsize = 0;

		memory_map_bank(bank_no, total, realsize);

		total += realsize;
	}

	if (GTREGREAD(SDRAM_TIMING) & (1 << 13)) {
		puts("[ECC] ");
	}

        return(total);
}
