MIPS: BCM47xx: Really fix 128MB RAM problem

The previous patch 4a86f2d27733f610e642649aca3e82e86fca9e22 (lmo) rsp.
84a6fcb368a080620d12fc4d79e07902dbee7335 (kernel.org) was wrong.

The BCM47xx architecture maps the ram into a 128MB address space. It
will be spaced there as often as goes into the 128MB. Detection tries to
find the position where the same memory is found. When reading beyond
128MB the processor will throw an exception. If 128MB RAM is installed,
it will not find a memory alias because it tries to read beyond the 128MB
border. Now it just assumes 128MB installed ram if it can not find an
alias.

Signed-off-by: Hauke Mehrtens <hauke@hauke-m.de>
To: linux-mips@linux-mips.org
Patchwork: https://patchwork.linux-mips.org/patch/1508/
Acked-by: Florian Fainelli <florian@openwrt.org>
Signed-off-by: Ralf Baechle <ralf@linux-mips.org>
diff --git a/arch/mips/bcm47xx/prom.c b/arch/mips/bcm47xx/prom.c
index 0fa646c..f6e9063 100644
--- a/arch/mips/bcm47xx/prom.c
+++ b/arch/mips/bcm47xx/prom.c
@@ -126,6 +126,7 @@
 static __init void prom_init_mem(void)
 {
 	unsigned long mem;
+	unsigned long max;
 
 	/* Figure out memory size by finding aliases.
 	 *
@@ -134,21 +135,26 @@
 	 * want to reuse the memory used by CFE (around 4MB). That means cfe_*
 	 * functions stop to work at some point during the boot, we should only
 	 * call them at the beginning of the boot.
+	 *
+	 * BCM47XX uses 128MB for addressing the ram, if the system contains
+	 * less that that amount of ram it remaps the ram more often into the
+	 * available space.
+	 * Accessing memory after 128MB will cause an exception.
+	 * max contains the biggest possible address supported by the platform.
+	 * If the method wants to try something above we assume 128MB ram.
 	 */
+	max = ((unsigned long)(prom_init) | ((128 << 20) - 1));
 	for (mem = (1 << 20); mem < (128 << 20); mem += (1 << 20)) {
+		if (((unsigned long)(prom_init) + mem) > max) {
+			mem = (128 << 20);
+			printk(KERN_DEBUG "assume 128MB RAM\n");
+			break;
+		}
 		if (*(unsigned long *)((unsigned long)(prom_init) + mem) ==
 		    *(unsigned long *)(prom_init))
 			break;
 	}
 
-	/* Ignoring the last page when ddr size is 128M. Cached
-	 * accesses to last page is causing the processor to prefetch
-	 * using address above 128M stepping out of the ddr address
-	 * space.
-	 */
-	if (mem == 0x8000000)
-		mem -= 0x1000;
-
 	add_memory_region(0, mem, BOOT_MEM_RAM);
 }