Home | History | Annotate | Line # | Download | only in kern
subr_disk.c revision 1.55
      1 /*	$NetBSD: subr_disk.c,v 1.55 2003/12/05 10:16:16 yamt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996, 1997, 1999, 2000 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1988, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  * (c) UNIX System Laboratories, Inc.
     44  * All or some portions of this file are derived from material licensed
     45  * to the University of California by American Telephone and Telegraph
     46  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     47  * the permission of UNIX System Laboratories, Inc.
     48  *
     49  * Redistribution and use in source and binary forms, with or without
     50  * modification, are permitted provided that the following conditions
     51  * are met:
     52  * 1. Redistributions of source code must retain the above copyright
     53  *    notice, this list of conditions and the following disclaimer.
     54  * 2. Redistributions in binary form must reproduce the above copyright
     55  *    notice, this list of conditions and the following disclaimer in the
     56  *    documentation and/or other materials provided with the distribution.
     57  * 3. Neither the name of the University nor the names of its contributors
     58  *    may be used to endorse or promote products derived from this software
     59  *    without specific prior written permission.
     60  *
     61  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     62  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     63  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     64  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     65  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     66  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     67  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     68  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     69  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     70  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     71  * SUCH DAMAGE.
     72  *
     73  *	@(#)ufs_disksubr.c	8.5 (Berkeley) 1/21/94
     74  */
     75 
     76 #include <sys/cdefs.h>
     77 __KERNEL_RCSID(0, "$NetBSD: subr_disk.c,v 1.55 2003/12/05 10:16:16 yamt Exp $");
     78 
     79 #include "opt_compat_netbsd.h"
     80 
     81 #include <sys/param.h>
     82 #include <sys/kernel.h>
     83 #include <sys/malloc.h>
     84 #include <sys/buf.h>
     85 #include <sys/syslog.h>
     86 #include <sys/disklabel.h>
     87 #include <sys/disk.h>
     88 #include <sys/sysctl.h>
     89 #include <lib/libkern/libkern.h>
     90 
     91 /*
     92  * A global list of all disks attached to the system.  May grow or
     93  * shrink over time.
     94  */
     95 struct	disklist_head disklist;	/* TAILQ_HEAD */
     96 int	disk_count;		/* number of drives in global disklist */
     97 struct simplelock disklist_slock = SIMPLELOCK_INITIALIZER;
     98 
     99 /*
    100  * Compute checksum for disk label.
    101  */
    102 u_int
    103 dkcksum(struct disklabel *lp)
    104 {
    105 	u_short *start, *end;
    106 	u_short sum = 0;
    107 
    108 	start = (u_short *)lp;
    109 	end = (u_short *)&lp->d_partitions[lp->d_npartitions];
    110 	while (start < end)
    111 		sum ^= *start++;
    112 	return (sum);
    113 }
    114 
    115 /*
    116  * Disk error is the preface to plaintive error messages
    117  * about failing disk transfers.  It prints messages of the form
    118 
    119 hp0g: hard error reading fsbn 12345 of 12344-12347 (hp0 bn %d cn %d tn %d sn %d)
    120 
    121  * if the offset of the error in the transfer and a disk label
    122  * are both available.  blkdone should be -1 if the position of the error
    123  * is unknown; the disklabel pointer may be null from drivers that have not
    124  * been converted to use them.  The message is printed with printf
    125  * if pri is LOG_PRINTF, otherwise it uses log at the specified priority.
    126  * The message should be completed (with at least a newline) with printf
    127  * or addlog, respectively.  There is no trailing space.
    128  */
    129 #ifndef PRIdaddr
    130 #define PRIdaddr PRId64
    131 #endif
    132 void
    133 diskerr(const struct buf *bp, const char *dname, const char *what, int pri,
    134     int blkdone, const struct disklabel *lp)
    135 {
    136 	int unit = DISKUNIT(bp->b_dev), part = DISKPART(bp->b_dev);
    137 	void (*pr)(const char *, ...);
    138 	char partname = 'a' + part;
    139 	daddr_t sn;
    140 
    141 	if (/*CONSTCOND*/0)
    142 		/* Compiler will error this is the format is wrong... */
    143 		printf("%" PRIdaddr, bp->b_blkno);
    144 
    145 	if (pri != LOG_PRINTF) {
    146 		static const char fmt[] = "";
    147 		log(pri, fmt);
    148 		pr = addlog;
    149 	} else
    150 		pr = printf;
    151 	(*pr)("%s%d%c: %s %sing fsbn ", dname, unit, partname, what,
    152 	    bp->b_flags & B_READ ? "read" : "writ");
    153 	sn = bp->b_blkno;
    154 	if (bp->b_bcount <= DEV_BSIZE)
    155 		(*pr)("%" PRIdaddr, sn);
    156 	else {
    157 		if (blkdone >= 0) {
    158 			sn += blkdone;
    159 			(*pr)("%" PRIdaddr " of ", sn);
    160 		}
    161 		(*pr)("%" PRIdaddr "-%" PRIdaddr "", bp->b_blkno,
    162 		    bp->b_blkno + (bp->b_bcount - 1) / DEV_BSIZE);
    163 	}
    164 	if (lp && (blkdone >= 0 || bp->b_bcount <= lp->d_secsize)) {
    165 		sn += lp->d_partitions[part].p_offset;
    166 		(*pr)(" (%s%d bn %" PRIdaddr "; cn %" PRIdaddr "",
    167 		    dname, unit, sn, sn / lp->d_secpercyl);
    168 		sn %= lp->d_secpercyl;
    169 		(*pr)(" tn %" PRIdaddr " sn %" PRIdaddr ")",
    170 		    sn / lp->d_nsectors, sn % lp->d_nsectors);
    171 	}
    172 }
    173 
    174 /*
    175  * Initialize the disklist.  Called by main() before autoconfiguration.
    176  */
    177 void
    178 disk_init(void)
    179 {
    180 
    181 	TAILQ_INIT(&disklist);
    182 	disk_count = 0;
    183 }
    184 
    185 /*
    186  * Searches the disklist for the disk corresponding to the
    187  * name provided.
    188  */
    189 struct disk *
    190 disk_find(char *name)
    191 {
    192 	struct disk *diskp;
    193 
    194 	if ((name == NULL) || (disk_count <= 0))
    195 		return (NULL);
    196 
    197 	simple_lock(&disklist_slock);
    198 	for (diskp = TAILQ_FIRST(&disklist); diskp != NULL;
    199 	    diskp = TAILQ_NEXT(diskp, dk_link))
    200 		if (strcmp(diskp->dk_name, name) == 0) {
    201 			simple_unlock(&disklist_slock);
    202 			return (diskp);
    203 		}
    204 	simple_unlock(&disklist_slock);
    205 
    206 	return (NULL);
    207 }
    208 
    209 /*
    210  * Attach a disk.
    211  */
    212 void
    213 disk_attach(struct disk *diskp)
    214 {
    215 	int s;
    216 
    217 	/*
    218 	 * Allocate and initialize the disklabel structures.  Note that
    219 	 * it's not safe to sleep here, since we're probably going to be
    220 	 * called during autoconfiguration.
    221 	 */
    222 	diskp->dk_label = malloc(sizeof(struct disklabel), M_DEVBUF, M_NOWAIT);
    223 	diskp->dk_cpulabel = malloc(sizeof(struct cpu_disklabel), M_DEVBUF,
    224 	    M_NOWAIT);
    225 	if ((diskp->dk_label == NULL) || (diskp->dk_cpulabel == NULL))
    226 		panic("disk_attach: can't allocate storage for disklabel");
    227 
    228 	memset(diskp->dk_label, 0, sizeof(struct disklabel));
    229 	memset(diskp->dk_cpulabel, 0, sizeof(struct cpu_disklabel));
    230 
    231 	/*
    232 	 * Set the attached timestamp.
    233 	 */
    234 	s = splclock();
    235 	diskp->dk_attachtime = mono_time;
    236 	splx(s);
    237 
    238 	/*
    239 	 * Link into the disklist.
    240 	 */
    241 	simple_lock(&disklist_slock);
    242 	TAILQ_INSERT_TAIL(&disklist, diskp, dk_link);
    243 	simple_unlock(&disklist_slock);
    244 	++disk_count;
    245 }
    246 
    247 /*
    248  * Detach a disk.
    249  */
    250 void
    251 disk_detach(struct disk *diskp)
    252 {
    253 
    254 	/*
    255 	 * Remove from the disklist.
    256 	 */
    257 	if (--disk_count < 0)
    258 		panic("disk_detach: disk_count < 0");
    259 	simple_lock(&disklist_slock);
    260 	TAILQ_REMOVE(&disklist, diskp, dk_link);
    261 	simple_unlock(&disklist_slock);
    262 
    263 	/*
    264 	 * Free the space used by the disklabel structures.
    265 	 */
    266 	free(diskp->dk_label, M_DEVBUF);
    267 	free(diskp->dk_cpulabel, M_DEVBUF);
    268 }
    269 
    270 /*
    271  * Increment a disk's busy counter.  If the counter is going from
    272  * 0 to 1, set the timestamp.
    273  */
    274 void
    275 disk_busy(struct disk *diskp)
    276 {
    277 	int s;
    278 
    279 	/*
    280 	 * XXX We'd like to use something as accurate as microtime(),
    281 	 * but that doesn't depend on the system TOD clock.
    282 	 */
    283 	if (diskp->dk_busy++ == 0) {
    284 		s = splclock();
    285 		diskp->dk_timestamp = mono_time;
    286 		splx(s);
    287 	}
    288 }
    289 
    290 /*
    291  * Decrement a disk's busy counter, increment the byte count, total busy
    292  * time, and reset the timestamp.
    293  */
    294 void
    295 disk_unbusy(struct disk *diskp, long bcount, int read)
    296 {
    297 	int s;
    298 	struct timeval dv_time, diff_time;
    299 
    300 	if (diskp->dk_busy-- == 0) {
    301 		printf("%s: dk_busy < 0\n", diskp->dk_name);
    302 		panic("disk_unbusy");
    303 	}
    304 
    305 	s = splclock();
    306 	dv_time = mono_time;
    307 	splx(s);
    308 
    309 	timersub(&dv_time, &diskp->dk_timestamp, &diff_time);
    310 	timeradd(&diskp->dk_time, &diff_time, &diskp->dk_time);
    311 
    312 	diskp->dk_timestamp = dv_time;
    313 	if (bcount > 0) {
    314 		if (read) {
    315 			diskp->dk_rbytes += bcount;
    316 			diskp->dk_rxfer++;
    317 		} else {
    318 			diskp->dk_wbytes += bcount;
    319 			diskp->dk_wxfer++;
    320 		}
    321 	}
    322 }
    323 
    324 /*
    325  * Reset the metrics counters on the given disk.  Note that we cannot
    326  * reset the busy counter, as it may case a panic in disk_unbusy().
    327  * We also must avoid playing with the timestamp information, as it
    328  * may skew any pending transfer results.
    329  */
    330 void
    331 disk_resetstat(struct disk *diskp)
    332 {
    333 	int s = splbio(), t;
    334 
    335 	diskp->dk_rxfer = 0;
    336 	diskp->dk_rbytes = 0;
    337 	diskp->dk_wxfer = 0;
    338 	diskp->dk_wbytes = 0;
    339 
    340 	t = splclock();
    341 	diskp->dk_attachtime = mono_time;
    342 	splx(t);
    343 
    344 	timerclear(&diskp->dk_time);
    345 
    346 	splx(s);
    347 }
    348 
    349 int
    350 sysctl_hw_disknames(SYSCTLFN_ARGS)
    351 {
    352 	char buf[DK_DISKNAMELEN + 1];
    353 	char *where = oldp;
    354 	struct disk *diskp;
    355 	size_t needed, left, slen;
    356 	int error, first;
    357 
    358 	if (newp != NULL)
    359 		return (EPERM);
    360 	if (namelen != 0)
    361 		return (EINVAL);
    362 
    363 	first = 1;
    364 	error = 0;
    365 	needed = 0;
    366 	left = *oldlenp;
    367 
    368 	simple_lock(&disklist_slock);
    369 	for (diskp = TAILQ_FIRST(&disklist); diskp != NULL;
    370 	    diskp = TAILQ_NEXT(diskp, dk_link)) {
    371 		if (where == NULL)
    372 			needed += strlen(diskp->dk_name) + 1;
    373 		else {
    374 			memset(buf, 0, sizeof(buf));
    375 			if (first) {
    376 				strncpy(buf, diskp->dk_name, sizeof(buf));
    377 				first = 0;
    378 			} else {
    379 				buf[0] = ' ';
    380 				strncpy(buf + 1, diskp->dk_name,
    381 				    sizeof(buf) - 1);
    382 			}
    383 			buf[DK_DISKNAMELEN] = '\0';
    384 			slen = strlen(buf);
    385 			if (left < slen + 1)
    386 				break;
    387 			/* +1 to copy out the trailing NUL byte */
    388 			error = copyout(buf, where, slen + 1);
    389 			if (error)
    390 				break;
    391 			where += slen;
    392 			needed += slen;
    393 			left -= slen;
    394 		}
    395 	}
    396 	simple_unlock(&disklist_slock);
    397 	*oldlenp = needed;
    398 	return (error);
    399 }
    400 
    401 int
    402 sysctl_hw_diskstats(SYSCTLFN_ARGS)
    403 {
    404 	struct disk_sysctl sdisk;
    405 	struct disk *diskp;
    406 	char *where = oldp;
    407 	size_t tocopy, left;
    408 	int error;
    409 
    410 	if (newp != NULL)
    411 		return (EPERM);
    412 
    413 	/*
    414 	 * The original hw.diskstats call was broken and did not require
    415 	 * the userland to pass in it's size of struct disk_sysctl.  This
    416 	 * was fixed after NetBSD 1.6 was released, and any applications
    417 	 * that do not pass in the size are given an error only, unless
    418 	 * we care about 1.6 compatibility.
    419 	 */
    420 	if (namelen == 0)
    421 #ifdef COMPAT_16
    422 		tocopy = offsetof(struct disk_sysctl, dk_rxfer);
    423 #else
    424 		return (EINVAL);
    425 #endif
    426 	else
    427 		tocopy = name[0];
    428 
    429 	if (where == NULL) {
    430 		*oldlenp = disk_count * tocopy;
    431 		return (0);
    432 	}
    433 
    434 	error = 0;
    435 	left = *oldlenp;
    436 	memset(&sdisk, 0, sizeof(sdisk));
    437 	*oldlenp = 0;
    438 
    439 	simple_lock(&disklist_slock);
    440 	TAILQ_FOREACH(diskp, &disklist, dk_link) {
    441 		if (left < tocopy)
    442 			break;
    443 		strncpy(sdisk.dk_name, diskp->dk_name, sizeof(sdisk.dk_name));
    444 		sdisk.dk_xfer = diskp->dk_rxfer + diskp->dk_wxfer;
    445 		sdisk.dk_rxfer = diskp->dk_rxfer;
    446 		sdisk.dk_wxfer = diskp->dk_wxfer;
    447 		sdisk.dk_seek = diskp->dk_seek;
    448 		sdisk.dk_bytes = diskp->dk_rbytes + diskp->dk_wbytes;
    449 		sdisk.dk_rbytes = diskp->dk_rbytes;
    450 		sdisk.dk_wbytes = diskp->dk_wbytes;
    451 		sdisk.dk_attachtime_sec = diskp->dk_attachtime.tv_sec;
    452 		sdisk.dk_attachtime_usec = diskp->dk_attachtime.tv_usec;
    453 		sdisk.dk_timestamp_sec = diskp->dk_timestamp.tv_sec;
    454 		sdisk.dk_timestamp_usec = diskp->dk_timestamp.tv_usec;
    455 		sdisk.dk_time_sec = diskp->dk_time.tv_sec;
    456 		sdisk.dk_time_usec = diskp->dk_time.tv_usec;
    457 		sdisk.dk_busy = diskp->dk_busy;
    458 
    459 		error = copyout(&sdisk, where, min(tocopy, sizeof(sdisk)));
    460 		if (error)
    461 			break;
    462 		where += tocopy;
    463 		*oldlenp += tocopy;
    464 		left -= tocopy;
    465 	}
    466 	simple_unlock(&disklist_slock);
    467 	return (error);
    468 }
    469 
    470 struct bufq_fcfs {
    471 	TAILQ_HEAD(, buf) bq_head;	/* actual list of buffers */
    472 };
    473 
    474 struct bufq_disksort {
    475 	TAILQ_HEAD(, buf) bq_head;	/* actual list of buffers */
    476 };
    477 
    478 #define PRIO_READ_BURST		48
    479 #define PRIO_WRITE_REQ		16
    480 
    481 struct bufq_prio {
    482 	TAILQ_HEAD(, buf) bq_read, bq_write; /* actual list of buffers */
    483 	struct buf *bq_write_next;	/* next request in bq_write */
    484 	struct buf *bq_next;		/* current request */
    485 	int bq_read_burst;		/* # of consecutive reads */
    486 };
    487 
    488 
    489 /*
    490  * Check if two buf's are in ascending order.
    491  */
    492 static __inline int
    493 buf_inorder(struct buf *bp, struct buf *bq, int sortby)
    494 {
    495 
    496 	if (bp == NULL || bq == NULL)
    497 		return (bq == NULL);
    498 
    499 	if (sortby == BUFQ_SORT_CYLINDER && bp->b_cylinder < bq->b_cylinder)
    500 		return 1;
    501 
    502 	if (bp->b_rawblkno < bq->b_rawblkno)
    503 		return 1;
    504 }
    505 
    506 
    507 /*
    508  * First-come first-served sort for disks.
    509  *
    510  * Requests are appended to the queue without any reordering.
    511  */
    512 static void
    513 bufq_fcfs_put(struct bufq_state *bufq, struct buf *bp)
    514 {
    515 	struct bufq_fcfs *fcfs = bufq->bq_private;
    516 
    517 	TAILQ_INSERT_TAIL(&fcfs->bq_head, bp, b_actq);
    518 }
    519 
    520 static struct buf *
    521 bufq_fcfs_get(struct bufq_state *bufq, int remove)
    522 {
    523 	struct bufq_fcfs *fcfs = bufq->bq_private;
    524 	struct buf *bp;
    525 
    526 	bp = TAILQ_FIRST(&fcfs->bq_head);
    527 
    528 	if (bp != NULL && remove)
    529 		TAILQ_REMOVE(&fcfs->bq_head, bp, b_actq);
    530 
    531 	return (bp);
    532 }
    533 
    534 
    535 /*
    536  * Seek sort for disks.
    537  *
    538  * There are actually two queues, sorted in ascendening order.  The first
    539  * queue holds those requests which are positioned after the current block;
    540  * the second holds requests which came in after their position was passed.
    541  * Thus we implement a one-way scan, retracting after reaching the end of
    542  * the drive to the first request on the second queue, at which time it
    543  * becomes the first queue.
    544  *
    545  * A one-way scan is natural because of the way UNIX read-ahead blocks are
    546  * allocated.
    547  */
    548 static void
    549 bufq_disksort_put(struct bufq_state *bufq, struct buf *bp)
    550 {
    551 	struct bufq_disksort *disksort = bufq->bq_private;
    552 	struct buf *bq, *nbq;
    553 	int sortby;
    554 
    555 	sortby = bufq->bq_flags & BUFQ_SORT_MASK;
    556 
    557 	bq = TAILQ_FIRST(&disksort->bq_head);
    558 
    559 	/*
    560 	 * If the queue is empty it's easy; we just go on the end.
    561 	 */
    562 	if (bq == NULL) {
    563 		TAILQ_INSERT_TAIL(&disksort->bq_head, bp, b_actq);
    564 		return;
    565 	}
    566 
    567 	/*
    568 	 * If we lie before the currently active request, then we
    569 	 * must locate the second request list and add ourselves to it.
    570 	 */
    571 	if (buf_inorder(bp, bq, sortby)) {
    572 		while ((nbq = TAILQ_NEXT(bq, b_actq)) != NULL) {
    573 			/*
    574 			 * Check for an ``inversion'' in the normally ascending
    575 			 * block numbers, indicating the start of the second
    576 			 * request list.
    577 			 */
    578 			if (buf_inorder(nbq, bq, sortby)) {
    579 				/*
    580 				 * Search the second request list for the first
    581 				 * request at a larger block number.  We go
    582 				 * after that; if there is no such request, we
    583 				 * go at the end.
    584 				 */
    585 				do {
    586 					if (buf_inorder(bp, nbq, sortby))
    587 						goto insert;
    588 					bq = nbq;
    589 				} while ((nbq =
    590 				    TAILQ_NEXT(bq, b_actq)) != NULL);
    591 				goto insert;		/* after last */
    592 			}
    593 			bq = nbq;
    594 		}
    595 		/*
    596 		 * No inversions... we will go after the last, and
    597 		 * be the first request in the second request list.
    598 		 */
    599 		goto insert;
    600 	}
    601 	/*
    602 	 * Request is at/after the current request...
    603 	 * sort in the first request list.
    604 	 */
    605 	while ((nbq = TAILQ_NEXT(bq, b_actq)) != NULL) {
    606 		/*
    607 		 * We want to go after the current request if there is an
    608 		 * inversion after it (i.e. it is the end of the first
    609 		 * request list), or if the next request is a larger cylinder
    610 		 * than our request.
    611 		 */
    612 		if (buf_inorder(nbq, bq, sortby) ||
    613 		    buf_inorder(bp, nbq, sortby))
    614 			goto insert;
    615 		bq = nbq;
    616 	}
    617 	/*
    618 	 * Neither a second list nor a larger request... we go at the end of
    619 	 * the first list, which is the same as the end of the whole schebang.
    620 	 */
    621 insert:	TAILQ_INSERT_AFTER(&disksort->bq_head, bq, bp, b_actq);
    622 }
    623 
    624 static struct buf *
    625 bufq_disksort_get(struct bufq_state *bufq, int remove)
    626 {
    627 	struct bufq_disksort *disksort = bufq->bq_private;
    628 	struct buf *bp;
    629 
    630 	bp = TAILQ_FIRST(&disksort->bq_head);
    631 
    632 	if (bp != NULL && remove)
    633 		TAILQ_REMOVE(&disksort->bq_head, bp, b_actq);
    634 
    635 	return (bp);
    636 }
    637 
    638 
    639 /*
    640  * Seek sort for disks.
    641  *
    642  * There are two queues.  The first queue holds read requests; the second
    643  * holds write requests.  The read queue is first-come first-served; the
    644  * write queue is sorted in ascendening block order.
    645  * The read queue is processed first.  After PRIO_READ_BURST consecutive
    646  * read requests with non-empty write queue PRIO_WRITE_REQ requests from
    647  * the write queue will be processed.
    648  */
    649 static void
    650 bufq_prio_put(struct bufq_state *bufq, struct buf *bp)
    651 {
    652 	struct bufq_prio *prio = bufq->bq_private;
    653 	struct buf *bq;
    654 	int sortby;
    655 
    656 	sortby = bufq->bq_flags & BUFQ_SORT_MASK;
    657 
    658 	/*
    659 	 * If it's a read request append it to the list.
    660 	 */
    661 	if ((bp->b_flags & B_READ) == B_READ) {
    662 		TAILQ_INSERT_TAIL(&prio->bq_read, bp, b_actq);
    663 		return;
    664 	}
    665 
    666 	bq = TAILQ_FIRST(&prio->bq_write);
    667 
    668 	/*
    669 	 * If the write list is empty, simply append it to the list.
    670 	 */
    671 	if (bq == NULL) {
    672 		TAILQ_INSERT_TAIL(&prio->bq_write, bp, b_actq);
    673 		prio->bq_write_next = bp;
    674 		return;
    675 	}
    676 
    677 	/*
    678 	 * If we lie after the next request, insert after this request.
    679 	 */
    680 	if (buf_inorder(prio->bq_write_next, bp, sortby))
    681 		bq = prio->bq_write_next;
    682 
    683 	/*
    684 	 * Search for the first request at a larger block number.
    685 	 * We go before this request if it exists.
    686 	 */
    687 	while (bq != NULL && buf_inorder(bq, bp, sortby))
    688 		bq = TAILQ_NEXT(bq, b_actq);
    689 
    690 	if (bq != NULL)
    691 		TAILQ_INSERT_BEFORE(bq, bp, b_actq);
    692 	else
    693 		TAILQ_INSERT_TAIL(&prio->bq_write, bp, b_actq);
    694 }
    695 
    696 static struct buf *
    697 bufq_prio_get(struct bufq_state *bufq, int remove)
    698 {
    699 	struct bufq_prio *prio = bufq->bq_private;
    700 	struct buf *bp;
    701 
    702 	/*
    703 	 * If no current request, get next from the lists.
    704 	 */
    705 	if (prio->bq_next == NULL) {
    706 		/*
    707 		 * If at least one list is empty, select the other.
    708 		 */
    709 		if (TAILQ_FIRST(&prio->bq_read) == NULL) {
    710 			prio->bq_next = prio->bq_write_next;
    711 			prio->bq_read_burst = 0;
    712 		} else if (prio->bq_write_next == NULL) {
    713 			prio->bq_next = TAILQ_FIRST(&prio->bq_read);
    714 			prio->bq_read_burst = 0;
    715 		} else {
    716 			/*
    717 			 * Both list have requests.  Select the read list up
    718 			 * to PRIO_READ_BURST times, then select the write
    719 			 * list PRIO_WRITE_REQ times.
    720 			 */
    721 			if (prio->bq_read_burst++ < PRIO_READ_BURST)
    722 				prio->bq_next = TAILQ_FIRST(&prio->bq_read);
    723 			else if (prio->bq_read_burst <
    724 			    PRIO_READ_BURST + PRIO_WRITE_REQ)
    725 				prio->bq_next = prio->bq_write_next;
    726 			else {
    727 				prio->bq_next = TAILQ_FIRST(&prio->bq_read);
    728 				prio->bq_read_burst = 0;
    729 			}
    730 		}
    731 	}
    732 
    733 	bp = prio->bq_next;
    734 
    735 	if (bp != NULL && remove) {
    736 		if ((bp->b_flags & B_READ) == B_READ)
    737 			TAILQ_REMOVE(&prio->bq_read, bp, b_actq);
    738 		else {
    739 			/*
    740 			 * Advance the write pointer before removing
    741 			 * bp since it is actually prio->bq_write_next.
    742 			 */
    743 			prio->bq_write_next =
    744 			    TAILQ_NEXT(prio->bq_write_next, b_actq);
    745 			TAILQ_REMOVE(&prio->bq_write, bp, b_actq);
    746 			if (prio->bq_write_next == NULL)
    747 				prio->bq_write_next =
    748 				    TAILQ_FIRST(&prio->bq_write);
    749 		}
    750 
    751 		prio->bq_next = NULL;
    752 	}
    753 
    754 	return (bp);
    755 }
    756 
    757 /*
    758  * Create a device buffer queue.
    759  */
    760 void
    761 bufq_alloc(struct bufq_state *bufq, int flags)
    762 {
    763 	struct bufq_fcfs *fcfs;
    764 	struct bufq_disksort *disksort;
    765 	struct bufq_prio *prio;
    766 
    767 	bufq->bq_flags = flags;
    768 
    769 	switch (flags & BUFQ_SORT_MASK) {
    770 	case BUFQ_SORT_RAWBLOCK:
    771 	case BUFQ_SORT_CYLINDER:
    772 		break;
    773 	case 0:
    774 		if ((flags & BUFQ_METHOD_MASK) == BUFQ_FCFS)
    775 			break;
    776 		/* FALLTHROUGH */
    777 	default:
    778 		panic("bufq_alloc: sort out of range");
    779 	}
    780 
    781 	switch (flags & BUFQ_METHOD_MASK) {
    782 	case BUFQ_FCFS:
    783 		bufq->bq_get = bufq_fcfs_get;
    784 		bufq->bq_put = bufq_fcfs_put;
    785 		MALLOC(bufq->bq_private, struct bufq_fcfs *,
    786 		    sizeof(struct bufq_fcfs), M_DEVBUF, M_ZERO);
    787 		fcfs = (struct bufq_fcfs *)bufq->bq_private;
    788 		TAILQ_INIT(&fcfs->bq_head);
    789 		break;
    790 	case BUFQ_DISKSORT:
    791 		bufq->bq_get = bufq_disksort_get;
    792 		bufq->bq_put = bufq_disksort_put;
    793 		MALLOC(bufq->bq_private, struct bufq_disksort *,
    794 		    sizeof(struct bufq_disksort), M_DEVBUF, M_ZERO);
    795 		disksort = (struct bufq_disksort *)bufq->bq_private;
    796 		TAILQ_INIT(&disksort->bq_head);
    797 		break;
    798 	case BUFQ_READ_PRIO:
    799 		bufq->bq_get = bufq_prio_get;
    800 		bufq->bq_put = bufq_prio_put;
    801 		MALLOC(bufq->bq_private, struct bufq_prio *,
    802 		    sizeof(struct bufq_prio), M_DEVBUF, M_ZERO);
    803 		prio = (struct bufq_prio *)bufq->bq_private;
    804 		TAILQ_INIT(&prio->bq_read);
    805 		TAILQ_INIT(&prio->bq_write);
    806 		break;
    807 	default:
    808 		panic("bufq_alloc: method out of range");
    809 	}
    810 }
    811 
    812 /*
    813  * Destroy a device buffer queue.
    814  */
    815 void
    816 bufq_free(struct bufq_state *bufq)
    817 {
    818 
    819 	KASSERT(bufq->bq_private != NULL);
    820 	KASSERT(BUFQ_PEEK(bufq) == NULL);
    821 
    822 	FREE(bufq->bq_private, M_DEVBUF);
    823 	bufq->bq_get = NULL;
    824 	bufq->bq_put = NULL;
    825 }
    826 
    827 /*
    828  * Bounds checking against the media size, used for the raw partition.
    829  * The sector size passed in should currently always be DEV_BSIZE,
    830  * and the media size the size of the device in DEV_BSIZE sectors.
    831  */
    832 int
    833 bounds_check_with_mediasize(struct buf *bp, int secsize, u_int64_t mediasize)
    834 {
    835 	int sz;
    836 
    837 	sz = howmany(bp->b_bcount, secsize);
    838 
    839 	if (bp->b_blkno + sz > mediasize) {
    840 		sz = mediasize - bp->b_blkno;
    841 		if (sz == 0) {
    842 			/* If exactly at end of disk, return EOF. */
    843 			bp->b_resid = bp->b_bcount;
    844 			goto done;
    845 		}
    846 		if (sz < 0) {
    847 			/* If past end of disk, return EINVAL. */
    848 			bp->b_error = EINVAL;
    849 			goto bad;
    850 		}
    851 		/* Otherwise, truncate request. */
    852 		bp->b_bcount = sz << DEV_BSHIFT;
    853 	}
    854 
    855 	return 1;
    856 
    857 bad:
    858 	bp->b_flags |= B_ERROR;
    859 done:
    860 	return 0;
    861 }
    862