From 4d7be85e730bc7f46ec5433c425733c4b65a90ed Mon Sep 17 00:00:00 2001
From: Merry <git@mary.rs>
Date: Sun, 1 Jan 2023 11:14:44 +0000
Subject: [PATCH 1/2] host_memory: Allocate virtual_base with MAP_NORESERVE

Specify that we do not require swap to be reserved for this address range;
allow overcommitting.
---
 src/common/host_memory.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp
index 909f6cf3fd..4a67f77b22 100644
--- a/src/common/host_memory.cpp
+++ b/src/common/host_memory.cpp
@@ -393,8 +393,8 @@ public:
         }
 
         // Virtual memory initialization
-        virtual_base = static_cast<u8*>(
-            mmap(nullptr, virtual_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
+        virtual_base = static_cast<u8*>(mmap(nullptr, virtual_size, PROT_NONE,
+                                             MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0));
         if (virtual_base == MAP_FAILED) {
             LOG_CRITICAL(HW_Memory, "mmap failed: {}", strerror(errno));
             throw std::bad_alloc{};

From fd1831b65bc8a0817776ac41f82b6ff053247b1b Mon Sep 17 00:00:00 2001
From: Merry <git@mary.rs>
Date: Sun, 1 Jan 2023 11:38:49 +0000
Subject: [PATCH 2/2] host_memory: Use transparent huge pages where available

---
 src/common/host_memory.cpp | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/common/host_memory.cpp b/src/common/host_memory.cpp
index 4a67f77b22..611c7d1a31 100644
--- a/src/common/host_memory.cpp
+++ b/src/common/host_memory.cpp
@@ -393,12 +393,27 @@ public:
         }
 
         // Virtual memory initialization
+#if defined(__FreeBSD__)
+        virtual_base =
+            static_cast<u8*>(mmap(nullptr, virtual_size, PROT_NONE,
+                                  MAP_PRIVATE | MAP_ANONYMOUS | MAP_ALIGNED_SUPER, -1, 0));
+        if (virtual_base == MAP_FAILED) {
+            virtual_base = static_cast<u8*>(
+                mmap(nullptr, virtual_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
+            if (virtual_base == MAP_FAILED) {
+                LOG_CRITICAL(HW_Memory, "mmap failed: {}", strerror(errno));
+                throw std::bad_alloc{};
+            }
+        }
+#else
         virtual_base = static_cast<u8*>(mmap(nullptr, virtual_size, PROT_NONE,
                                              MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0));
         if (virtual_base == MAP_FAILED) {
             LOG_CRITICAL(HW_Memory, "mmap failed: {}", strerror(errno));
             throw std::bad_alloc{};
         }
+        madvise(virtual_base, virtual_size, MADV_HUGEPAGE);
+#endif
 
         good = true;
     }