git: a4a353f0d089 - main - vm_page_unwire_unmanaged(): fix a double free of the page

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Mon, 23 Nov 2026 00:36:11 UTC
The branch main has been updated by kib:

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

commit a4a353f0d089d35aceeaf26df7ab436de20fc8cb
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2026-11-22 00:31:44 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2026-11-23 00:35:14 +0000

    vm_page_unwire_unmanaged(): fix a double free of the page
    
    The function decided to free the page when vm_page_unwire_noq() reported
    that the last wiring was released and a separate load of ref_count then
    returned zero. For a page that belongs to an object, the object can drop
    its VPRC_OBJREF reference between the decrement and the load. The load
    then sees zero, and both threads free the page, which ends up on the
    free lists twice and is later handed out to two owners.
    
    Decide from the value returned by our own atomic decrement instead.
    
    Reported by:    alc
    Reviewed by:    alc
    Fixes:  fee2a2fa3983 ("Change synchonization rules for vm_page reference counting.")
    Sponsored by:   The FreeBSD Foundation
    MFC after:      1 week
    Differential revision:  https://reviews.freebsd.org/D61860
---
 sys/vm/vm_page.c | 26 +++++++++++++++++++++-----
 1 file changed, 21 insertions(+), 5 deletions(-)

diff --git a/sys/vm/vm_page.c b/sys/vm/vm_page.c
index 6ead05a274b2..b69443088002 100644
--- a/sys/vm/vm_page.c
+++ b/sys/vm/vm_page.c
@@ -4385,13 +4385,29 @@ vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
 bool
 vm_page_unwire_unmanaged(vm_page_t m)
 {
+	u_int old;
+
 	MPASS((m->oflags & VPO_UNMANAGED) != 0);
 
-	if (vm_page_unwire_noq(m) && m->ref_count == 0) {
-		vm_page_free(m);
-		return (true);
-	}
-	return (false);
+	/*
+	 * Decide from the value returned by our own decrement.  If the page
+	 * belongs to an object, the object may drop its VPRC_OBJREF
+	 * reference concurrently, see vm_object_terminate_single_page(),
+	 * and a later load of ref_count could make both threads free the
+	 * page.
+	 */
+	old = vm_page_drop(m, 1);
+	KASSERT(VPRC_WIRE_COUNT(old) != 0,
+	    ("%s: counter underflow for page %p", __func__, m));
+	KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
+	    ("%s: missing ref on fictitious page %p", __func__, m));
+	if (VPRC_WIRE_COUNT(old) > 1)
+		return (false);
+	vm_wire_sub(1);
+	if (old != 1)
+		return (false);
+	vm_page_free(m);
+	return (true);
 }
 
 /*