arm: mvebu: dram.c: Rework dram_init() and dram_init_banksize()

Rework these functions so that dram_init_banksize() does not call
dram_init() again. It only needs to set the banksize values in the
bdinfo struct.

Make sure to also clip the size of the last bank if it exceeds the
maximum allowed value of 3 GiB (0xc000.0000). Otherwise other
address windows (e.g. PCIe) will overlap with this memory window.

Signed-off-by: Stefan Roese <sr@denx.de>
Cc: Luka Perkov <luka.perkov@sartura.hr>
diff --git a/arch/arm/mach-mvebu/dram.c b/arch/arm/mach-mvebu/dram.c
index 600dc09..a75ada3 100644
--- a/arch/arm/mach-mvebu/dram.c
+++ b/arch/arm/mach-mvebu/dram.c
@@ -35,6 +35,8 @@
 #define REG_CPUCS_WIN_WIN0_CS(x)	(((x) & 0x3) << 2)
 #define REG_CPUCS_WIN_SIZE(x)		(((x) & 0xff) << 24)
 
+#define SDRAM_SIZE_MAX			0xc0000000
+
 /*
  * mvebu_sdram_bar - reads SDRAM Base Address Register
  */
@@ -102,29 +104,26 @@
 
 int dram_init(void)
 {
+	u64 size = 0;
 	int i;
 
-	gd->ram_size = 0;
 	for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
-		gd->bd->bi_dram[i].start = mvebu_sdram_bar(i);
-		gd->bd->bi_dram[i].size = mvebu_sdram_bs(i);
 		/*
 		 * It is assumed that all memory banks are consecutive
 		 * and without gaps.
 		 * If the gap is found, ram_size will be reported for
 		 * consecutive memory only
 		 */
-		if (gd->bd->bi_dram[i].start != gd->ram_size)
+		if (mvebu_sdram_bar(i) != size)
 			break;
 
 		/*
 		 * Don't report more than 3GiB of SDRAM, otherwise there is no
 		 * address space left for the internal registers etc.
 		 */
-		if ((gd->ram_size + gd->bd->bi_dram[i].size != 0) &&
-		    (gd->ram_size + gd->bd->bi_dram[i].size <= (3 << 30)))
-			gd->ram_size += gd->bd->bi_dram[i].size;
-
+		size += mvebu_sdram_bs(i);
+		if (size > SDRAM_SIZE_MAX)
+			size = SDRAM_SIZE_MAX;
 	}
 
 	for (; i < CONFIG_NR_DRAM_BANKS; i++) {
@@ -136,6 +135,8 @@
 		gd->bd->bi_dram[i].size = 0;
 	}
 
+	gd->ram_size = size;
+
 	return 0;
 }
 
@@ -145,7 +146,18 @@
  */
 void dram_init_banksize(void)
 {
-	dram_init();
+	u64 size = 0;
+	int i;
+
+	for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
+		gd->bd->bi_dram[i].start = mvebu_sdram_bar(i);
+		gd->bd->bi_dram[i].size = mvebu_sdram_bs(i);
+
+		/* Clip the banksize to 1GiB if it exceeds the max size */
+		size += gd->bd->bi_dram[i].size;
+		if (size > SDRAM_SIZE_MAX)
+			mvebu_sdram_bs_set(i, 0x40000000);
+	}
 }
 
 void board_add_ram_info(int use_default)