Home | History | Annotate | Line # | Download | only in kern
      1 /*	$NetBSD: kern_physio.c,v 1.104 2026/01/04 01:36:43 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1982, 1986, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)kern_physio.c	8.1 (Berkeley) 6/10/93
     37  */
     38 
     39 /*-
     40  * Copyright (c) 1994 Christopher G. Demetriou
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  *
     70  *	@(#)kern_physio.c	8.1 (Berkeley) 6/10/93
     71  */
     72 
     73 #include <sys/cdefs.h>
     74 __KERNEL_RCSID(0, "$NetBSD: kern_physio.c,v 1.104 2026/01/04 01:36:43 riastradh Exp $");
     75 
     76 #include <sys/param.h>
     77 #include <sys/types.h>
     78 
     79 #include <sys/buf.h>
     80 #include <sys/conf.h>
     81 #include <sys/kmem.h>
     82 #include <sys/once.h>
     83 #include <sys/proc.h>
     84 #include <sys/sdt.h>
     85 #include <sys/systm.h>
     86 #include <sys/workqueue.h>
     87 
     88 #include <uvm/uvm_extern.h>
     89 
     90 ONCE_DECL(physio_initialized);
     91 struct workqueue *physio_workqueue;
     92 
     93 int physio_concurrency = 16;
     94 
     95 /* #define	PHYSIO_DEBUG */
     96 #if defined(PHYSIO_DEBUG)
     97 #define	DPRINTF(a)	printf a
     98 #else /* defined(PHYSIO_DEBUG) */
     99 #define	DPRINTF(a)	/* nothing */
    100 #endif /* defined(PHYSIO_DEBUG) */
    101 
    102 struct physio_stat {
    103 	int ps_running;
    104 	int ps_error;
    105 	int ps_failed;
    106 	off_t ps_endoffset;
    107 	size_t ps_resid;
    108 	buf_t *ps_orig_bp;
    109 	kmutex_t ps_lock;
    110 	kcondvar_t ps_cv;
    111 };
    112 
    113 static void
    114 physio_done(struct work *wk, void *dummy)
    115 {
    116 	struct buf *bp = (void *)wk;
    117 	size_t todo = bp->b_bufsize;
    118 	size_t done = bp->b_bcount - bp->b_resid;
    119 	struct physio_stat *ps = bp->b_private;
    120 	bool is_iobuf;
    121 
    122 	KASSERT(&bp->b_work == wk);
    123 	KASSERT(bp->b_bcount <= todo);
    124 	KASSERT(bp->b_resid <= bp->b_bcount);
    125 	KASSERT((bp->b_flags & B_PHYS) != 0);
    126 	KASSERT(dummy == NULL);
    127 
    128 	vunmapbuf(bp, todo);
    129 	uvm_vsunlock(bp->b_proc->p_vmspace, bp->b_data, todo);
    130 
    131 	mutex_enter(&ps->ps_lock);
    132 	is_iobuf = (bp != ps->ps_orig_bp);
    133 	if (__predict_false(done != todo)) {
    134 		off_t endoffset = dbtob(bp->b_blkno) + done;
    135 
    136 		/*
    137 		 * we got an error or hit EOM.
    138 		 *
    139 		 * we only care about the first one.
    140 		 * ie. the one at the lowest offset.
    141 		 */
    142 
    143 		KASSERT(ps->ps_endoffset != endoffset);
    144 		DPRINTF(("%s: error=%d at %" PRIu64 " - %" PRIu64
    145 		    ", blkno=%" PRIu64 ", bcount=%d, flags=0x%x\n",
    146 		    __func__, bp->b_error, dbtob(bp->b_blkno), endoffset,
    147 		    bp->b_blkno, bp->b_bcount, bp->b_flags));
    148 
    149 		if (ps->ps_endoffset == -1 || endoffset < ps->ps_endoffset) {
    150 			DPRINTF(("%s: ps=%p, error %d -> %d, endoff %" PRIu64
    151 			    " -> %" PRIu64 "\n",
    152 			    __func__, ps,
    153 			    ps->ps_error, bp->b_error,
    154 			    ps->ps_endoffset, endoffset));
    155 
    156 			ps->ps_endoffset = endoffset;
    157 			ps->ps_error = bp->b_error;
    158 		}
    159 		ps->ps_failed++;
    160 
    161 		ps->ps_resid += todo - done;
    162 	} else {
    163 		KASSERT(bp->b_error == 0);
    164 	}
    165 
    166 	ps->ps_running--;
    167 	cv_signal(&ps->ps_cv);
    168 	mutex_exit(&ps->ps_lock);
    169 
    170 	if (is_iobuf)
    171 		putiobuf(bp);
    172 }
    173 
    174 static void
    175 physio_biodone(struct buf *bp)
    176 {
    177 #if defined(DIAGNOSTIC)
    178 	struct physio_stat *ps = bp->b_private;
    179 	size_t todo = bp->b_bufsize;
    180 	size_t done = bp->b_bcount - bp->b_resid;
    181 
    182 	KASSERT(ps->ps_running > 0);
    183 	KASSERT(bp->b_bcount <= todo);
    184 	KASSERT(bp->b_resid <= bp->b_bcount);
    185 	if (done == todo)
    186 		KASSERTMSG(bp->b_error == 0, "error=%d", bp->b_error);
    187 #endif /* defined(DIAGNOSTIC) */
    188 
    189 	workqueue_enqueue(physio_workqueue, &bp->b_work, NULL);
    190 }
    191 
    192 static void
    193 physio_wait(struct physio_stat *ps, int n)
    194 {
    195 
    196 	KASSERT(mutex_owned(&ps->ps_lock));
    197 
    198 	while (ps->ps_running > n)
    199 		cv_wait(&ps->ps_cv, &ps->ps_lock);
    200 }
    201 
    202 static int
    203 physio_init(void)
    204 {
    205 	int error;
    206 
    207 	KASSERT(physio_workqueue == NULL);
    208 
    209 	error = workqueue_create(&physio_workqueue, "physiod",
    210 	    physio_done, NULL, PRI_BIO, IPL_BIO, WQ_MPSAFE);
    211 
    212 	return error;
    213 }
    214 
    215 /*
    216  * Do "physical I/O" on behalf of a user.  "Physical I/O" is I/O directly
    217  * from the raw device to user buffers, and bypasses the buffer cache.
    218  */
    219 int
    220 physio(void (*strategy)(struct buf *), struct buf *obp, dev_t dev, int flags,
    221     void (*min_phys)(struct buf *), struct uio *uio)
    222 {
    223 	struct iovec *iovp;
    224 	struct lwp *l = curlwp;
    225 	struct proc *p = l->l_proc;
    226 	int i, error;
    227 	struct buf *bp = NULL;
    228 	struct physio_stat *ps;
    229 	int concurrency = physio_concurrency - 1;
    230 	int isdisk;
    231 
    232 	error = RUN_ONCE(&physio_initialized, physio_init);
    233 	if (__predict_false(error != 0)) {
    234 		return error;
    235 	}
    236 
    237 	DPRINTF(("%s: called: off=%" PRIu64 ", resid=%zu\n",
    238 	    __func__, uio->uio_offset, uio->uio_resid));
    239 
    240 	flags &= B_READ | B_WRITE;
    241 
    242 	ps = kmem_zalloc(sizeof(*ps), KM_SLEEP);
    243 	/* ps->ps_running = 0; */
    244 	/* ps->ps_error = 0; */
    245 	/* ps->ps_failed = 0; */
    246 	ps->ps_orig_bp = obp;
    247 	ps->ps_endoffset = -1;
    248 	ps->ps_resid = 0;
    249 	mutex_init(&ps->ps_lock, MUTEX_DEFAULT, IPL_NONE);
    250 	cv_init(&ps->ps_cv, "physio");
    251 
    252 	/* Allow concurrent I/O only for disks */
    253 	isdisk = cdev_type(dev) == D_DISK;
    254 	if (!isdisk)
    255 		concurrency = 0;
    256 
    257 	/* Make sure we have a buffer, creating one if necessary. */
    258 	if (obp != NULL) {
    259 		mutex_enter(&bufcache_lock);
    260 		/* Mark it busy, so nobody else will use it. */
    261 		while (bbusy(obp, false, 0, NULL) == EPASSTHROUGH)
    262 			;
    263 		mutex_exit(&bufcache_lock);
    264 		concurrency = 0; /* see "XXXkludge" comment below */
    265 	}
    266 
    267 	for (i = 0; i < uio->uio_iovcnt; i++) {
    268 		bool sync = true;
    269 
    270 		iovp = &uio->uio_iov[i];
    271 		while (iovp->iov_len > 0) {
    272 			size_t todo;
    273 			vaddr_t endp;
    274 
    275 			mutex_enter(&ps->ps_lock);
    276 			if (ps->ps_failed != 0) {
    277 				goto done_locked;
    278 			}
    279 			physio_wait(ps, sync ? 0 : concurrency);
    280 			mutex_exit(&ps->ps_lock);
    281 			if (obp != NULL) {
    282 				/*
    283 				 * XXXkludge
    284 				 * some drivers use "obp" as an identifier.
    285 				 */
    286 				bp = obp;
    287 			} else {
    288 				bp = getiobuf(NULL, true);
    289 				bp->b_cflags |= BC_BUSY;
    290 			}
    291 			bp->b_dev = dev;
    292 			bp->b_proc = p;
    293 			bp->b_private = ps;
    294 
    295 			/*
    296 			 * Mrk the buffer busy for physical I/O.  Also set
    297 			 * B_PHYS because it's an I/O to user memory, and
    298 			 * B_RAW because B_RAW is to be "set by physio for
    299 			 * raw transfers".
    300 			 */
    301 			bp->b_oflags = 0;
    302 			bp->b_cflags |= BC_BUSY;
    303 			bp->b_flags = flags | B_PHYS | B_RAW;
    304 			bp->b_iodone = physio_biodone;
    305 
    306 			/* Set up the buffer for a maximum-sized transfer. */
    307 			bp->b_blkno = btodb(uio->uio_offset);
    308 			if (isdisk) {
    309 				/*
    310 				 * For disks, check that offsets are at least block
    311 				 * aligned, the block addresses are used to track
    312 				 * errors of finished requests.
    313 				 */
    314 				if (uio->uio_offset & (DEV_BSIZE - 1)) {
    315 					error = SET_ERROR(EINVAL);
    316 					goto done;
    317 				}
    318 				/*
    319 				 * Split request into MAXPHYS chunks
    320 				 */
    321 				bp->b_bcount = MIN(MAXPHYS, iovp->iov_len);
    322 			} else {
    323 				bp->b_bcount = MIN(INT_MAX, iovp->iov_len);
    324 			}
    325 			bp->b_data = iovp->iov_base;
    326 
    327 			/*
    328 			 * Call minphys to bound the transfer size,
    329 			 * and remember the amount of data to transfer,
    330 			 * for later comparison.
    331 			 */
    332 			(*min_phys)(bp);
    333 			todo = bp->b_bufsize = bp->b_bcount;
    334 #if defined(DIAGNOSTIC)
    335 			if (todo > MAXPHYS)
    336 				panic("todo(%zu) > MAXPHYS; minphys broken",
    337 				    todo);
    338 #endif /* defined(DIAGNOSTIC) */
    339 
    340 			sync = false;
    341 			endp = (vaddr_t)bp->b_data + todo;
    342 			if (trunc_page(endp) != endp) {
    343 				/*
    344 				 * Following requests can overlap.
    345 				 * note that uvm_vslock does round_page.
    346 				 */
    347 				sync = true;
    348 			}
    349 
    350 			/*
    351 			 * Lock the part of the user address space involved
    352 			 * in the transfer.
    353 			 */
    354 			error = uvm_vslock(p->p_vmspace, bp->b_data, todo,
    355 			    (flags & B_READ) ?  VM_PROT_WRITE : VM_PROT_READ);
    356 			if (error) {
    357 				goto done;
    358 			}
    359 
    360 			/*
    361 			 * Beware vmapbuf(); if successful it clobbers
    362 			 * b_data and saves it in b_saveaddr.
    363 			 * However, vunmapbuf() restores b_data.
    364 			 */
    365 			if ((error = vmapbuf(bp, todo)) != 0) {
    366 				uvm_vsunlock(p->p_vmspace, bp->b_data, todo);
    367 				goto done;
    368 			}
    369 
    370 			BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
    371 
    372 			mutex_enter(&ps->ps_lock);
    373 			ps->ps_running++;
    374 			mutex_exit(&ps->ps_lock);
    375 
    376 			/* Call strategy to start the transfer. */
    377 			(*strategy)(bp);
    378 			bp = NULL;
    379 
    380 			iovp->iov_len -= todo;
    381 			iovp->iov_base = (char *)iovp->iov_base + todo;
    382 			uio->uio_offset += todo;
    383 			uio->uio_resid -= todo;
    384 		}
    385 	}
    386 
    387 done:
    388 	mutex_enter(&ps->ps_lock);
    389 done_locked:
    390 	physio_wait(ps, 0);
    391 	mutex_exit(&ps->ps_lock);
    392 
    393 	KASSERT(ps->ps_failed || ps->ps_endoffset == -1);
    394 
    395 	/*
    396 	 * Compute residual, for disks adjust for the
    397 	 * lowest numbered block that returned an error.
    398 	 */
    399 	if (isdisk) {
    400 		if (ps->ps_failed != 0) {
    401 			off_t delta;
    402 
    403 			delta = uio->uio_offset - ps->ps_endoffset;
    404 			KASSERT(delta > 0);
    405 			uio->uio_resid += delta;
    406 			/* uio->uio_offset = ps->ps_endoffset; */
    407 		}
    408 	} else {
    409 		uio->uio_resid += ps->ps_resid;
    410 	}
    411 
    412 	if (bp != NULL && bp != obp) {
    413 		putiobuf(bp);
    414 	}
    415 	if (error == 0) {
    416 		error = ps->ps_error;
    417 	}
    418 	mutex_destroy(&ps->ps_lock);
    419 	cv_destroy(&ps->ps_cv);
    420 	kmem_free(ps, sizeof(*ps));
    421 
    422 	/*
    423 	 * Clean up the state of the buffer.  Remember if somebody wants
    424 	 * it, so we can wake them up below.  Also, if we had to steal it,
    425 	 * give it back.
    426 	 */
    427 	if (obp != NULL) {
    428 		KASSERT((obp->b_cflags & BC_BUSY) != 0);
    429 
    430 		/*
    431 		 * If another process is waiting for the raw I/O buffer,
    432 		 * wake up processes waiting to do physical I/O;
    433 		 */
    434 		mutex_enter(&bufcache_lock);
    435 		obp->b_cflags &= ~(BC_BUSY | BC_WANTED);
    436 		obp->b_flags &= ~(B_PHYS | B_RAW);
    437 		obp->b_iodone = NULL;
    438 		cv_broadcast(&obp->b_busy);
    439 		mutex_exit(&bufcache_lock);
    440 	}
    441 
    442 	DPRINTF(("%s: done: off=%" PRIu64 ", resid=%zu\n",
    443 	    __func__, uio->uio_offset, uio->uio_resid));
    444 
    445 	return error;
    446 }
    447 
    448 /*
    449  * A minphys() routine is called by physio() to adjust the size of each
    450  * I/O transfer before the latter is passed to the strategy routine.
    451  *
    452  * This minphys() is a default that must be called to enforce limits
    453  * that are applicable to all devices, because of limitations in the
    454  * kernel or the hardware platform.
    455  */
    456 void
    457 minphys(struct buf *bp)
    458 {
    459 
    460 	if (bp->b_bcount > MAXPHYS)
    461 		bp->b_bcount = MAXPHYS;
    462 }
    463