git: 212af7b6133a - stable/14 - scsi_cd: Maintain a periph reference during media checks

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Fri, 09 Feb 2024 15:04:24 UTC
The branch stable/14 has been updated by markj:

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

commit 212af7b6133a60382e62237bb3e99cf63342d157
Author:     Mark Johnston <markj@FreeBSD.org>
AuthorDate: 2024-01-30 01:01:12 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2024-02-09 14:55:45 +0000

    scsi_cd: Maintain a periph reference during media checks
    
    Otherwise nothing prevents the asynchronous media check state machine
    from running after the periph has been destroyed, which can result in a
    double free.  Acquire the reference even when performing a synchronous
    check, since that doesn't hurt and keeps things simpler.
    
    PR:             276251
    Reviewed by:    imp
    Fixes:          dd78f43259ef ("scsi_cd: make the media check asynchronous")
    MFC after:      1 week
    Differential Revision:  https://reviews.freebsd.org/D43525
    
    (cherry picked from commit c961afe82596bdeb7e6a8626f02ddb181c8a24b6)
---
 sys/cam/scsi/scsi_cd.c | 21 ++++++++++-----------
 1 file changed, 10 insertions(+), 11 deletions(-)

diff --git a/sys/cam/scsi/scsi_cd.c b/sys/cam/scsi/scsi_cd.c
index d3299486ac2d..bfc91fad6390 100644
--- a/sys/cam/scsi/scsi_cd.c
+++ b/sys/cam/scsi/scsi_cd.c
@@ -2675,6 +2675,7 @@ cdmediaprobedone(struct cam_periph *periph)
 		softc->flags &= ~CD_FLAG_MEDIA_WAIT;
 		wakeup(&softc->toc);
 	}
+	cam_periph_release_locked(periph);
 }
 
 /*
@@ -2692,31 +2693,29 @@ cdcheckmedia(struct cam_periph *periph, bool do_wait)
 	softc = (struct cd_softc *)periph->softc;
 	error = 0;
 
-	if ((do_wait != 0)
-	 && ((softc->flags & CD_FLAG_MEDIA_WAIT) == 0)) {
+	/* Released by cdmediaprobedone(). */
+	error = cam_periph_acquire(periph);
+	if (error != 0)
+		return (error);
+
+	if (do_wait)
 		softc->flags |= CD_FLAG_MEDIA_WAIT;
-	}
 	if ((softc->flags & CD_FLAG_MEDIA_SCAN_ACT) == 0) {
 		softc->state = CD_STATE_MEDIA_PREVENT;
 		softc->flags |= CD_FLAG_MEDIA_SCAN_ACT;
 		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
 	}
-
-	if (do_wait == 0)
-		goto bailout;
+	if (!do_wait)
+		return (0);
 
 	error = msleep(&softc->toc, cam_periph_mtx(periph), PRIBIO,"cdmedia",0);
 
-	if (error != 0)
-		goto bailout;
-
 	/*
 	 * Check to see whether we have a valid size from the media.  We
 	 * may or may not have a valid TOC.
 	 */
-	if ((softc->flags & CD_FLAG_VALID_MEDIA) == 0)
+	if (error == 0 && (softc->flags & CD_FLAG_VALID_MEDIA) == 0)
 		error = EINVAL;
-bailout:
 
 	return (error);
 }