From a188c59223ef72c3c9098246e9c9d71fc3f2cf02 Mon Sep 17 00:00:00 2001
From: Roger Pau Monne <roger.pau@citrix.com>
Date: Wed, 12 Feb 2014 18:42:21 +0100
Subject: [PATCH 10/31] xen: use the hardware e820 map on Dom0

We need to do some tweaking of the hardware e820 map, since the memory
layout provided by Xen and the e820 map doesn't match.

This consists in clamping the e820 map so that regions above max_pfn
are marked as unusuable.

Approved by: xxx
Sponsored by: Citrix Systems R&D

x86/xen/pv.c:
 - Clamp the hardware memory map provided by Xen to not use pfns
   greater than max_pfn.
---
 sys/x86/xen/pv.c |   35 +++++++++++++++++++++++++++++++++--
 1 files changed, 33 insertions(+), 2 deletions(-)

diff --git a/sys/x86/xen/pv.c b/sys/x86/xen/pv.c
index c2a4576..a802110 100644
--- a/sys/x86/xen/pv.c
+++ b/sys/x86/xen/pv.c
@@ -330,16 +330,47 @@ static void
 xen_pv_parse_memmap(caddr_t kmdp, vm_paddr_t *physmap, int *physmap_idx)
 {
 	struct xen_memory_map memmap;
+	unsigned long max_pfn = HYPERVISOR_start_info->nr_pages;
+	u_int64_t mem_end = ptoa(max_pfn);
 	u_int32_t size;
-	int rc;
+	int rc, mem_op, i;
 
 	/* Fetch the E820 map from Xen */
 	memmap.nr_entries = MAX_E820_ENTRIES;
 	set_xen_guest_handle(memmap.buffer, xen_smap);
-	rc = HYPERVISOR_memory_op(XENMEM_memory_map, &memmap);
+	mem_op = xen_initial_domain() ?
+	                XENMEM_machine_memory_map :
+	                XENMEM_memory_map;
+	rc = HYPERVISOR_memory_op(mem_op, &memmap);
 	if (rc)
 		panic("unable to fetch Xen E820 memory map");
 	size = memmap.nr_entries * sizeof(xen_smap[0]);
 
+	/*
+	 * This should be improved, Xen provides us with a single
+	 * chunk of physical memory that goes from 0 to max_pfn,
+	 * and what we do here is clamp the HW memory map to make
+	 * sure regions above max_pfn are marked as reserved.
+	 *
+	 * TRTTD would be to move the memory not used because of
+	 * the holes in the HW memory map to the now clamped regions
+	 * using XENMEM_{decrease/increase}_reservation.
+	 */
+	for (i = 0; i < memmap.nr_entries; i++) {
+		u_int64_t end = xen_smap[i].base + xen_smap[i].length;
+		if (xen_smap[i].type == SMAP_TYPE_MEMORY) {
+			if (xen_smap[i].base > mem_end) {
+				/* Mark as reserved */
+				xen_smap[i].type = SMAP_TYPE_RESERVED;
+				continue;
+			}
+			if (end > mem_end) {
+				/* Truncate region */
+				xen_smap[i].length -= end - mem_end;
+			}
+		}
+	}
+
+
 	bios_add_smap_entries(xen_smap, size, physmap, physmap_idx);
 }
-- 
1.7.7.5 (Apple Git-26)

