git: c37b83055406 - main - hwpmc: refuse MOD_UNLOAD while PMC owners exist

From: Mitchell Horne <mhorne_at_FreeBSD.org>
Date: Thu, 12 Nov 2026 16:21:24 UTC
The branch main has been updated by mhorne:

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

commit c37b830554064fcc46ae383f3dc5725ea63a80c4
Author:     Andre Silva <andasilv@amd.com>
AuthorDate: 2026-11-12 16:19:02 +0000
Commit:     Mitchell Horne <mhorne@FreeBSD.org>
CommitDate: 2026-11-12 16:21:14 +0000

    hwpmc: refuse MOD_UNLOAD while PMC owners exist
    
    Unloading hwpmc while processes own PMCs frees state they still use.
    Return EBUSY instead.  Use a try-lock on pmc_sx, since MOD_UNLOAD runs
    with kld_sx held. MOD_SHUTDOWN still always cleans up.
    
    Reviewed by:    mhorne
    MFC after:      1 week
    Sponsored by:   Advanced Micro Devices, Inc.
    Differential Revision:  https://reviews.freebsd.org/D60561
---
 sys/dev/hwpmc/hwpmc_mod.c | 37 ++++++++++++++++++++++++++++++++++++-
 1 file changed, 36 insertions(+), 1 deletion(-)

diff --git a/sys/dev/hwpmc/hwpmc_mod.c b/sys/dev/hwpmc/hwpmc_mod.c
index 82079e7660ea..662c4f52fc5d 100644
--- a/sys/dev/hwpmc/hwpmc_mod.c
+++ b/sys/dev/hwpmc/hwpmc_mod.c
@@ -5941,12 +5941,14 @@ pmc_cleanup(void)
 
 	PMCDBG0(MOD,INI,0, "cleanup");
 
+	/* The caller holds pmc_sx from the owner check through unhooking. */
+	sx_assert(&pmc_sx, SX_XLOCKED);
+
 	/* switch off sampling */
 	CPU_FOREACH(cpu)
 		DPCPU_ID_SET(cpu, pmc_sampled, 0);
 	pmc_intr = NULL;
 
-	sx_xlock(&pmc_sx);
 	if (pmc_hook == NULL) {	/* being unloaded already */
 		sx_xunlock(&pmc_sx);
 		return;
@@ -6101,6 +6103,33 @@ pmc_cleanup(void)
 	sx_xunlock(&pmc_sx);	/* we are done */
 }
 
+/*
+ * Do not unhook sampling while owners can still hold queued samples.
+ * MOD_UNLOAD runs under kld_sx.  A blocking acquisition of pmc_sx would
+ * invert the sampling path's pmc_sx -> kld_sx order, so refuse on lock
+ * contention.  Keep the successful try-lock through cleanup to exclude
+ * new owners between checking the hash and disabling the hooks.
+ */
+static int
+pmc_unload(void)
+{
+	struct pmc_ownerhash *ph;
+
+	if (!sx_try_xlock(&pmc_sx))
+		return (EXTERROR(EBUSY, "PMC state lock is busy"));
+	if (pmc_ownerhash != NULL) {
+		for (ph = pmc_ownerhash;
+		     ph <= &pmc_ownerhash[pmc_ownerhashmask]; ph++) {
+			if (!LIST_EMPTY(ph)) {
+				sx_xunlock(&pmc_sx);
+				return (EXTERROR(EBUSY, "PMC owners still exist"));
+			}
+		}
+	}
+	pmc_cleanup();
+	return (0);
+}
+
 /*
  * The function called at load/unload.
  */
@@ -6121,7 +6150,13 @@ load(struct module *module __unused, int cmd, void *arg __unused)
 		    pmc_cpu_max());
 		break;
 	case MOD_UNLOAD:
+		error = pmc_unload();
+		if (error == 0)
+			PMCDBG0(MOD,INI,1, "unloaded");
+		break;
 	case MOD_SHUTDOWN:
+		/* Shutdown cannot be vetoed by PMC owners. */
+		sx_xlock(&pmc_sx);
 		pmc_cleanup();
 		PMCDBG0(MOD,INI,1, "unloaded");
 		break;