From ef91cb9ed071a03594933eafff759649f92b874c Mon Sep 17 00:00:00 2001
From: Zheng Xu <zheng.xu@linaro.org>
Date: Fri, 2 Sep 2016 15:03:30 +0800
Subject: [PATCH] Bug 1143022 - Manually mmap on arm64 to ensure high 17 bits
 are clear. r=ehoogeveen

There might be 48-bit VA on arm64 depending on kernel configuration.
Manually mmap heap memory to align with the assumption made by JS engine.

Change-Id: Ic5d2b2fe4b758b3c87cc0688348af7e71a991146
---
 js/src/gc/Memory.cpp | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)

diff --git a/js/src/gc/Memory.cpp b/js/src/gc/Memory.cpp
index 153ccb4..42aee6c 100644
--- a/js/src/gc/Memory.cpp
+++ b/js/src/gc/Memory.cpp
@@ -339,6 +339,41 @@ MapMemory(size_t length, int prot, int flags, int fd, off_t offset)
         return MAP_FAILED;
     }
     return region;
+#elif defined(__aarch64__)
+   /*
+    * There might be similar virtual address issue on arm64 which depends on
+    * hardware and kernel configurations. But the work around is slightly
+    * different due to the different mmap behavior.
+    *
+    * TODO: Merge with the above code block if this implementation works for
+    * ia64 and sparc64.
+    */
+    const uintptr_t start = (uintptr_t)0x0000070000000000;
+    const uintptr_t end   = (uintptr_t)0x0000800000000000;
+    const uintptr_t step  = ChunkSize;
+   /*
+    * Optimization options if there are too many retries in practice:
+    * 1. Examine /proc/self/maps to find an available address. This file is
+    *    not always available, however. In addition, even if we examine
+    *    /proc/self/maps, we may still need to retry several times due to
+    *    racing with other threads.
+    * 2. Use a global/static variable with lock to track the addresses we have
+    *    allocated or tried.
+    */
+    uintptr_t hint;
+    void* region = MAP_FAILED;
+    for (hint = start; region == MAP_FAILED && hint + length <= end; hint += step) {
+        region = mmap((void*)hint, length, prot, flags, fd, offset);
+        if (region != MAP_FAILED) {
+            if ((uintptr_t(region) + (length - 1)) & 0xffff800000000000) {
+                if (munmap(region, length)) {
+                    MOZ_ASSERT(errno == ENOMEM);
+                }
+                region = MAP_FAILED;
+            }
+        }
+    }
+    return region == MAP_FAILED ? nullptr : region;
 #else
     return mmap(NULL, length, prot, flags, fd, offset);
 #endif
-- 
1.9.1

