/*
 * Copyright (c) 2015-2019, Renesas Electronics Corporation
 * All rights reserved.
 */

#include <stdint.h>
#include <debug.h>
#include <mmio.h>
#include "boot_init_dram.h"
#include "V3M/ddr_init_v3m.h"

/* Mode pin register */
#define	RCAR_MODEMR			(0xE6160060U)
#define CHECK_MD19			(0x80000U)

#define DDR3L_1600			(0x00000U)
#define DDR3L_1333			(0x80000U)

void InitDram(void)
{
	uint32_t chk_data;
	uint32_t ret;
	const char *str;
	const char *ddr3l_1583 = "1583";
	const char *ddr3l_1316 = "1316";

	chk_data = mmio_read_32((uintptr_t)RCAR_MODEMR)
							& CHECK_MD19;

	switch (chk_data) {
	case DDR3L_1600:/* MD19=0 */
		str = ddr3l_1583;
		pll3_freq_change_bypmode_1583();
		ret = init_ddr_v3m1583();
		if(ret != 1U)
		{
			ERROR("Failed to DRAM initialize (%d).\n", ret);
			panic();
		}
		break;
	case DDR3L_1333:/* MD19=1 */
		str = ddr3l_1316;
		pll3_freq_change_bypmode_1316();
		ret = init_ddr_v3m1316();
		if(ret != 1U)
		{
			ERROR("Failed to DRAM initialize (%d).\n", ret);
			panic();
		}
		break;
	default:
		/* Error */
		ERROR("CR7: MODEMR ERROR value=%x\n", chk_data);
		panic();
		break;
	}

	NOTICE("DDR3L %sMbps(%s)\n", str, RCAR_V3M_DDR_VERSION);

#if RCAR_DDR_REG_CHECK == 1
	/* initialized reg check */
	ret = InitDram_regcheck();

	if (ret != 0U) {
		ERROR("Failed to DDRPHY REG check (%d).\n", ret);
		/*
		 * User need to implement what IPL should do
		 * if InitDram_regcheck() is failed.
		 */
	} else {
		NOTICE("DDRPHY REG check is OK (%d).\n", ret);
	}
#endif /* #if RCAR_DDR_REG_CHECK == 1 */
}


