git: a2adf568cdfe - main - loader.efi: Free the unused tail of the memdisk buffer

From: Olivier Cochard <olivier_at_FreeBSD.org>
Date: Thu, 12 Nov 2026 09:44:27 UTC
The branch main has been updated by olivier:

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

commit a2adf568cdfe83d8aca49f9eb9ba7891e88ff3cd
Author:     Olivier Cochard <olivier@FreeBSD.org>
AuthorDate: 2026-11-08 22:14:52 +0000
Commit:     Olivier Cochard <olivier@FreeBSD.org>
CommitDate: 2026-11-12 09:38:56 +0000

    loader.efi: Free the unused tail of the memdisk buffer
    
    The buffer is sized from a guess, 4x the compressed size for most formats, so
    free the pages past the image once it is complete.
    
    Reviewed by:    imp
    Sponsored by:   Netflix
    Differential Revision:  https://ron-dev.freebsd.org/FreeBSD/src/pulls/100
---
 stand/efi/loader/decompress.c | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)

diff --git a/stand/efi/loader/decompress.c b/stand/efi/loader/decompress.c
index 11199e1ed3bc..c90634037260 100644
--- a/stand/efi/loader/decompress.c
+++ b/stand/efi/loader/decompress.c
@@ -129,6 +129,28 @@ free_buffer(decomp_state *dctx)
 	dctx->buf = 0;
 }
 
+/*
+ * The buffer size is a guess, so once the image is complete, give the pages
+ * past its end back to the firmware.
+ */
+static void
+trim_buffer(decomp_state *dctx)
+{
+	size_t used = roundup2((uintptr_t)dctx->buf_cur - (uintptr_t)dctx->buf,
+	    EFI_PAGE_SIZE);
+	size_t pages = used / EFI_PAGE_SIZE;
+
+	if (dctx->buf == 0 || pages == 0 || pages >= dctx->pages)
+		return;
+	if (EFI_ERROR(BS->FreePages(dctx->buf + used, dctx->pages - pages)))
+		return;
+	printf("Freed %llu unused bytes of the decompression buffer\n",
+	    ULL(dctx->alloc_size - used));
+	dctx->pages = pages;
+	dctx->alloc_size = used;
+	dctx->buf_end = (uint8_t *)(uintptr_t)dctx->buf + used;
+}
+
 /*
  * zlib supprot
  */
@@ -504,7 +526,9 @@ decomp_step(decomp_state *dctx, uint8_t *buf, size_t len, size_t offset)
 void
 decomp_fini(decomp_state *dctx, bool flush)
 {
-	return (dctx->fini(dctx, flush));
+	dctx->fini(dctx, flush);
+	if (!flush)
+		trim_buffer(dctx);
 }
 
 EFI_PHYSICAL_ADDRESS