git: efe5907279e1 - main - amd64: fix physmap entry addition logic

From: Ahmad Khalifa <vexeduxr_at_FreeBSD.org>
Date: Sun, 06 Jul 2025 19:28:20 UTC
The branch main has been updated by vexeduxr:

URL: https://cgit.FreeBSD.org/src/commit/?id=efe5907279e1aa1781fc4d5260204888cd235cc2

commit efe5907279e1aa1781fc4d5260204888cd235cc2
Author:     Ahmad Khalifa <vexeduxr@FreeBSD.org>
AuthorDate: 2025-07-06 19:09:15 +0000
Commit:     Ahmad Khalifa <vexeduxr@FreeBSD.org>
CommitDate: 2025-07-06 19:26:07 +0000

    amd64: fix physmap entry addition logic
    
    Since physmap_idx points to the next slot, we should make sure both 'i'
    and 'insert_idx' are less than physmap_idx, but never equal to it.
    
    Also allow physmap_idx to reach PHYS_AVAIL_ENTRIES so the last slot can
    be populated.
    
    Reviewed by:    kib, markj
    Approved by:    imp (mentor)
    Differential Revision:  https://reviews.freebsd.org/D51173
---
 sys/amd64/amd64/machdep.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/sys/amd64/amd64/machdep.c b/sys/amd64/amd64/machdep.c
index 032a134bbd4b..9724a6acb130 100644
--- a/sys/amd64/amd64/machdep.c
+++ b/sys/amd64/amd64/machdep.c
@@ -645,7 +645,7 @@ add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
 	 * NB: physmap_idx points to the next free slot.
 	 */
 	insert_idx = physmap_idx;
-	for (i = 0; i <= physmap_idx; i += 2) {
+	for (i = 0; i < physmap_idx; i += 2) {
 		if (base < physmap[i + 1]) {
 			if (base + length <= physmap[i]) {
 				insert_idx = i;
@@ -659,7 +659,7 @@ add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
 	}
 
 	/* See if we can prepend to the next entry. */
-	if (insert_idx <= physmap_idx && base + length == physmap[insert_idx]) {
+	if (insert_idx < physmap_idx && base + length == physmap[insert_idx]) {
 		physmap[insert_idx] = base;
 		return (1);
 	}
@@ -670,8 +670,6 @@ add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
 		return (1);
 	}
 
-	physmap_idx += 2;
-	*physmap_idxp = physmap_idx;
 	if (physmap_idx == PHYS_AVAIL_ENTRIES) {
 		printf(
 		"Too many segments in the physical address map, giving up\n");
@@ -682,11 +680,14 @@ add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
 	 * Move the last 'N' entries down to make room for the new
 	 * entry if needed.
 	 */
-	for (i = (physmap_idx - 2); i > insert_idx; i -= 2) {
+	for (i = physmap_idx; i > insert_idx; i -= 2) {
 		physmap[i] = physmap[i - 2];
 		physmap[i + 1] = physmap[i - 1];
 	}
 
+	physmap_idx += 2;
+	*physmap_idxp = physmap_idx;
+
 	/* Insert the new entry. */
 	physmap[insert_idx] = base;
 	physmap[insert_idx + 1] = base + length;