xref: /openbsd/sys/kern/vfs_bio.c (revision 8932bfb7)
1 /*	$OpenBSD: vfs_bio.c,v 1.133 2011/07/06 20:50:05 beck Exp $	*/
2 /*	$NetBSD: vfs_bio.c,v 1.44 1996/06/11 11:15:36 pk Exp $	*/
3 
4 /*
5  * Copyright (c) 1994 Christopher G. Demetriou
6  * Copyright (c) 1982, 1986, 1989, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)vfs_bio.c	8.6 (Berkeley) 1/11/94
39  */
40 
41 /*
42  * Some references:
43  *	Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
44  *	Leffler, et al.: The Design and Implementation of the 4.3BSD
45  *		UNIX Operating System (Addison Welley, 1989)
46  */
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/proc.h>
51 #include <sys/buf.h>
52 #include <sys/vnode.h>
53 #include <sys/mount.h>
54 #include <sys/malloc.h>
55 #include <sys/pool.h>
56 #include <sys/resourcevar.h>
57 #include <sys/conf.h>
58 #include <sys/kernel.h>
59 #include <sys/specdev.h>
60 
61 #include <uvm/uvm_extern.h>
62 
63 /*
64  * Definitions for the buffer free lists.
65  */
66 #define	BQUEUES		2		/* number of free buffer queues */
67 
68 #define	BQ_DIRTY	0		/* LRU queue with dirty buffers */
69 #define	BQ_CLEAN	1		/* LRU queue with clean buffers */
70 
71 TAILQ_HEAD(bqueues, buf) bufqueues[BQUEUES];
72 int needbuffer;
73 struct bio_ops bioops;
74 
75 /*
76  * Buffer pool for I/O buffers.
77  */
78 struct pool bufpool;
79 struct bufhead bufhead = LIST_HEAD_INITIALIZER(bufhead);
80 void buf_put(struct buf *);
81 
82 /*
83  * Insq/Remq for the buffer free lists.
84  */
85 #define	binsheadfree(bp, dp)	TAILQ_INSERT_HEAD(dp, bp, b_freelist)
86 #define	binstailfree(bp, dp)	TAILQ_INSERT_TAIL(dp, bp, b_freelist)
87 
88 struct buf *bio_doread(struct vnode *, daddr64_t, int, int);
89 struct buf *buf_get(struct vnode *, daddr64_t, size_t);
90 void bread_cluster_callback(struct buf *);
91 
92 /*
93  * We keep a few counters to monitor the utilization of the buffer cache
94  *
95  *  numbufpages   - number of pages totally allocated.
96  *  numdirtypages - number of pages on BQ_DIRTY queue.
97  *  lodirtypages  - low water mark for buffer cleaning daemon.
98  *  hidirtypages  - high water mark for buffer cleaning daemon.
99  *  numcleanpages - number of pages on BQ_CLEAN queue.
100  *		    Used to track the need to speedup the cleaner and
101  *		    as a reserve for special processes like syncer.
102  *  maxcleanpages - the highest page count on BQ_CLEAN.
103  */
104 
105 struct bcachestats bcstats;
106 long lodirtypages;
107 long hidirtypages;
108 long locleanpages;
109 long hicleanpages;
110 long maxcleanpages;
111 long backoffpages;	/* backoff counter for page allocations */
112 long buflowpages;	/* bufpages low water mark */
113 long bufhighpages; 	/* bufpages high water mark */
114 long bufbackpages; 	/* number of pages we back off when asked to shrink */
115 
116 vsize_t bufkvm;
117 
118 struct proc *cleanerproc;
119 int bd_req;			/* Sleep point for cleaner daemon. */
120 
121 void
122 bremfree(struct buf *bp)
123 {
124 	struct bqueues *dp = NULL;
125 
126 	splassert(IPL_BIO);
127 
128 	/*
129 	 * We only calculate the head of the freelist when removing
130 	 * the last element of the list as that is the only time that
131 	 * it is needed (e.g. to reset the tail pointer).
132 	 *
133 	 * NB: This makes an assumption about how tailq's are implemented.
134 	 */
135 	if (TAILQ_NEXT(bp, b_freelist) == NULL) {
136 		for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
137 			if (dp->tqh_last == &TAILQ_NEXT(bp, b_freelist))
138 				break;
139 		if (dp == &bufqueues[BQUEUES])
140 			panic("bremfree: lost tail");
141 	}
142 	if (!ISSET(bp->b_flags, B_DELWRI)) {
143 		bcstats.numcleanpages -= atop(bp->b_bufsize);
144 	} else {
145 		bcstats.numdirtypages -= atop(bp->b_bufsize);
146 	}
147 	TAILQ_REMOVE(dp, bp, b_freelist);
148 	bcstats.freebufs--;
149 }
150 
151 void
152 buf_put(struct buf *bp)
153 {
154 	splassert(IPL_BIO);
155 
156 #ifdef DIAGNOSTIC
157 	if (bp->b_pobj != NULL)
158 		KASSERT(bp->b_bufsize > 0);
159 	if (ISSET(bp->b_flags, B_DELWRI))
160 		panic("buf_put: releasing dirty buffer");
161 	if (bp->b_freelist.tqe_next != NOLIST &&
162 	    bp->b_freelist.tqe_next != (void *)-1)
163 		panic("buf_put: still on the free list");
164 	if (bp->b_vnbufs.le_next != NOLIST &&
165 	    bp->b_vnbufs.le_next != (void *)-1)
166 		panic("buf_put: still on the vnode list");
167 	if (!LIST_EMPTY(&bp->b_dep))
168 		panic("buf_put: b_dep is not empty");
169 #endif
170 
171 	LIST_REMOVE(bp, b_list);
172 	bcstats.numbufs--;
173 	if (backoffpages) {
174 		backoffpages -= atop(bp->b_bufsize);
175 		if (backoffpages < 0)
176 			backoffpages = 0;
177 	}
178 
179 	if (buf_dealloc_mem(bp) != 0)
180 		return;
181 	pool_put(&bufpool, bp);
182 }
183 
184 /*
185  * Initialize buffers and hash links for buffers.
186  */
187 void
188 bufinit(void)
189 {
190 	u_int64_t dmapages;
191 	struct bqueues *dp;
192 
193 	dmapages = uvm_pagecount(&dma_constraint);
194 
195 	/*
196 	 * If MD code doesn't say otherwise, use 10% of kvm for mappings and
197 	 * 10% of dmaable pages for cache pages.
198 	 */
199 	if (bufcachepercent == 0)
200 		bufcachepercent = 10;
201 	if (bufpages == 0)
202 		bufpages = dmapages * bufcachepercent / 100;
203 
204 	bufhighpages = bufpages;
205 
206 	/*
207 	 * set the base backoff level for the buffer cache to bufpages.
208 	 * we will not allow uvm to steal back more than this number of
209 	 * pages
210 	 */
211 	buflowpages = dmapages * 10 / 100;
212 
213 	/*
214 	 * set bufbackpages to 100 pages, or 10 percent of the low water mark
215 	 * if we don't have that many pages.
216 	 */
217 
218 	bufbackpages = buflowpages * 10 / 100;
219 	if (bufbackpages > 100)
220 		bufbackpages = 100;
221 
222 	if (bufkvm == 0)
223 		bufkvm = (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) / 10;
224 
225 	/*
226 	 * Don't use more than twice the amount of bufpages for mappings.
227 	 * It's twice since we map things sparsely.
228 	 */
229 	if (bufkvm > bufpages * PAGE_SIZE)
230 		bufkvm = bufpages * PAGE_SIZE;
231 	/*
232 	 * Round bufkvm to MAXPHYS because we allocate chunks of va space
233 	 * in MAXPHYS chunks.
234 	 */
235 	bufkvm &= ~(MAXPHYS - 1);
236 
237 	pool_init(&bufpool, sizeof(struct buf), 0, 0, 0, "bufpl", NULL);
238 	pool_setipl(&bufpool, IPL_BIO);
239 	for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
240 		TAILQ_INIT(dp);
241 
242 	/*
243 	 * hmm - bufkvm is an argument because it's static, while
244 	 * bufpages is global because it can change while running.
245  	 */
246 	buf_mem_init(bufkvm);
247 
248 	hidirtypages = (bufpages / 4) * 3;
249 	lodirtypages = bufpages / 2;
250 
251 	/*
252 	 * When we hit 95% of pages being clean, we bring them down to
253 	 * 90% to have some slack.
254 	 */
255 	hicleanpages = bufpages - (bufpages / 20);
256 	locleanpages = bufpages - (bufpages / 10);
257 
258 	maxcleanpages = locleanpages;
259 }
260 
261 /*
262  * Change cachepct
263  */
264 void
265 bufadjust(int newbufpages)
266 {
267 	/*
268 	 * XXX - note, bufkvm was allocated once, based on 10% of physmem
269 	 * see above.
270 	 */
271 	struct buf *bp;
272 	int s;
273 
274 	s = splbio();
275 	bufpages = newbufpages;
276 
277 	hidirtypages = (bufpages / 4) * 3;
278 	lodirtypages = bufpages / 2;
279 
280 	/*
281 	 * When we hit 95% of pages being clean, we bring them down to
282 	 * 90% to have some slack.
283 	 */
284 	hicleanpages = bufpages - (bufpages / 20);
285 	locleanpages = bufpages - (bufpages / 10);
286 
287 	maxcleanpages = locleanpages;
288 
289 	/*
290 	 * If we we have more buffers allocated than bufpages,
291 	 * free them up to get back down. this may possibly consume
292 	 * all our clean pages...
293 	 */
294 	while ((bp = TAILQ_FIRST(&bufqueues[BQ_CLEAN])) &&
295 	    (bcstats.numbufpages > bufpages)) {
296 		bremfree(bp);
297 		if (bp->b_vp) {
298 			RB_REMOVE(buf_rb_bufs,
299 			    &bp->b_vp->v_bufs_tree, bp);
300 			brelvp(bp);
301 		}
302 		buf_put(bp);
303 	}
304 
305 	/*
306 	 * Wake up cleaner if we're getting low on pages. We might
307 	 * now have too much dirty, or have fallen below our low
308 	 * water mark on clean pages so we need to free more stuff
309 	 * up.
310 	 */
311 	if (bcstats.numdirtypages >= hidirtypages ||
312 	    bcstats.numcleanpages <= locleanpages)
313 		wakeup(&bd_req);
314 
315 	/*
316 	 * if immediate action has not freed up enough goo for us
317 	 * to proceed - we tsleep and wait for the cleaner above
318 	 * to do it's work and get us reduced down to sanity.
319 	 */
320 	while (bcstats.numbufpages > bufpages) {
321 		tsleep(&needbuffer, PRIBIO, "needbuffer", 0);
322 	}
323 	splx(s);
324 }
325 
326 /*
327  * Make the buffer cache back off from cachepct.
328  */
329 int
330 bufbackoff(struct uvm_constraint_range *range, long size)
331 {
332 	/*
333 	 * Back off the amount of buffer cache pages. Called by the page
334 	 * daemon to consume buffer cache pages rather than swapping.
335 	 *
336 	 * On success, it frees N pages from the buffer cache, and sets
337 	 * a flag so that the next N allocations from buf_get will recycle
338 	 * a buffer rather than allocate a new one. It then returns 0 to the
339 	 * caller.
340 	 *
341 	 * on failure, it could free no pages from the buffer cache, does
342 	 * nothing and returns -1 to the caller.
343 	 */
344 	long d;
345 
346 	if (bufpages <= buflowpages)
347 		return(-1);
348 
349 	if (bufpages - bufbackpages >= buflowpages)
350 		d = bufbackpages;
351 	else
352 		d = bufpages - buflowpages;
353 	backoffpages = bufbackpages;
354 	bufadjust(bufpages - d);
355 	backoffpages = bufbackpages;
356 	return(0);
357 }
358 
359 struct buf *
360 bio_doread(struct vnode *vp, daddr64_t blkno, int size, int async)
361 {
362 	struct buf *bp;
363 	struct mount *mp;
364 
365 	bp = getblk(vp, blkno, size, 0, 0);
366 
367 	/*
368 	 * If buffer does not have valid data, start a read.
369 	 * Note that if buffer is B_INVAL, getblk() won't return it.
370 	 * Therefore, it's valid if its I/O has completed or been delayed.
371 	 */
372 	if (!ISSET(bp->b_flags, (B_DONE | B_DELWRI))) {
373 		SET(bp->b_flags, B_READ | async);
374 		bcstats.pendingreads++;
375 		bcstats.numreads++;
376 		VOP_STRATEGY(bp);
377 		/* Pay for the read. */
378 		curproc->p_stats->p_ru.ru_inblock++;		/* XXX */
379 	} else if (async) {
380 		brelse(bp);
381 	}
382 
383 	mp = vp->v_type == VBLK? vp->v_specmountpoint : vp->v_mount;
384 
385 	/*
386 	 * Collect statistics on synchronous and asynchronous reads.
387 	 * Reads from block devices are charged to their associated
388 	 * filesystem (if any).
389 	 */
390 	if (mp != NULL) {
391 		if (async == 0)
392 			mp->mnt_stat.f_syncreads++;
393 		else
394 			mp->mnt_stat.f_asyncreads++;
395 	}
396 
397 	return (bp);
398 }
399 
400 /*
401  * Read a disk block.
402  * This algorithm described in Bach (p.54).
403  */
404 int
405 bread(struct vnode *vp, daddr64_t blkno, int size, struct buf **bpp)
406 {
407 	struct buf *bp;
408 
409 	/* Get buffer for block. */
410 	bp = *bpp = bio_doread(vp, blkno, size, 0);
411 
412 	/* Wait for the read to complete, and return result. */
413 	return (biowait(bp));
414 }
415 
416 /*
417  * Read-ahead multiple disk blocks. The first is sync, the rest async.
418  * Trivial modification to the breada algorithm presented in Bach (p.55).
419  */
420 int
421 breadn(struct vnode *vp, daddr64_t blkno, int size, daddr64_t rablks[],
422     int rasizes[], int nrablks, struct buf **bpp)
423 {
424 	struct buf *bp;
425 	int i;
426 
427 	bp = *bpp = bio_doread(vp, blkno, size, 0);
428 
429 	/*
430 	 * For each of the read-ahead blocks, start a read, if necessary.
431 	 */
432 	for (i = 0; i < nrablks; i++) {
433 		/* If it's in the cache, just go on to next one. */
434 		if (incore(vp, rablks[i]))
435 			continue;
436 
437 		/* Get a buffer for the read-ahead block */
438 		(void) bio_doread(vp, rablks[i], rasizes[i], B_ASYNC);
439 	}
440 
441 	/* Otherwise, we had to start a read for it; wait until it's valid. */
442 	return (biowait(bp));
443 }
444 
445 /*
446  * Called from interrupt context.
447  */
448 void
449 bread_cluster_callback(struct buf *bp)
450 {
451 	struct buf **xbpp = bp->b_saveaddr;
452 	int i;
453 
454 	if (xbpp[1] != NULL) {
455 		size_t newsize = xbpp[1]->b_bufsize;
456 
457 		/*
458 		 * Shrink this buffer's mapping to only cover its part of
459 		 * the total I/O.
460 		 */
461 		buf_fix_mapping(bp, newsize);
462 		bp->b_bcount = newsize;
463 	}
464 
465 	for (i = 1; xbpp[i] != 0; i++) {
466 		if (ISSET(bp->b_flags, B_ERROR))
467 			SET(xbpp[i]->b_flags, B_INVAL | B_ERROR);
468 		biodone(xbpp[i]);
469 	}
470 
471 	free(xbpp, M_TEMP);
472 
473 	if (ISSET(bp->b_flags, B_ASYNC)) {
474 		brelse(bp);
475 	} else {
476 		CLR(bp->b_flags, B_WANTED);
477 		wakeup(bp);
478 	}
479 }
480 
481 int
482 bread_cluster(struct vnode *vp, daddr64_t blkno, int size, struct buf **rbpp)
483 {
484 	struct buf *bp, **xbpp;
485 	int howmany, maxra, i, inc;
486 	daddr64_t sblkno;
487 
488 	*rbpp = bio_doread(vp, blkno, size, 0);
489 
490 	if (size != round_page(size))
491 		goto out;
492 
493 	if (VOP_BMAP(vp, blkno + 1, NULL, &sblkno, &maxra))
494 		goto out;
495 
496 	maxra++;
497 	if (sblkno == -1 || maxra < 2)
498 		goto out;
499 
500 	howmany = MAXPHYS / size;
501 	if (howmany > maxra)
502 		howmany = maxra;
503 
504 	xbpp = malloc((howmany + 1) * sizeof(struct buf *), M_TEMP, M_NOWAIT);
505 	if (xbpp == NULL)
506 		goto out;
507 
508 	for (i = howmany - 1; i >= 0; i--) {
509 		size_t sz;
510 
511 		/*
512 		 * First buffer allocates big enough size to cover what
513 		 * all the other buffers need.
514 		 */
515 		sz = i == 0 ? howmany * size : 0;
516 
517 		xbpp[i] = buf_get(vp, blkno + i + 1, sz);
518 		if (xbpp[i] == NULL) {
519 			for (++i; i < howmany; i++) {
520 				SET(xbpp[i]->b_flags, B_INVAL);
521 				brelse(xbpp[i]);
522 			}
523 			free(xbpp, M_TEMP);
524 			goto out;
525 		}
526 	}
527 
528 	bp = xbpp[0];
529 
530 	xbpp[howmany] = 0;
531 
532 	inc = btodb(size);
533 
534 	for (i = 1; i < howmany; i++) {
535 		bcstats.pendingreads++;
536 		bcstats.numreads++;
537 		SET(xbpp[i]->b_flags, B_READ | B_ASYNC);
538 		xbpp[i]->b_blkno = sblkno + (i * inc);
539 		xbpp[i]->b_bufsize = xbpp[i]->b_bcount = size;
540 		xbpp[i]->b_data = NULL;
541 		xbpp[i]->b_pobj = bp->b_pobj;
542 		xbpp[i]->b_poffs = bp->b_poffs + (i * size);
543 	}
544 
545 	KASSERT(bp->b_lblkno == blkno + 1);
546 	KASSERT(bp->b_vp == vp);
547 
548 	bp->b_blkno = sblkno;
549 	SET(bp->b_flags, B_READ | B_ASYNC | B_CALL);
550 
551 	bp->b_saveaddr = (void *)xbpp;
552 	bp->b_iodone = bread_cluster_callback;
553 
554 	bcstats.pendingreads++;
555 	bcstats.numreads++;
556 	VOP_STRATEGY(bp);
557 	curproc->p_stats->p_ru.ru_inblock++;
558 
559 out:
560 	return (biowait(*rbpp));
561 }
562 
563 /*
564  * Block write.  Described in Bach (p.56)
565  */
566 int
567 bwrite(struct buf *bp)
568 {
569 	int rv, async, wasdelayed, s;
570 	struct vnode *vp;
571 	struct mount *mp;
572 
573 	vp = bp->b_vp;
574 	if (vp != NULL)
575 		mp = vp->v_type == VBLK? vp->v_specmountpoint : vp->v_mount;
576 	else
577 		mp = NULL;
578 
579 	/*
580 	 * Remember buffer type, to switch on it later.  If the write was
581 	 * synchronous, but the file system was mounted with MNT_ASYNC,
582 	 * convert it to a delayed write.
583 	 * XXX note that this relies on delayed tape writes being converted
584 	 * to async, not sync writes (which is safe, but ugly).
585 	 */
586 	async = ISSET(bp->b_flags, B_ASYNC);
587 	if (!async && mp && ISSET(mp->mnt_flag, MNT_ASYNC)) {
588 		bdwrite(bp);
589 		return (0);
590 	}
591 
592 	/*
593 	 * Collect statistics on synchronous and asynchronous writes.
594 	 * Writes to block devices are charged to their associated
595 	 * filesystem (if any).
596 	 */
597 	if (mp != NULL) {
598 		if (async)
599 			mp->mnt_stat.f_asyncwrites++;
600 		else
601 			mp->mnt_stat.f_syncwrites++;
602 	}
603 	bcstats.pendingwrites++;
604 	bcstats.numwrites++;
605 
606 	wasdelayed = ISSET(bp->b_flags, B_DELWRI);
607 	CLR(bp->b_flags, (B_READ | B_DONE | B_ERROR | B_DELWRI));
608 
609 	s = splbio();
610 
611 	/*
612 	 * If not synchronous, pay for the I/O operation and make
613 	 * sure the buf is on the correct vnode queue.  We have
614 	 * to do this now, because if we don't, the vnode may not
615 	 * be properly notified that its I/O has completed.
616 	 */
617 	if (wasdelayed) {
618 		reassignbuf(bp);
619 	} else
620 		curproc->p_stats->p_ru.ru_oublock++;
621 
622 
623 	/* Initiate disk write.  Make sure the appropriate party is charged. */
624 	bp->b_vp->v_numoutput++;
625 	splx(s);
626 	SET(bp->b_flags, B_WRITEINPROG);
627 	VOP_STRATEGY(bp);
628 
629 	if (async)
630 		return (0);
631 
632 	/*
633 	 * If I/O was synchronous, wait for it to complete.
634 	 */
635 	rv = biowait(bp);
636 
637 	/* Release the buffer. */
638 	brelse(bp);
639 
640 	return (rv);
641 }
642 
643 
644 /*
645  * Delayed write.
646  *
647  * The buffer is marked dirty, but is not queued for I/O.
648  * This routine should be used when the buffer is expected
649  * to be modified again soon, typically a small write that
650  * partially fills a buffer.
651  *
652  * NB: magnetic tapes cannot be delayed; they must be
653  * written in the order that the writes are requested.
654  *
655  * Described in Leffler, et al. (pp. 208-213).
656  */
657 void
658 bdwrite(struct buf *bp)
659 {
660 	int s;
661 
662 	/*
663 	 * If the block hasn't been seen before:
664 	 *	(1) Mark it as having been seen,
665 	 *	(2) Charge for the write.
666 	 *	(3) Make sure it's on its vnode's correct block list,
667 	 *	(4) If a buffer is rewritten, move it to end of dirty list
668 	 */
669 	if (!ISSET(bp->b_flags, B_DELWRI)) {
670 		SET(bp->b_flags, B_DELWRI);
671 		s = splbio();
672 		reassignbuf(bp);
673 		splx(s);
674 		curproc->p_stats->p_ru.ru_oublock++;	/* XXX */
675 	}
676 
677 	/* If this is a tape block, write the block now. */
678 	if (major(bp->b_dev) < nblkdev &&
679 	    bdevsw[major(bp->b_dev)].d_type == D_TAPE) {
680 		bawrite(bp);
681 		return;
682 	}
683 
684 	/* Otherwise, the "write" is done, so mark and release the buffer. */
685 	CLR(bp->b_flags, B_NEEDCOMMIT);
686 	SET(bp->b_flags, B_DONE);
687 	brelse(bp);
688 }
689 
690 /*
691  * Asynchronous block write; just an asynchronous bwrite().
692  */
693 void
694 bawrite(struct buf *bp)
695 {
696 
697 	SET(bp->b_flags, B_ASYNC);
698 	VOP_BWRITE(bp);
699 }
700 
701 /*
702  * Must be called at splbio()
703  */
704 void
705 buf_dirty(struct buf *bp)
706 {
707 	splassert(IPL_BIO);
708 
709 #ifdef DIAGNOSTIC
710 	if (!ISSET(bp->b_flags, B_BUSY))
711 		panic("Trying to dirty buffer on freelist!");
712 #endif
713 
714 	if (ISSET(bp->b_flags, B_DELWRI) == 0) {
715 		SET(bp->b_flags, B_DELWRI);
716 		reassignbuf(bp);
717 	}
718 }
719 
720 /*
721  * Must be called at splbio()
722  */
723 void
724 buf_undirty(struct buf *bp)
725 {
726 	splassert(IPL_BIO);
727 
728 #ifdef DIAGNOSTIC
729 	if (!ISSET(bp->b_flags, B_BUSY))
730 		panic("Trying to undirty buffer on freelist!");
731 #endif
732 	if (ISSET(bp->b_flags, B_DELWRI)) {
733 		CLR(bp->b_flags, B_DELWRI);
734 		reassignbuf(bp);
735 	}
736 }
737 
738 /*
739  * Release a buffer on to the free lists.
740  * Described in Bach (p. 46).
741  */
742 void
743 brelse(struct buf *bp)
744 {
745 	struct bqueues *bufq;
746 	int s;
747 
748 	s = splbio();
749 
750 	if (bp->b_data != NULL)
751 		KASSERT(bp->b_bufsize > 0);
752 
753 	/*
754 	 * Determine which queue the buffer should be on, then put it there.
755 	 */
756 
757 	/* If it's not cacheable, or an error, mark it invalid. */
758 	if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
759 		SET(bp->b_flags, B_INVAL);
760 
761 	if (ISSET(bp->b_flags, B_INVAL)) {
762 		/*
763 		 * If the buffer is invalid, place it in the clean queue, so it
764 		 * can be reused.
765 		 */
766 		if (LIST_FIRST(&bp->b_dep) != NULL)
767 			buf_deallocate(bp);
768 
769 		if (ISSET(bp->b_flags, B_DELWRI)) {
770 			CLR(bp->b_flags, B_DELWRI);
771 		}
772 
773 		if (bp->b_vp) {
774 			RB_REMOVE(buf_rb_bufs, &bp->b_vp->v_bufs_tree,
775 			    bp);
776 			brelvp(bp);
777 		}
778 		bp->b_vp = NULL;
779 
780 		/*
781 		 * If the buffer has no associated data, place it back in the
782 		 * pool.
783 		 */
784 		if (bp->b_data == NULL && bp->b_pobj == NULL) {
785 			/*
786 			 * Wake up any processes waiting for _this_ buffer to
787 			 * become free. They are not allowed to grab it
788 			 * since it will be freed. But the only sleeper is
789 			 * getblk and it's restarting the operation after
790 			 * sleep.
791 			 */
792 			if (ISSET(bp->b_flags, B_WANTED)) {
793 				CLR(bp->b_flags, B_WANTED);
794 				wakeup(bp);
795 			}
796 			if (bp->b_vp != NULL)
797 				RB_REMOVE(buf_rb_bufs,
798 				    &bp->b_vp->v_bufs_tree, bp);
799 			buf_put(bp);
800 			splx(s);
801 			return;
802 		}
803 
804 		bcstats.numcleanpages += atop(bp->b_bufsize);
805 		if (maxcleanpages < bcstats.numcleanpages)
806 			maxcleanpages = bcstats.numcleanpages;
807 		binsheadfree(bp, &bufqueues[BQ_CLEAN]);
808 	} else {
809 		/*
810 		 * It has valid data.  Put it on the end of the appropriate
811 		 * queue, so that it'll stick around for as long as possible.
812 		 */
813 
814 		if (!ISSET(bp->b_flags, B_DELWRI)) {
815 			bcstats.numcleanpages += atop(bp->b_bufsize);
816 			if (maxcleanpages < bcstats.numcleanpages)
817 				maxcleanpages = bcstats.numcleanpages;
818 			bufq = &bufqueues[BQ_CLEAN];
819 		} else {
820 			bcstats.numdirtypages += atop(bp->b_bufsize);
821 			bufq = &bufqueues[BQ_DIRTY];
822 		}
823 		if (ISSET(bp->b_flags, B_AGE)) {
824 			binsheadfree(bp, bufq);
825 			bp->b_synctime = time_uptime + 30;
826 		} else {
827 			binstailfree(bp, bufq);
828 			bp->b_synctime = time_uptime + 300;
829 		}
830 	}
831 
832 	/* Unlock the buffer. */
833 	bcstats.freebufs++;
834 	CLR(bp->b_flags, (B_AGE | B_ASYNC | B_NOCACHE | B_DEFERRED));
835 	buf_release(bp);
836 
837 	/* Wake up any processes waiting for any buffer to become free. */
838 	if (needbuffer) {
839 		needbuffer--;
840 		wakeup(&needbuffer);
841 	}
842 
843 	/* Wake up any processes waiting for _this_ buffer to become free. */
844 	if (ISSET(bp->b_flags, B_WANTED)) {
845 		CLR(bp->b_flags, B_WANTED);
846 		wakeup(bp);
847 	}
848 
849 	splx(s);
850 }
851 
852 /*
853  * Determine if a block is in the cache. Just look on what would be its hash
854  * chain. If it's there, return a pointer to it, unless it's marked invalid.
855  */
856 struct buf *
857 incore(struct vnode *vp, daddr64_t blkno)
858 {
859 	struct buf *bp;
860 	struct buf b;
861 	int s;
862 
863 	s = splbio();
864 
865 	/* Search buf lookup tree */
866 	b.b_lblkno = blkno;
867 	bp = RB_FIND(buf_rb_bufs, &vp->v_bufs_tree, &b);
868 	if (bp != NULL && ISSET(bp->b_flags, B_INVAL))
869 		bp = NULL;
870 
871 	splx(s);
872 	return (bp);
873 }
874 
875 /*
876  * Get a block of requested size that is associated with
877  * a given vnode and block offset. If it is found in the
878  * block cache, mark it as having been found, make it busy
879  * and return it. Otherwise, return an empty block of the
880  * correct size. It is up to the caller to ensure that the
881  * cached blocks be of the correct size.
882  */
883 struct buf *
884 getblk(struct vnode *vp, daddr64_t blkno, int size, int slpflag, int slptimeo)
885 {
886 	struct buf *bp;
887 	struct buf b;
888 	int s, error;
889 
890 	/*
891 	 * XXX
892 	 * The following is an inlined version of 'incore()', but with
893 	 * the 'invalid' test moved to after the 'busy' test.  It's
894 	 * necessary because there are some cases in which the NFS
895 	 * code sets B_INVAL prior to writing data to the server, but
896 	 * in which the buffers actually contain valid data.  In this
897 	 * case, we can't allow the system to allocate a new buffer for
898 	 * the block until the write is finished.
899 	 */
900 start:
901 	s = splbio();
902 	b.b_lblkno = blkno;
903 	bp = RB_FIND(buf_rb_bufs, &vp->v_bufs_tree, &b);
904 	if (bp != NULL) {
905 		if (ISSET(bp->b_flags, B_BUSY)) {
906 			SET(bp->b_flags, B_WANTED);
907 			error = tsleep(bp, slpflag | (PRIBIO + 1), "getblk",
908 			    slptimeo);
909 			splx(s);
910 			if (error)
911 				return (NULL);
912 			goto start;
913 		}
914 
915 		if (!ISSET(bp->b_flags, B_INVAL)) {
916 			bcstats.cachehits++;
917 			SET(bp->b_flags, B_CACHE);
918 			bremfree(bp);
919 			buf_acquire(bp);
920 			splx(s);
921 			return (bp);
922 		}
923 	}
924 	splx(s);
925 
926 	if ((bp = buf_get(vp, blkno, size)) == NULL)
927 		goto start;
928 
929 	return (bp);
930 }
931 
932 /*
933  * Get an empty, disassociated buffer of given size.
934  */
935 struct buf *
936 geteblk(int size)
937 {
938 	struct buf *bp;
939 
940 	while ((bp = buf_get(NULL, 0, size)) == NULL)
941 		;
942 
943 	return (bp);
944 }
945 
946 /*
947  * Allocate a buffer.
948  */
949 struct buf *
950 buf_get(struct vnode *vp, daddr64_t blkno, size_t size)
951 {
952 	static int gcount = 0;
953 	struct buf *bp;
954 	int poolwait = size == 0 ? PR_NOWAIT : PR_WAITOK;
955 	int npages;
956 	int s;
957 
958 	/*
959 	 * if we were previously backed off, slowly climb back up
960 	 * to the high water mark again.
961 	 */
962 	if ((backoffpages == 0) && (bufpages < bufhighpages)) {
963 		if ( gcount == 0 )  {
964 			bufadjust(bufpages + bufbackpages);
965 			gcount += bufbackpages;
966 		} else
967 			gcount--;
968 	}
969 
970 	s = splbio();
971 	if (size) {
972 		/*
973 		 * Wake up cleaner if we're getting low on pages.
974 		 */
975 		if (bcstats.numdirtypages >= hidirtypages ||
976 		    bcstats.numcleanpages <= locleanpages)
977 			wakeup(&bd_req);
978 
979 		/*
980 		 * If we're above the high water mark for clean pages,
981 		 * free down to the low water mark.
982 		 */
983 		if (bcstats.numcleanpages > hicleanpages) {
984 			while (bcstats.numcleanpages > locleanpages) {
985 				bp = TAILQ_FIRST(&bufqueues[BQ_CLEAN]);
986 				bremfree(bp);
987 				if (bp->b_vp) {
988 					RB_REMOVE(buf_rb_bufs,
989 					    &bp->b_vp->v_bufs_tree, bp);
990 					brelvp(bp);
991 				}
992 				buf_put(bp);
993 			}
994 		}
995 
996 		npages = atop(round_page(size));
997 
998 		/*
999 		 * Free some buffers until we have enough space.
1000 		 */
1001 		while ((bcstats.numbufpages + npages > bufpages)
1002 		    || backoffpages) {
1003 			int freemax = 5;
1004 			int i = freemax;
1005 			while ((bp = TAILQ_FIRST(&bufqueues[BQ_CLEAN])) && i--) {
1006 				bremfree(bp);
1007 				if (bp->b_vp) {
1008 					RB_REMOVE(buf_rb_bufs,
1009 					    &bp->b_vp->v_bufs_tree, bp);
1010 					brelvp(bp);
1011 				}
1012 				buf_put(bp);
1013 			}
1014 			if (freemax == i &&
1015 			    (bcstats.numbufpages + npages > bufpages)) {
1016 				needbuffer++;
1017 				tsleep(&needbuffer, PRIBIO, "needbuffer", 0);
1018 				splx(s);
1019 				return (NULL);
1020 			}
1021 		}
1022 	}
1023 
1024 	bp = pool_get(&bufpool, poolwait|PR_ZERO);
1025 
1026 	if (bp == NULL) {
1027 		splx(s);
1028 		return (NULL);
1029 	}
1030 
1031 	bp->b_freelist.tqe_next = NOLIST;
1032 	bp->b_synctime = time_uptime + 300;
1033 	bp->b_dev = NODEV;
1034 	LIST_INIT(&bp->b_dep);
1035 	bp->b_bcount = size;
1036 
1037 	buf_acquire_unmapped(bp);
1038 
1039 	if (vp != NULL) {
1040 		/*
1041 		 * We insert the buffer into the hash with B_BUSY set
1042 		 * while we allocate pages for it. This way any getblk
1043 		 * that happens while we allocate pages will wait for
1044 		 * this buffer instead of starting its own guf_get.
1045 		 *
1046 		 * But first, we check if someone beat us to it.
1047 		 */
1048 		if (incore(vp, blkno)) {
1049 			pool_put(&bufpool, bp);
1050 			splx(s);
1051 			return (NULL);
1052 		}
1053 
1054 		bp->b_blkno = bp->b_lblkno = blkno;
1055 		bgetvp(vp, bp);
1056 		if (RB_INSERT(buf_rb_bufs, &vp->v_bufs_tree, bp))
1057 			panic("buf_get: dup lblk vp %p bp %p", vp, bp);
1058 	} else {
1059 		bp->b_vnbufs.le_next = NOLIST;
1060 		SET(bp->b_flags, B_INVAL);
1061 		bp->b_vp = NULL;
1062 	}
1063 
1064 	LIST_INSERT_HEAD(&bufhead, bp, b_list);
1065 	bcstats.numbufs++;
1066 
1067 	if (size) {
1068 		buf_alloc_pages(bp, round_page(size));
1069 		buf_map(bp);
1070 	}
1071 
1072 	splx(s);
1073 
1074 	return (bp);
1075 }
1076 
1077 /*
1078  * Buffer cleaning daemon.
1079  */
1080 void
1081 buf_daemon(struct proc *p)
1082 {
1083 	struct timeval starttime, timediff;
1084 	struct buf *bp;
1085 	int s;
1086 
1087 	cleanerproc = curproc;
1088 
1089 	s = splbio();
1090 	for (;;) {
1091 		if (bcstats.numdirtypages < hidirtypages)
1092 			tsleep(&bd_req, PRIBIO - 7, "cleaner", 0);
1093 
1094 		getmicrouptime(&starttime);
1095 
1096 		while ((bp = TAILQ_FIRST(&bufqueues[BQ_DIRTY]))) {
1097 			struct timeval tv;
1098 
1099 			if (bcstats.numdirtypages < lodirtypages)
1100 				break;
1101 
1102 			bremfree(bp);
1103 			buf_acquire(bp);
1104 			splx(s);
1105 
1106 			if (ISSET(bp->b_flags, B_INVAL)) {
1107 				brelse(bp);
1108 				s = splbio();
1109 				continue;
1110 			}
1111 #ifdef DIAGNOSTIC
1112 			if (!ISSET(bp->b_flags, B_DELWRI))
1113 				panic("Clean buffer on BQ_DIRTY");
1114 #endif
1115 			if (LIST_FIRST(&bp->b_dep) != NULL &&
1116 			    !ISSET(bp->b_flags, B_DEFERRED) &&
1117 			    buf_countdeps(bp, 0, 0)) {
1118 				SET(bp->b_flags, B_DEFERRED);
1119 				s = splbio();
1120 				bcstats.numdirtypages += atop(bp->b_bufsize);
1121 				binstailfree(bp, &bufqueues[BQ_DIRTY]);
1122 				bcstats.freebufs++;
1123 				buf_release(bp);
1124 				continue;
1125 			}
1126 
1127 			bawrite(bp);
1128 
1129 			/* Never allow processing to run for more than 1 sec */
1130 			getmicrouptime(&tv);
1131 			timersub(&tv, &starttime, &timediff);
1132 			s = splbio();
1133 			if (timediff.tv_sec)
1134 				break;
1135 
1136 		}
1137 	}
1138 }
1139 
1140 /*
1141  * Wait for operations on the buffer to complete.
1142  * When they do, extract and return the I/O's error value.
1143  */
1144 int
1145 biowait(struct buf *bp)
1146 {
1147 	int s;
1148 
1149 	KASSERT(!(bp->b_flags & B_ASYNC));
1150 
1151 	s = splbio();
1152 	while (!ISSET(bp->b_flags, B_DONE))
1153 		tsleep(bp, PRIBIO + 1, "biowait", 0);
1154 	splx(s);
1155 
1156 	/* check for interruption of I/O (e.g. via NFS), then errors. */
1157 	if (ISSET(bp->b_flags, B_EINTR)) {
1158 		CLR(bp->b_flags, B_EINTR);
1159 		return (EINTR);
1160 	}
1161 
1162 	if (ISSET(bp->b_flags, B_ERROR))
1163 		return (bp->b_error ? bp->b_error : EIO);
1164 	else
1165 		return (0);
1166 }
1167 
1168 /*
1169  * Mark I/O complete on a buffer.
1170  *
1171  * If a callback has been requested, e.g. the pageout
1172  * daemon, do so. Otherwise, awaken waiting processes.
1173  *
1174  * [ Leffler, et al., says on p.247:
1175  *	"This routine wakes up the blocked process, frees the buffer
1176  *	for an asynchronous write, or, for a request by the pagedaemon
1177  *	process, invokes a procedure specified in the buffer structure" ]
1178  *
1179  * In real life, the pagedaemon (or other system processes) wants
1180  * to do async stuff to, and doesn't want the buffer brelse()'d.
1181  * (for swap pager, that puts swap buffers on the free lists (!!!),
1182  * for the vn device, that puts malloc'd buffers on the free lists!)
1183  *
1184  * Must be called at splbio().
1185  */
1186 void
1187 biodone(struct buf *bp)
1188 {
1189 	splassert(IPL_BIO);
1190 
1191 	if (ISSET(bp->b_flags, B_DONE))
1192 		panic("biodone already");
1193 	SET(bp->b_flags, B_DONE);		/* note that it's done */
1194 
1195 	if (bp->b_bq)
1196 		bufq_done(bp->b_bq, bp);
1197 
1198 	if (LIST_FIRST(&bp->b_dep) != NULL)
1199 		buf_complete(bp);
1200 
1201 	if (!ISSET(bp->b_flags, B_READ)) {
1202 		CLR(bp->b_flags, B_WRITEINPROG);
1203 		vwakeup(bp->b_vp);
1204 	}
1205 	if (bcstats.numbufs &&
1206 	    (!(ISSET(bp->b_flags, B_RAW) || ISSET(bp->b_flags, B_PHYS)))) {
1207 		if (!ISSET(bp->b_flags, B_READ))
1208 			bcstats.pendingwrites--;
1209 		else
1210 			bcstats.pendingreads--;
1211 	}
1212 	if (ISSET(bp->b_flags, B_CALL)) {	/* if necessary, call out */
1213 		CLR(bp->b_flags, B_CALL);	/* but note callout done */
1214 		(*bp->b_iodone)(bp);
1215 	} else {
1216 		if (ISSET(bp->b_flags, B_ASYNC)) {/* if async, release it */
1217 			brelse(bp);
1218 		} else {			/* or just wakeup the buffer */
1219 			CLR(bp->b_flags, B_WANTED);
1220 			wakeup(bp);
1221 		}
1222 	}
1223 }
1224 
1225 #ifdef DDB
1226 void	bcstats_print(int (*)(const char *, ...));
1227 /*
1228  * bcstats_print: ddb hook to print interesting buffer cache counters
1229  */
1230 void
1231 bcstats_print(int (*pr)(const char *, ...))
1232 {
1233 	(*pr)("Current Buffer Cache status:\n");
1234 	(*pr)("numbufs %lld, freebufs %lld\n",
1235 	    bcstats.numbufs, bcstats.freebufs);
1236     	(*pr)("bufpages %lld, freepages %lld, dirtypages %lld\n",
1237 	    bcstats.numbufpages, bcstats.numfreepages, bcstats.numdirtypages);
1238 	(*pr)("pendingreads %lld, pendingwrites %lld\n",
1239 	    bcstats.pendingreads, bcstats.pendingwrites);
1240 }
1241 #endif
1242