From 448ec62f85a90e8a27368ddc05057a5a714944b8 Mon Sep 17 00:00:00 2001
From: notaz <notasas@gmail.com>
Date: Fri, 6 Oct 2017 01:23:03 +0300
Subject: [PATCH] retry with mmap when mremap fails

---
 linux/plat.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/linux/plat.c b/linux/plat.c
index 06c315e..2842691 100644
--- a/linux/plat.c
+++ b/linux/plat.c
@@ -216,8 +216,18 @@ void *plat_mremap(void *ptr, size_t oldsize, size_t newsize)
 	void *ret;
 
 	ret = mremap(ptr, oldsize, newsize, MREMAP_MAYMOVE);
-	if (ret == MAP_FAILED)
-		return NULL;
+	if (ret == MAP_FAILED) {
+		fprintf(stderr, "mremap %p %zd %zd: ",
+			ptr, oldsize, newsize);
+		perror(NULL);
+		// might be because huge pages can't be remapped,
+		// just make a new mapping
+		ret = plat_mmap(0, newsize, 0, 0);
+		if (ret == MAP_FAILED)
+			return NULL;
+		memcpy(ret, ptr, oldsize);
+		munmap(ptr, oldsize);
+	}
 	if (ret != ptr)
 		printf("warning: mremap moved: %p -> %p\n", ptr, ret);
 
-- 
2.39.5