git: 5ae9f8e9ac5e - main - md: Restore guards in mddestroy()

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Thu, 03 Jul 2025 15:20:36 UTC
The branch main has been updated by markj:

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

commit 5ae9f8e9ac5e1307fed4f7f2549347576f01b3fa
Author:     Mark Johnston <markj@FreeBSD.org>
AuthorDate: 2025-07-03 13:10:49 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2025-07-03 15:10:41 +0000

    md: Restore guards in mddestroy()
    
    mddestroy() may be invoked on a partially constructed md device.
    Restore the guards that handled this prior to commit e91022168101.
    
    Reported by:    syzbot+a0ff73f664de8757cfaa@syzkaller.appspotmail.com
    Reported by:    syzbot+7b4a4824bf81548283ab@syzkaller.appspotmail.com
    Reviewed by:    kib
    Fixes:          e91022168101 ("md(4): move type-specific data under union")
    Differential Revision:  https://reviews.freebsd.org/D51145
---
 sys/dev/md/md.c | 25 ++++++++++++++++---------
 1 file changed, 16 insertions(+), 9 deletions(-)

diff --git a/sys/dev/md/md.c b/sys/dev/md/md.c
index b842d4f2fd8e..741a7c013f7d 100644
--- a/sys/dev/md/md.c
+++ b/sys/dev/md/md.c
@@ -1559,19 +1559,26 @@ mddestroy(struct md_s *sc, struct thread *td)
 	mtx_destroy(&sc->queue_mtx);
 	switch (sc->type) {
 	case MD_VNODE:
-		vn_lock(sc->s_vnode.vnode, LK_EXCLUSIVE | LK_RETRY);
-		sc->s_vnode.vnode->v_vflag &= ~VV_MD;
-		VOP_UNLOCK(sc->s_vnode.vnode);
-		(void)vn_close(sc->s_vnode.vnode, sc->flags & MD_READONLY ?
-		    FREAD : (FREAD|FWRITE), sc->cred, td);
-		kva_free(sc->s_vnode.kva, maxphys + PAGE_SIZE);
+		if (sc->s_vnode.vnode != NULL) {
+			vn_lock(sc->s_vnode.vnode, LK_EXCLUSIVE | LK_RETRY);
+			sc->s_vnode.vnode->v_vflag &= ~VV_MD;
+			VOP_UNLOCK(sc->s_vnode.vnode);
+			(void)vn_close(sc->s_vnode.vnode,
+			    sc->flags & MD_READONLY ?  FREAD : (FREAD|FWRITE),
+			    sc->cred, td);
+		}
+		if (sc->s_vnode.kva != 0)
+			kva_free(sc->s_vnode.kva, maxphys + PAGE_SIZE);
 		break;
 	case MD_SWAP:
-		vm_object_deallocate(sc->s_swap.object);
+		if (sc->s_swap.object != NULL)
+			vm_object_deallocate(sc->s_swap.object);
 		break;
 	case MD_MALLOC:
-		destroy_indir(sc, sc->s_malloc.indir);
-		uma_zdestroy(sc->s_malloc.uma);
+		if (sc->s_malloc.indir != NULL)
+			destroy_indir(sc, sc->s_malloc.indir);
+		if (sc->s_malloc.uma != NULL)
+			uma_zdestroy(sc->s_malloc.uma);
 		break;
 	case MD_PRELOAD:
 	case MD_NULL: