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