xref: /freebsd/sys/kern/vfs_bio.c (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
1 /*
2  * Copyright (c) 1994,1997 John S. Dyson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. Absolutely no warranty of function or purpose is made by the author
12  *		John S. Dyson.
13  *
14  * $FreeBSD$
15  */
16 
17 /*
18  * this file contains a new buffer I/O scheme implementing a coherent
19  * VM object and buffer cache scheme.  Pains have been taken to make
20  * sure that the performance degradation associated with schemes such
21  * as this is not realized.
22  *
23  * Author:  John S. Dyson
24  * Significant help during the development and debugging phases
25  * had been provided by David Greenman, also of the FreeBSD core team.
26  *
27  * see man buf(9) for more info.
28  */
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/bio.h>
33 #include <sys/buf.h>
34 #include <sys/eventhandler.h>
35 #include <sys/lock.h>
36 #include <sys/malloc.h>
37 #include <sys/mount.h>
38 #include <sys/mutex.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/ktr.h>
42 #include <sys/proc.h>
43 #include <sys/reboot.h>
44 #include <sys/resourcevar.h>
45 #include <sys/sysctl.h>
46 #include <sys/vmmeter.h>
47 #include <sys/vnode.h>
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
56 
57 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
58 
59 struct	bio_ops bioops;		/* I/O operation notification */
60 
61 struct buf *buf;		/* buffer header pool */
62 struct swqueue bswlist;
63 struct mtx buftimelock;		/* Interlock on setting prio and timo */
64 
65 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
66 		vm_offset_t to);
67 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
68 		vm_offset_t to);
69 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
70 			       int pageno, vm_page_t m);
71 static void vfs_clean_pages(struct buf * bp);
72 static void vfs_setdirty(struct buf *bp);
73 static void vfs_vmio_release(struct buf *bp);
74 static void vfs_backgroundwritedone(struct buf *bp);
75 static int flushbufqueues(void);
76 
77 static int bd_request;
78 
79 static void buf_daemon __P((void));
80 /*
81  * bogus page -- for I/O to/from partially complete buffers
82  * this is a temporary solution to the problem, but it is not
83  * really that bad.  it would be better to split the buffer
84  * for input in the case of buffers partially already in memory,
85  * but the code is intricate enough already.
86  */
87 vm_page_t bogus_page;
88 int runningbufspace;
89 int vmiodirenable = FALSE;
90 static vm_offset_t bogus_offset;
91 
92 static int bufspace, maxbufspace,
93 	bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
94 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
95 static int maxbdrun;
96 static int needsbuffer;
97 static int numdirtybuffers, hidirtybuffers;
98 static int numfreebuffers, lofreebuffers, hifreebuffers;
99 static int getnewbufcalls;
100 static int getnewbufrestarts;
101 
102 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
103 	&numdirtybuffers, 0, "");
104 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
105 	&hidirtybuffers, 0, "");
106 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
107 	&numfreebuffers, 0, "");
108 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
109 	&lofreebuffers, 0, "");
110 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
111 	&hifreebuffers, 0, "");
112 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
113 	&runningbufspace, 0, "");
114 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD,
115 	&maxbufspace, 0, "");
116 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
117 	&hibufspace, 0, "");
118 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD,
119 	&lobufspace, 0, "");
120 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
121 	&bufspace, 0, "");
122 SYSCTL_INT(_vfs, OID_AUTO, maxbdrun, CTLFLAG_RW,
123 	&maxbdrun, 0, "");
124 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
125 	&maxbufmallocspace, 0, "");
126 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
127 	&bufmallocspace, 0, "");
128 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW,
129 	&getnewbufcalls, 0, "");
130 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW,
131 	&getnewbufrestarts, 0, "");
132 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW,
133 	&vmiodirenable, 0, "");
134 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW,
135 	&bufdefragcnt, 0, "");
136 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW,
137 	&buffreekvacnt, 0, "");
138 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW,
139 	&bufreusecnt, 0, "");
140 
141 static int bufhashmask;
142 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
143 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
144 char *buf_wmesg = BUF_WMESG;
145 
146 extern int vm_swap_size;
147 
148 #define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
149 #define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
150 #define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
151 #define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
152 
153 /*
154  * Buffer hash table code.  Note that the logical block scans linearly, which
155  * gives us some L1 cache locality.
156  */
157 
158 static __inline
159 struct bufhashhdr *
160 bufhash(struct vnode *vnp, daddr_t bn)
161 {
162 	return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
163 }
164 
165 /*
166  *	numdirtywakeup:
167  *
168  *	If someone is blocked due to there being too many dirty buffers,
169  *	and numdirtybuffers is now reasonable, wake them up.
170  */
171 
172 static __inline void
173 numdirtywakeup(void)
174 {
175 	if (numdirtybuffers < hidirtybuffers) {
176 		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
177 			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
178 			wakeup(&needsbuffer);
179 		}
180 	}
181 }
182 
183 /*
184  *	bufspacewakeup:
185  *
186  *	Called when buffer space is potentially available for recovery.
187  *	getnewbuf() will block on this flag when it is unable to free
188  *	sufficient buffer space.  Buffer space becomes recoverable when
189  *	bp's get placed back in the queues.
190  */
191 
192 static __inline void
193 bufspacewakeup(void)
194 {
195 	/*
196 	 * If someone is waiting for BUF space, wake them up.  Even
197 	 * though we haven't freed the kva space yet, the waiting
198 	 * process will be able to now.
199 	 */
200 	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
201 		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
202 		wakeup(&needsbuffer);
203 	}
204 }
205 
206 /*
207  *	bufcountwakeup:
208  *
209  *	Called when a buffer has been added to one of the free queues to
210  *	account for the buffer and to wakeup anyone waiting for free buffers.
211  *	This typically occurs when large amounts of metadata are being handled
212  *	by the buffer cache ( else buffer space runs out first, usually ).
213  */
214 
215 static __inline void
216 bufcountwakeup(void)
217 {
218 	++numfreebuffers;
219 	if (needsbuffer) {
220 		needsbuffer &= ~VFS_BIO_NEED_ANY;
221 		if (numfreebuffers >= hifreebuffers)
222 			needsbuffer &= ~VFS_BIO_NEED_FREE;
223 		wakeup(&needsbuffer);
224 	}
225 }
226 
227 /*
228  *	vfs_buf_test_cache:
229  *
230  *	Called when a buffer is extended.  This function clears the B_CACHE
231  *	bit if the newly extended portion of the buffer does not contain
232  *	valid data.
233  */
234 static __inline__
235 void
236 vfs_buf_test_cache(struct buf *bp,
237 		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
238 		  vm_page_t m)
239 {
240 	if (bp->b_flags & B_CACHE) {
241 		int base = (foff + off) & PAGE_MASK;
242 		if (vm_page_is_valid(m, base, size) == 0)
243 			bp->b_flags &= ~B_CACHE;
244 	}
245 }
246 
247 static __inline__
248 void
249 bd_wakeup(int dirtybuflevel)
250 {
251 	if (numdirtybuffers >= dirtybuflevel && bd_request == 0) {
252 		bd_request = 1;
253 		wakeup(&bd_request);
254 	}
255 }
256 
257 /*
258  * bd_speedup - speedup the buffer cache flushing code
259  */
260 
261 static __inline__
262 void
263 bd_speedup(void)
264 {
265 	bd_wakeup(1);
266 }
267 
268 /*
269  * Initialize buffer headers and related structures.
270  */
271 
272 caddr_t
273 bufhashinit(caddr_t vaddr)
274 {
275 	/* first, make a null hash table */
276 	for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
277 		;
278 	bufhashtbl = (void *)vaddr;
279 	vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
280 	--bufhashmask;
281 	return(vaddr);
282 }
283 
284 void
285 bufinit(void)
286 {
287 	struct buf *bp;
288 	int i;
289 
290 	TAILQ_INIT(&bswlist);
291 	LIST_INIT(&invalhash);
292 	mtx_init(&buftimelock, "buftime lock", MTX_DEF);
293 
294 	for (i = 0; i <= bufhashmask; i++)
295 		LIST_INIT(&bufhashtbl[i]);
296 
297 	/* next, make a null set of free lists */
298 	for (i = 0; i < BUFFER_QUEUES; i++)
299 		TAILQ_INIT(&bufqueues[i]);
300 
301 	/* finally, initialize each buffer header and stick on empty q */
302 	for (i = 0; i < nbuf; i++) {
303 		bp = &buf[i];
304 		bzero(bp, sizeof *bp);
305 		bp->b_flags = B_INVAL;	/* we're just an empty header */
306 		bp->b_dev = NODEV;
307 		bp->b_rcred = NOCRED;
308 		bp->b_wcred = NOCRED;
309 		bp->b_qindex = QUEUE_EMPTY;
310 		bp->b_xflags = 0;
311 		LIST_INIT(&bp->b_dep);
312 		BUF_LOCKINIT(bp);
313 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
314 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
315 	}
316 
317 	/*
318 	 * maxbufspace is the absolute maximum amount of buffer space we are
319 	 * allowed to reserve in KVM and in real terms.  The absolute maximum
320 	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
321 	 * used by most other processes.  The differential is required to
322 	 * ensure that buf_daemon is able to run when other processes might
323 	 * be blocked waiting for buffer space.
324 	 *
325 	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
326 	 * this may result in KVM fragmentation which is not handled optimally
327 	 * by the system.
328 	 */
329 	maxbufspace = nbuf * BKVASIZE;
330 	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
331 	lobufspace = hibufspace - MAXBSIZE;
332 
333 /*
334  * Limit the amount of malloc memory since it is wired permanently into
335  * the kernel space.  Even though this is accounted for in the buffer
336  * allocation, we don't want the malloced region to grow uncontrolled.
337  * The malloc scheme improves memory utilization significantly on average
338  * (small) directories.
339  */
340 	maxbufmallocspace = hibufspace / 20;
341 
342 /*
343  * Reduce the chance of a deadlock occuring by limiting the number
344  * of delayed-write dirty buffers we allow to stack up.
345  */
346 	hidirtybuffers = nbuf / 4 + 20;
347 	numdirtybuffers = 0;
348 /*
349  * To support extreme low-memory systems, make sure hidirtybuffers cannot
350  * eat up all available buffer space.  This occurs when our minimum cannot
351  * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
352  * BKVASIZE'd (8K) buffers.
353  */
354 	while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
355 		hidirtybuffers >>= 1;
356 	}
357 
358 /*
359  * Try to keep the number of free buffers in the specified range,
360  * and give special processes (e.g. like buf_daemon) access to an
361  * emergency reserve.
362  */
363 	lofreebuffers = nbuf / 18 + 5;
364 	hifreebuffers = 2 * lofreebuffers;
365 	numfreebuffers = nbuf;
366 
367 /*
368  * Maximum number of async ops initiated per buf_daemon loop.  This is
369  * somewhat of a hack at the moment, we really need to limit ourselves
370  * based on the number of bytes of I/O in-transit that were initiated
371  * from buf_daemon.
372  */
373 	if ((maxbdrun = nswbuf / 4) < 4)
374 		maxbdrun = 4;
375 
376 	bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
377 	bogus_page = vm_page_alloc(kernel_object,
378 			((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
379 			VM_ALLOC_NORMAL);
380 	cnt.v_wire_count++;
381 
382 }
383 
384 /*
385  * bfreekva() - free the kva allocation for a buffer.
386  *
387  *	Must be called at splbio() or higher as this is the only locking for
388  *	buffer_map.
389  *
390  *	Since this call frees up buffer space, we call bufspacewakeup().
391  */
392 static void
393 bfreekva(struct buf * bp)
394 {
395 	if (bp->b_kvasize) {
396 		++buffreekvacnt;
397 		bufspace -= bp->b_kvasize;
398 		vm_map_delete(buffer_map,
399 		    (vm_offset_t) bp->b_kvabase,
400 		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize
401 		);
402 		bp->b_kvasize = 0;
403 		bufspacewakeup();
404 	}
405 }
406 
407 /*
408  *	bremfree:
409  *
410  *	Remove the buffer from the appropriate free list.
411  */
412 void
413 bremfree(struct buf * bp)
414 {
415 	int s = splbio();
416 	int old_qindex = bp->b_qindex;
417 
418 	if (bp->b_qindex != QUEUE_NONE) {
419 		KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
420 		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
421 		bp->b_qindex = QUEUE_NONE;
422 		runningbufspace += bp->b_bufsize;
423 	} else {
424 		if (BUF_REFCNT(bp) <= 1)
425 			panic("bremfree: removing a buffer not on a queue");
426 	}
427 
428 	/*
429 	 * Fixup numfreebuffers count.  If the buffer is invalid or not
430 	 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
431 	 * the buffer was free and we must decrement numfreebuffers.
432 	 */
433 	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
434 		switch(old_qindex) {
435 		case QUEUE_DIRTY:
436 		case QUEUE_CLEAN:
437 		case QUEUE_EMPTY:
438 		case QUEUE_EMPTYKVA:
439 			--numfreebuffers;
440 			break;
441 		default:
442 			break;
443 		}
444 	}
445 	splx(s);
446 }
447 
448 
449 /*
450  * Get a buffer with the specified data.  Look in the cache first.  We
451  * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
452  * is set, the buffer is valid and we do not have to do anything ( see
453  * getblk() ).
454  */
455 int
456 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
457     struct buf ** bpp)
458 {
459 	struct buf *bp;
460 
461 	bp = getblk(vp, blkno, size, 0, 0);
462 	*bpp = bp;
463 
464 	/* if not found in cache, do some I/O */
465 	if ((bp->b_flags & B_CACHE) == 0) {
466 		if (curproc != idleproc)
467 			curproc->p_stats->p_ru.ru_inblock++;
468 		KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
469 		bp->b_iocmd = BIO_READ;
470 		bp->b_flags &= ~B_INVAL;
471 		bp->b_ioflags &= ~BIO_ERROR;
472 		if (bp->b_rcred == NOCRED) {
473 			if (cred != NOCRED)
474 				crhold(cred);
475 			bp->b_rcred = cred;
476 		}
477 		vfs_busy_pages(bp, 0);
478 		VOP_STRATEGY(vp, bp);
479 		return (bufwait(bp));
480 	}
481 	return (0);
482 }
483 
484 /*
485  * Operates like bread, but also starts asynchronous I/O on
486  * read-ahead blocks.  We must clear BIO_ERROR and B_INVAL prior
487  * to initiating I/O . If B_CACHE is set, the buffer is valid
488  * and we do not have to do anything.
489  */
490 int
491 breadn(struct vnode * vp, daddr_t blkno, int size,
492     daddr_t * rablkno, int *rabsize,
493     int cnt, struct ucred * cred, struct buf ** bpp)
494 {
495 	struct buf *bp, *rabp;
496 	int i;
497 	int rv = 0, readwait = 0;
498 
499 	*bpp = bp = getblk(vp, blkno, size, 0, 0);
500 
501 	/* if not found in cache, do some I/O */
502 	if ((bp->b_flags & B_CACHE) == 0) {
503 		if (curproc != idleproc)
504 			curproc->p_stats->p_ru.ru_inblock++;
505 		bp->b_iocmd = BIO_READ;
506 		bp->b_flags &= ~B_INVAL;
507 		bp->b_ioflags &= ~BIO_ERROR;
508 		if (bp->b_rcred == NOCRED) {
509 			if (cred != NOCRED)
510 				crhold(cred);
511 			bp->b_rcred = cred;
512 		}
513 		vfs_busy_pages(bp, 0);
514 		VOP_STRATEGY(vp, bp);
515 		++readwait;
516 	}
517 
518 	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
519 		if (inmem(vp, *rablkno))
520 			continue;
521 		rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
522 
523 		if ((rabp->b_flags & B_CACHE) == 0) {
524 			if (curproc != idleproc)
525 				curproc->p_stats->p_ru.ru_inblock++;
526 			rabp->b_flags |= B_ASYNC;
527 			rabp->b_flags &= ~B_INVAL;
528 			rabp->b_ioflags &= ~BIO_ERROR;
529 			rabp->b_iocmd = BIO_READ;
530 			if (rabp->b_rcred == NOCRED) {
531 				if (cred != NOCRED)
532 					crhold(cred);
533 				rabp->b_rcred = cred;
534 			}
535 			vfs_busy_pages(rabp, 0);
536 			BUF_KERNPROC(rabp);
537 			VOP_STRATEGY(vp, rabp);
538 		} else {
539 			brelse(rabp);
540 		}
541 	}
542 
543 	if (readwait) {
544 		rv = bufwait(bp);
545 	}
546 	return (rv);
547 }
548 
549 /*
550  * Write, release buffer on completion.  (Done by iodone
551  * if async).  Do not bother writing anything if the buffer
552  * is invalid.
553  *
554  * Note that we set B_CACHE here, indicating that buffer is
555  * fully valid and thus cacheable.  This is true even of NFS
556  * now so we set it generally.  This could be set either here
557  * or in biodone() since the I/O is synchronous.  We put it
558  * here.
559  */
560 int
561 bwrite(struct buf * bp)
562 {
563 	int oldflags, s;
564 	struct buf *newbp;
565 
566 	if (bp->b_flags & B_INVAL) {
567 		brelse(bp);
568 		return (0);
569 	}
570 
571 	oldflags = bp->b_flags;
572 
573 	if (BUF_REFCNT(bp) == 0)
574 		panic("bwrite: buffer is not busy???");
575 	s = splbio();
576 	/*
577 	 * If a background write is already in progress, delay
578 	 * writing this block if it is asynchronous. Otherwise
579 	 * wait for the background write to complete.
580 	 */
581 	if (bp->b_xflags & BX_BKGRDINPROG) {
582 		if (bp->b_flags & B_ASYNC) {
583 			splx(s);
584 			bdwrite(bp);
585 			return (0);
586 		}
587 		bp->b_xflags |= BX_BKGRDWAIT;
588 		tsleep(&bp->b_xflags, PRIBIO, "biord", 0);
589 		if (bp->b_xflags & BX_BKGRDINPROG)
590 			panic("bwrite: still writing");
591 	}
592 
593 	/* Mark the buffer clean */
594 	bundirty(bp);
595 
596 	/*
597 	 * If this buffer is marked for background writing and we
598 	 * do not have to wait for it, make a copy and write the
599 	 * copy so as to leave this buffer ready for further use.
600 	 *
601 	 * This optimization eats a lot of memory.  If we have a page
602 	 * or buffer shortfall we can't do it.
603 	 */
604 	if ((bp->b_xflags & BX_BKGRDWRITE) &&
605 	    (bp->b_flags & B_ASYNC) &&
606 	    !vm_page_count_severe() &&
607 	    !buf_dirty_count_severe()) {
608 		if (bp->b_iodone != NULL) {
609 			printf("bp->b_iodone = %p\n", bp->b_iodone);
610 			panic("bwrite: need chained iodone");
611 		}
612 
613 		/* get a new block */
614 		newbp = geteblk(bp->b_bufsize);
615 
616 		/* set it to be identical to the old block */
617 		memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
618 		bgetvp(bp->b_vp, newbp);
619 		newbp->b_lblkno = bp->b_lblkno;
620 		newbp->b_blkno = bp->b_blkno;
621 		newbp->b_offset = bp->b_offset;
622 		newbp->b_iodone = vfs_backgroundwritedone;
623 		newbp->b_flags |= B_ASYNC;
624 		newbp->b_flags &= ~B_INVAL;
625 
626 		/* move over the dependencies */
627 		if (LIST_FIRST(&bp->b_dep) != NULL)
628 			buf_movedeps(bp, newbp);
629 
630 		/*
631 		 * Initiate write on the copy, release the original to
632 		 * the B_LOCKED queue so that it cannot go away until
633 		 * the background write completes. If not locked it could go
634 		 * away and then be reconstituted while it was being written.
635 		 * If the reconstituted buffer were written, we could end up
636 		 * with two background copies being written at the same time.
637 		 */
638 		bp->b_xflags |= BX_BKGRDINPROG;
639 		bp->b_flags |= B_LOCKED;
640 		bqrelse(bp);
641 		bp = newbp;
642 	}
643 
644 	bp->b_flags &= ~B_DONE;
645 	bp->b_ioflags &= ~BIO_ERROR;
646 	bp->b_flags |= B_WRITEINPROG | B_CACHE;
647 	bp->b_iocmd = BIO_WRITE;
648 
649 	bp->b_vp->v_numoutput++;
650 	vfs_busy_pages(bp, 1);
651 	if (curproc != idleproc)
652 		curproc->p_stats->p_ru.ru_oublock++;
653 	splx(s);
654 	if (oldflags & B_ASYNC)
655 		BUF_KERNPROC(bp);
656 	BUF_STRATEGY(bp);
657 
658 	if ((oldflags & B_ASYNC) == 0) {
659 		int rtval = bufwait(bp);
660 		brelse(bp);
661 		return (rtval);
662 	}
663 
664 	return (0);
665 }
666 
667 /*
668  * Complete a background write started from bwrite.
669  */
670 static void
671 vfs_backgroundwritedone(bp)
672 	struct buf *bp;
673 {
674 	struct buf *origbp;
675 
676 	/*
677 	 * Find the original buffer that we are writing.
678 	 */
679 	if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
680 		panic("backgroundwritedone: lost buffer");
681 	/*
682 	 * Process dependencies then return any unfinished ones.
683 	 */
684 	if (LIST_FIRST(&bp->b_dep) != NULL)
685 		buf_complete(bp);
686 	if (LIST_FIRST(&bp->b_dep) != NULL)
687 		buf_movedeps(bp, origbp);
688 	/*
689 	 * Clear the BX_BKGRDINPROG flag in the original buffer
690 	 * and awaken it if it is waiting for the write to complete.
691 	 * If BX_BKGRDINPROG is not set in the original buffer it must
692 	 * have been released and re-instantiated - which is not legal.
693 	 */
694 	KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
695 	origbp->b_xflags &= ~BX_BKGRDINPROG;
696 	if (origbp->b_xflags & BX_BKGRDWAIT) {
697 		origbp->b_xflags &= ~BX_BKGRDWAIT;
698 		wakeup(&origbp->b_xflags);
699 	}
700 	/*
701 	 * Clear the B_LOCKED flag and remove it from the locked
702 	 * queue if it currently resides there.
703 	 */
704 	origbp->b_flags &= ~B_LOCKED;
705 	if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
706 		bremfree(origbp);
707 		bqrelse(origbp);
708 	}
709 	/*
710 	 * This buffer is marked B_NOCACHE, so when it is released
711 	 * by biodone, it will be tossed. We mark it with BIO_READ
712 	 * to avoid biodone doing a second vwakeup.
713 	 */
714 	bp->b_flags |= B_NOCACHE;
715 	bp->b_iocmd = BIO_READ;
716 	bp->b_flags &= ~(B_CACHE | B_DONE);
717 	bp->b_iodone = 0;
718 	bufdone(bp);
719 }
720 
721 /*
722  * Delayed write. (Buffer is marked dirty).  Do not bother writing
723  * anything if the buffer is marked invalid.
724  *
725  * Note that since the buffer must be completely valid, we can safely
726  * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
727  * biodone() in order to prevent getblk from writing the buffer
728  * out synchronously.
729  */
730 void
731 bdwrite(struct buf * bp)
732 {
733 	if (BUF_REFCNT(bp) == 0)
734 		panic("bdwrite: buffer is not busy");
735 
736 	if (bp->b_flags & B_INVAL) {
737 		brelse(bp);
738 		return;
739 	}
740 	bdirty(bp);
741 
742 	/*
743 	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
744 	 * true even of NFS now.
745 	 */
746 	bp->b_flags |= B_CACHE;
747 
748 	/*
749 	 * This bmap keeps the system from needing to do the bmap later,
750 	 * perhaps when the system is attempting to do a sync.  Since it
751 	 * is likely that the indirect block -- or whatever other datastructure
752 	 * that the filesystem needs is still in memory now, it is a good
753 	 * thing to do this.  Note also, that if the pageout daemon is
754 	 * requesting a sync -- there might not be enough memory to do
755 	 * the bmap then...  So, this is important to do.
756 	 */
757 	if (bp->b_lblkno == bp->b_blkno) {
758 		VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
759 	}
760 
761 	/*
762 	 * Set the *dirty* buffer range based upon the VM system dirty pages.
763 	 */
764 	vfs_setdirty(bp);
765 
766 	/*
767 	 * We need to do this here to satisfy the vnode_pager and the
768 	 * pageout daemon, so that it thinks that the pages have been
769 	 * "cleaned".  Note that since the pages are in a delayed write
770 	 * buffer -- the VFS layer "will" see that the pages get written
771 	 * out on the next sync, or perhaps the cluster will be completed.
772 	 */
773 	vfs_clean_pages(bp);
774 	bqrelse(bp);
775 
776 	/*
777 	 * Wakeup the buffer flushing daemon if we have saturated the
778 	 * buffer cache.
779 	 */
780 
781 	bd_wakeup(hidirtybuffers);
782 
783 	/*
784 	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
785 	 * due to the softdep code.
786 	 */
787 }
788 
789 /*
790  *	bdirty:
791  *
792  *	Turn buffer into delayed write request.  We must clear BIO_READ and
793  *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
794  *	itself to properly update it in the dirty/clean lists.  We mark it
795  *	B_DONE to ensure that any asynchronization of the buffer properly
796  *	clears B_DONE ( else a panic will occur later ).
797  *
798  *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
799  *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
800  *	should only be called if the buffer is known-good.
801  *
802  *	Since the buffer is not on a queue, we do not update the numfreebuffers
803  *	count.
804  *
805  *	Must be called at splbio().
806  *	The buffer must be on QUEUE_NONE.
807  */
808 void
809 bdirty(bp)
810 	struct buf *bp;
811 {
812 	KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
813 	bp->b_flags &= ~(B_RELBUF);
814 	bp->b_iocmd = BIO_WRITE;
815 
816 	if ((bp->b_flags & B_DELWRI) == 0) {
817 		bp->b_flags |= B_DONE | B_DELWRI;
818 		reassignbuf(bp, bp->b_vp);
819 		++numdirtybuffers;
820 		bd_wakeup(hidirtybuffers);
821 	}
822 }
823 
824 /*
825  *	bundirty:
826  *
827  *	Clear B_DELWRI for buffer.
828  *
829  *	Since the buffer is not on a queue, we do not update the numfreebuffers
830  *	count.
831  *
832  *	Must be called at splbio().
833  *	The buffer must be on QUEUE_NONE.
834  */
835 
836 void
837 bundirty(bp)
838 	struct buf *bp;
839 {
840 	KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
841 
842 	if (bp->b_flags & B_DELWRI) {
843 		bp->b_flags &= ~B_DELWRI;
844 		reassignbuf(bp, bp->b_vp);
845 		--numdirtybuffers;
846 		numdirtywakeup();
847 	}
848 	/*
849 	 * Since it is now being written, we can clear its deferred write flag.
850 	 */
851 	bp->b_flags &= ~B_DEFERRED;
852 }
853 
854 /*
855  *	bawrite:
856  *
857  *	Asynchronous write.  Start output on a buffer, but do not wait for
858  *	it to complete.  The buffer is released when the output completes.
859  *
860  *	bwrite() ( or the VOP routine anyway ) is responsible for handling
861  *	B_INVAL buffers.  Not us.
862  */
863 void
864 bawrite(struct buf * bp)
865 {
866 	bp->b_flags |= B_ASYNC;
867 	(void) BUF_WRITE(bp);
868 }
869 
870 /*
871  *	bowrite:
872  *
873  *	Ordered write.  Start output on a buffer, and flag it so that the
874  *	device will write it in the order it was queued.  The buffer is
875  *	released when the output completes.  bwrite() ( or the VOP routine
876  *	anyway ) is responsible for handling B_INVAL buffers.
877  */
878 int
879 bowrite(struct buf * bp)
880 {
881 	bp->b_ioflags |= BIO_ORDERED;
882 	bp->b_flags |= B_ASYNC;
883 	return (BUF_WRITE(bp));
884 }
885 
886 /*
887  *	bwillwrite:
888  *
889  *	Called prior to the locking of any vnodes when we are expecting to
890  *	write.  We do not want to starve the buffer cache with too many
891  *	dirty buffers so we block here.  By blocking prior to the locking
892  *	of any vnodes we attempt to avoid the situation where a locked vnode
893  *	prevents the various system daemons from flushing related buffers.
894  */
895 
896 void
897 bwillwrite(void)
898 {
899 	int slop = hidirtybuffers / 10;
900 
901 	if (numdirtybuffers > hidirtybuffers + slop) {
902 		int s;
903 
904 		s = splbio();
905 		while (numdirtybuffers > hidirtybuffers) {
906 			bd_wakeup(hidirtybuffers);
907 			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
908 			tsleep(&needsbuffer, (PRIBIO + 4), "flswai", 0);
909 		}
910 		splx(s);
911 	}
912 }
913 
914 /*
915  * Return true if we have too many dirty buffers.
916  */
917 int
918 buf_dirty_count_severe(void)
919 {
920 	return(numdirtybuffers >= hidirtybuffers);
921 }
922 
923 /*
924  *	brelse:
925  *
926  *	Release a busy buffer and, if requested, free its resources.  The
927  *	buffer will be stashed in the appropriate bufqueue[] allowing it
928  *	to be accessed later as a cache entity or reused for other purposes.
929  */
930 void
931 brelse(struct buf * bp)
932 {
933 	int s;
934 
935 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
936 
937 	s = splbio();
938 
939 	if (bp->b_flags & B_LOCKED)
940 		bp->b_ioflags &= ~BIO_ERROR;
941 
942 	if (bp->b_iocmd == BIO_WRITE &&
943 	    (bp->b_ioflags & BIO_ERROR) &&
944 	    !(bp->b_flags & B_INVAL)) {
945 		/*
946 		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
947 		 * pages from being scrapped.  If B_INVAL is set then
948 		 * this case is not run and the next case is run to
949 		 * destroy the buffer.  B_INVAL can occur if the buffer
950 		 * is outside the range supported by the underlying device.
951 		 */
952 		bp->b_ioflags &= ~BIO_ERROR;
953 		bdirty(bp);
954 	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
955 	    (bp->b_ioflags & BIO_ERROR) ||
956 	    bp->b_iocmd == BIO_DELETE || (bp->b_bufsize <= 0)) {
957 		/*
958 		 * Either a failed I/O or we were asked to free or not
959 		 * cache the buffer.
960 		 */
961 		bp->b_flags |= B_INVAL;
962 		if (LIST_FIRST(&bp->b_dep) != NULL)
963 			buf_deallocate(bp);
964 		if (bp->b_flags & B_DELWRI) {
965 			--numdirtybuffers;
966 			numdirtywakeup();
967 		}
968 		bp->b_flags &= ~(B_DELWRI | B_CACHE);
969 		if ((bp->b_flags & B_VMIO) == 0) {
970 			if (bp->b_bufsize)
971 				allocbuf(bp, 0);
972 			if (bp->b_vp)
973 				brelvp(bp);
974 		}
975 	}
976 
977 	/*
978 	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
979 	 * is called with B_DELWRI set, the underlying pages may wind up
980 	 * getting freed causing a previous write (bdwrite()) to get 'lost'
981 	 * because pages associated with a B_DELWRI bp are marked clean.
982 	 *
983 	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
984 	 * if B_DELWRI is set.
985 	 *
986 	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
987 	 * on pages to return pages to the VM page queues.
988 	 */
989 	if (bp->b_flags & B_DELWRI)
990 		bp->b_flags &= ~B_RELBUF;
991 	else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
992 		bp->b_flags |= B_RELBUF;
993 
994 	/*
995 	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
996 	 * constituted, not even NFS buffers now.  Two flags effect this.  If
997 	 * B_INVAL, the struct buf is invalidated but the VM object is kept
998 	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
999 	 *
1000 	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1001 	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1002 	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1003 	 *
1004 	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1005 	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1006 	 * the commit state and we cannot afford to lose the buffer. If the
1007 	 * buffer has a background write in progress, we need to keep it
1008 	 * around to prevent it from being reconstituted and starting a second
1009 	 * background write.
1010 	 */
1011 	if ((bp->b_flags & B_VMIO)
1012 	    && !(bp->b_vp->v_tag == VT_NFS &&
1013 		 !vn_isdisk(bp->b_vp, NULL) &&
1014 		 (bp->b_flags & B_DELWRI))
1015 	    ) {
1016 
1017 		int i, j, resid;
1018 		vm_page_t m;
1019 		off_t foff;
1020 		vm_pindex_t poff;
1021 		vm_object_t obj;
1022 		struct vnode *vp;
1023 
1024 		vp = bp->b_vp;
1025 
1026 		/*
1027 		 * Get the base offset and length of the buffer.  Note that
1028 		 * for block sizes that are less then PAGE_SIZE, the b_data
1029 		 * base of the buffer does not represent exactly b_offset and
1030 		 * neither b_offset nor b_size are necessarily page aligned.
1031 		 * Instead, the starting position of b_offset is:
1032 		 *
1033 		 * 	b_data + (b_offset & PAGE_MASK)
1034 		 *
1035 		 * block sizes less then DEV_BSIZE (usually 512) are not
1036 		 * supported due to the page granularity bits (m->valid,
1037 		 * m->dirty, etc...).
1038 		 *
1039 		 * See man buf(9) for more information
1040 		 */
1041 		resid = bp->b_bufsize;
1042 		foff = bp->b_offset;
1043 
1044 		for (i = 0; i < bp->b_npages; i++) {
1045 			int had_bogus = 0;
1046 
1047 			m = bp->b_pages[i];
1048 			vm_page_flag_clear(m, PG_ZERO);
1049 
1050 			/*
1051 			 * If we hit a bogus page, fixup *all* the bogus pages
1052 			 * now.
1053 			 */
1054 			if (m == bogus_page) {
1055 				VOP_GETVOBJECT(vp, &obj);
1056 				poff = OFF_TO_IDX(bp->b_offset);
1057 				had_bogus = 1;
1058 
1059 				for (j = i; j < bp->b_npages; j++) {
1060 					vm_page_t mtmp;
1061 					mtmp = bp->b_pages[j];
1062 					if (mtmp == bogus_page) {
1063 						mtmp = vm_page_lookup(obj, poff + j);
1064 						if (!mtmp) {
1065 							panic("brelse: page missing\n");
1066 						}
1067 						bp->b_pages[j] = mtmp;
1068 					}
1069 				}
1070 
1071 				if ((bp->b_flags & B_INVAL) == 0) {
1072 					pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1073 				}
1074 				m = bp->b_pages[i];
1075 			}
1076 			if ((bp->b_flags & B_NOCACHE) || (bp->b_ioflags & BIO_ERROR)) {
1077 				int poffset = foff & PAGE_MASK;
1078 				int presid = resid > (PAGE_SIZE - poffset) ?
1079 					(PAGE_SIZE - poffset) : resid;
1080 
1081 				KASSERT(presid >= 0, ("brelse: extra page"));
1082 				vm_page_set_invalid(m, poffset, presid);
1083 				if (had_bogus)
1084 					printf("avoided corruption bug in bogus_page/brelse code\n");
1085 			}
1086 			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1087 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1088 		}
1089 
1090 		if (bp->b_flags & (B_INVAL | B_RELBUF))
1091 			vfs_vmio_release(bp);
1092 
1093 	} else if (bp->b_flags & B_VMIO) {
1094 
1095 		if (bp->b_flags & (B_INVAL | B_RELBUF))
1096 			vfs_vmio_release(bp);
1097 
1098 	}
1099 
1100 	if (bp->b_qindex != QUEUE_NONE)
1101 		panic("brelse: free buffer onto another queue???");
1102 	if (BUF_REFCNT(bp) > 1) {
1103 		/* do not release to free list */
1104 		BUF_UNLOCK(bp);
1105 		splx(s);
1106 		return;
1107 	}
1108 
1109 	/* enqueue */
1110 
1111 	/* buffers with no memory */
1112 	if (bp->b_bufsize == 0) {
1113 		bp->b_flags |= B_INVAL;
1114 		bp->b_xflags &= ~BX_BKGRDWRITE;
1115 		if (bp->b_xflags & BX_BKGRDINPROG)
1116 			panic("losing buffer 1");
1117 		if (bp->b_kvasize) {
1118 			bp->b_qindex = QUEUE_EMPTYKVA;
1119 		} else {
1120 			bp->b_qindex = QUEUE_EMPTY;
1121 		}
1122 		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1123 		LIST_REMOVE(bp, b_hash);
1124 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1125 		bp->b_dev = NODEV;
1126 	/* buffers with junk contents */
1127 	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) || (bp->b_ioflags & BIO_ERROR)) {
1128 		bp->b_flags |= B_INVAL;
1129 		bp->b_xflags &= ~BX_BKGRDWRITE;
1130 		if (bp->b_xflags & BX_BKGRDINPROG)
1131 			panic("losing buffer 2");
1132 		bp->b_qindex = QUEUE_CLEAN;
1133 		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1134 		LIST_REMOVE(bp, b_hash);
1135 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1136 		bp->b_dev = NODEV;
1137 
1138 	/* buffers that are locked */
1139 	} else if (bp->b_flags & B_LOCKED) {
1140 		bp->b_qindex = QUEUE_LOCKED;
1141 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1142 
1143 	/* remaining buffers */
1144 	} else {
1145 		switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1146 		case B_DELWRI | B_AGE:
1147 		    bp->b_qindex = QUEUE_DIRTY;
1148 		    TAILQ_INSERT_HEAD(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1149 		    break;
1150 		case B_DELWRI:
1151 		    bp->b_qindex = QUEUE_DIRTY;
1152 		    TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1153 		    break;
1154 		case B_AGE:
1155 		    bp->b_qindex = QUEUE_CLEAN;
1156 		    TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1157 		    break;
1158 		default:
1159 		    bp->b_qindex = QUEUE_CLEAN;
1160 		    TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1161 		    break;
1162 		}
1163 	}
1164 
1165 	/*
1166 	 * If B_INVAL, clear B_DELWRI.  We've already placed the buffer
1167 	 * on the correct queue.
1168 	 */
1169 	if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI)) {
1170 		bp->b_flags &= ~B_DELWRI;
1171 		--numdirtybuffers;
1172 		numdirtywakeup();
1173 	}
1174 
1175 	runningbufspace -= bp->b_bufsize;
1176 
1177 	/*
1178 	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1179 	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1180 	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1181 	 * if B_INVAL is set ).
1182 	 */
1183 
1184 	if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1185 		bufcountwakeup();
1186 
1187 	/*
1188 	 * Something we can maybe free.
1189 	 */
1190 
1191 	if (bp->b_bufsize || bp->b_kvasize)
1192 		bufspacewakeup();
1193 
1194 	/* unlock */
1195 	BUF_UNLOCK(bp);
1196 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1197 	bp->b_ioflags &= ~BIO_ORDERED;
1198 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1199 		panic("brelse: not dirty");
1200 	splx(s);
1201 }
1202 
1203 /*
1204  * Release a buffer back to the appropriate queue but do not try to free
1205  * it.  The buffer is expected to be used again soon.
1206  *
1207  * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1208  * biodone() to requeue an async I/O on completion.  It is also used when
1209  * known good buffers need to be requeued but we think we may need the data
1210  * again soon.
1211  */
1212 void
1213 bqrelse(struct buf * bp)
1214 {
1215 	int s;
1216 
1217 	s = splbio();
1218 
1219 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1220 
1221 	if (bp->b_qindex != QUEUE_NONE)
1222 		panic("bqrelse: free buffer onto another queue???");
1223 	if (BUF_REFCNT(bp) > 1) {
1224 		/* do not release to free list */
1225 		BUF_UNLOCK(bp);
1226 		splx(s);
1227 		return;
1228 	}
1229 	if (bp->b_flags & B_LOCKED) {
1230 		bp->b_ioflags &= ~BIO_ERROR;
1231 		bp->b_qindex = QUEUE_LOCKED;
1232 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1233 		/* buffers with stale but valid contents */
1234 	} else if (bp->b_flags & B_DELWRI) {
1235 		bp->b_qindex = QUEUE_DIRTY;
1236 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1237 	} else if (vm_page_count_severe()) {
1238 		/*
1239 		 * We are too low on memory, we have to try to free the
1240 		 * buffer (most importantly: the wired pages making up its
1241 		 * backing store) *now*.
1242 		 */
1243 		splx(s);
1244 		brelse(bp);
1245 		return;
1246 	} else {
1247 		bp->b_qindex = QUEUE_CLEAN;
1248 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1249 	}
1250 
1251 	runningbufspace -= bp->b_bufsize;
1252 
1253 	if ((bp->b_flags & B_LOCKED) == 0 &&
1254 	    ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1255 		bufcountwakeup();
1256 	}
1257 
1258 	/*
1259 	 * Something we can maybe wakeup
1260 	 */
1261 	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1262 		bufspacewakeup();
1263 
1264 	/* unlock */
1265 	BUF_UNLOCK(bp);
1266 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1267 	bp->b_ioflags &= ~BIO_ORDERED;
1268 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1269 		panic("bqrelse: not dirty");
1270 	splx(s);
1271 }
1272 
1273 static void
1274 vfs_vmio_release(bp)
1275 	struct buf *bp;
1276 {
1277 	int i, s;
1278 	vm_page_t m;
1279 
1280 	s = splvm();
1281 	for (i = 0; i < bp->b_npages; i++) {
1282 		m = bp->b_pages[i];
1283 		bp->b_pages[i] = NULL;
1284 		/*
1285 		 * In order to keep page LRU ordering consistent, put
1286 		 * everything on the inactive queue.
1287 		 */
1288 		vm_page_unwire(m, 0);
1289 		/*
1290 		 * We don't mess with busy pages, it is
1291 		 * the responsibility of the process that
1292 		 * busied the pages to deal with them.
1293 		 */
1294 		if ((m->flags & PG_BUSY) || (m->busy != 0))
1295 			continue;
1296 
1297 		if (m->wire_count == 0) {
1298 			vm_page_flag_clear(m, PG_ZERO);
1299 			/*
1300 			 * Might as well free the page if we can and it has
1301 			 * no valid data.
1302 			 */
1303 			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1304 				vm_page_busy(m);
1305 				vm_page_protect(m, VM_PROT_NONE);
1306 				vm_page_free(m);
1307 			} else if (vm_page_count_severe()) {
1308 				vm_page_try_to_cache(m);
1309 			}
1310 		}
1311 	}
1312 	runningbufspace -= bp->b_bufsize;
1313 	splx(s);
1314 	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1315 	if (bp->b_bufsize)
1316 		bufspacewakeup();
1317 	bp->b_npages = 0;
1318 	bp->b_bufsize = 0;
1319 	bp->b_flags &= ~B_VMIO;
1320 	if (bp->b_vp)
1321 		brelvp(bp);
1322 }
1323 
1324 /*
1325  * Check to see if a block is currently memory resident.
1326  */
1327 struct buf *
1328 gbincore(struct vnode * vp, daddr_t blkno)
1329 {
1330 	struct buf *bp;
1331 	struct bufhashhdr *bh;
1332 
1333 	bh = bufhash(vp, blkno);
1334 
1335 	/* Search hash chain */
1336 	LIST_FOREACH(bp, bh, b_hash) {
1337 		/* hit */
1338 		if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1339 		    (bp->b_flags & B_INVAL) == 0) {
1340 			break;
1341 		}
1342 	}
1343 	return (bp);
1344 }
1345 
1346 /*
1347  *	vfs_bio_awrite:
1348  *
1349  *	Implement clustered async writes for clearing out B_DELWRI buffers.
1350  *	This is much better then the old way of writing only one buffer at
1351  *	a time.  Note that we may not be presented with the buffers in the
1352  *	correct order, so we search for the cluster in both directions.
1353  */
1354 int
1355 vfs_bio_awrite(struct buf * bp)
1356 {
1357 	int i;
1358 	int j;
1359 	daddr_t lblkno = bp->b_lblkno;
1360 	struct vnode *vp = bp->b_vp;
1361 	int s;
1362 	int ncl;
1363 	struct buf *bpa;
1364 	int nwritten;
1365 	int size;
1366 	int maxcl;
1367 
1368 	s = splbio();
1369 	/*
1370 	 * right now we support clustered writing only to regular files.  If
1371 	 * we find a clusterable block we could be in the middle of a cluster
1372 	 * rather then at the beginning.
1373 	 */
1374 	if ((vp->v_type == VREG) &&
1375 	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1376 	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1377 
1378 		size = vp->v_mount->mnt_stat.f_iosize;
1379 		maxcl = MAXPHYS / size;
1380 
1381 		for (i = 1; i < maxcl; i++) {
1382 			if ((bpa = gbincore(vp, lblkno + i)) &&
1383 			    BUF_REFCNT(bpa) == 0 &&
1384 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1385 			    (B_DELWRI | B_CLUSTEROK)) &&
1386 			    (bpa->b_bufsize == size)) {
1387 				if ((bpa->b_blkno == bpa->b_lblkno) ||
1388 				    (bpa->b_blkno !=
1389 				     bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1390 					break;
1391 			} else {
1392 				break;
1393 			}
1394 		}
1395 		for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1396 			if ((bpa = gbincore(vp, lblkno - j)) &&
1397 			    BUF_REFCNT(bpa) == 0 &&
1398 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1399 			    (B_DELWRI | B_CLUSTEROK)) &&
1400 			    (bpa->b_bufsize == size)) {
1401 				if ((bpa->b_blkno == bpa->b_lblkno) ||
1402 				    (bpa->b_blkno !=
1403 				     bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1404 					break;
1405 			} else {
1406 				break;
1407 			}
1408 		}
1409 		--j;
1410 		ncl = i + j;
1411 		/*
1412 		 * this is a possible cluster write
1413 		 */
1414 		if (ncl != 1) {
1415 			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1416 			splx(s);
1417 			return nwritten;
1418 		}
1419 	}
1420 
1421 	BUF_LOCK(bp, LK_EXCLUSIVE);
1422 	bremfree(bp);
1423 	bp->b_flags |= B_ASYNC;
1424 
1425 	splx(s);
1426 	/*
1427 	 * default (old) behavior, writing out only one block
1428 	 *
1429 	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1430 	 */
1431 	nwritten = bp->b_bufsize;
1432 	(void) BUF_WRITE(bp);
1433 
1434 	return nwritten;
1435 }
1436 
1437 /*
1438  *	getnewbuf:
1439  *
1440  *	Find and initialize a new buffer header, freeing up existing buffers
1441  *	in the bufqueues as necessary.  The new buffer is returned locked.
1442  *
1443  *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1444  *	buffer away, the caller must set B_INVAL prior to calling brelse().
1445  *
1446  *	We block if:
1447  *		We have insufficient buffer headers
1448  *		We have insufficient buffer space
1449  *		buffer_map is too fragmented ( space reservation fails )
1450  *		If we have to flush dirty buffers ( but we try to avoid this )
1451  *
1452  *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1453  *	Instead we ask the buf daemon to do it for us.  We attempt to
1454  *	avoid piecemeal wakeups of the pageout daemon.
1455  */
1456 
1457 static struct buf *
1458 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1459 {
1460 	struct buf *bp;
1461 	struct buf *nbp;
1462 	int defrag = 0;
1463 	int nqindex;
1464 	static int flushingbufs;
1465 
1466 	/*
1467 	 * We can't afford to block since we might be holding a vnode lock,
1468 	 * which may prevent system daemons from running.  We deal with
1469 	 * low-memory situations by proactively returning memory and running
1470 	 * async I/O rather then sync I/O.
1471 	 */
1472 
1473 	++getnewbufcalls;
1474 	--getnewbufrestarts;
1475 restart:
1476 	++getnewbufrestarts;
1477 
1478 	/*
1479 	 * Setup for scan.  If we do not have enough free buffers,
1480 	 * we setup a degenerate case that immediately fails.  Note
1481 	 * that if we are specially marked process, we are allowed to
1482 	 * dip into our reserves.
1483 	 *
1484 	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1485 	 *
1486 	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1487 	 * However, there are a number of cases (defragging, reusing, ...)
1488 	 * where we cannot backup.
1489 	 */
1490 	nqindex = QUEUE_EMPTYKVA;
1491 	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1492 
1493 	if (nbp == NULL) {
1494 		/*
1495 		 * If no EMPTYKVA buffers and we are either
1496 		 * defragging or reusing, locate a CLEAN buffer
1497 		 * to free or reuse.  If bufspace useage is low
1498 		 * skip this step so we can allocate a new buffer.
1499 		 */
1500 		if (defrag || bufspace >= lobufspace) {
1501 			nqindex = QUEUE_CLEAN;
1502 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1503 		}
1504 
1505 		/*
1506 		 * Nada.  If we are allowed to allocate an EMPTY
1507 		 * buffer, go get one.
1508 		 */
1509 		if (nbp == NULL && defrag == 0 && bufspace < hibufspace) {
1510 			nqindex = QUEUE_EMPTY;
1511 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1512 		}
1513 	}
1514 
1515 	/*
1516 	 * Run scan, possibly freeing data and/or kva mappings on the fly
1517 	 * depending.
1518 	 */
1519 
1520 	while ((bp = nbp) != NULL) {
1521 		int qindex = nqindex;
1522 
1523 		/*
1524 		 * Calculate next bp ( we can only use it if we do not block
1525 		 * or do other fancy things ).
1526 		 */
1527 		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1528 			switch(qindex) {
1529 			case QUEUE_EMPTY:
1530 				nqindex = QUEUE_EMPTYKVA;
1531 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1532 					break;
1533 				/* fall through */
1534 			case QUEUE_EMPTYKVA:
1535 				nqindex = QUEUE_CLEAN;
1536 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1537 					break;
1538 				/* fall through */
1539 			case QUEUE_CLEAN:
1540 				/*
1541 				 * nbp is NULL.
1542 				 */
1543 				break;
1544 			}
1545 		}
1546 
1547 		/*
1548 		 * Sanity Checks
1549 		 */
1550 		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1551 
1552 		/*
1553 		 * Note: we no longer distinguish between VMIO and non-VMIO
1554 		 * buffers.
1555 		 */
1556 
1557 		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1558 
1559 		/*
1560 		 * If we are defragging then we need a buffer with
1561 		 * b_kvasize != 0.  XXX this situation should no longer
1562 		 * occur, if defrag is non-zero the buffer's b_kvasize
1563 		 * should also be non-zero at this point.  XXX
1564 		 */
1565 		if (defrag && bp->b_kvasize == 0) {
1566 			printf("Warning: defrag empty buffer %p\n", bp);
1567 			continue;
1568 		}
1569 
1570 		/*
1571 		 * Start freeing the bp.  This is somewhat involved.  nbp
1572 		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1573 		 */
1574 
1575 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1576 			panic("getnewbuf: locked buf");
1577 		bremfree(bp);
1578 
1579 		if (qindex == QUEUE_CLEAN) {
1580 			if (bp->b_flags & B_VMIO) {
1581 				bp->b_flags &= ~B_ASYNC;
1582 				vfs_vmio_release(bp);
1583 			}
1584 			if (bp->b_vp)
1585 				brelvp(bp);
1586 		}
1587 
1588 		/*
1589 		 * NOTE:  nbp is now entirely invalid.  We can only restart
1590 		 * the scan from this point on.
1591 		 *
1592 		 * Get the rest of the buffer freed up.  b_kva* is still
1593 		 * valid after this operation.
1594 		 */
1595 
1596 		if (bp->b_rcred != NOCRED) {
1597 			crfree(bp->b_rcred);
1598 			bp->b_rcred = NOCRED;
1599 		}
1600 		if (bp->b_wcred != NOCRED) {
1601 			crfree(bp->b_wcred);
1602 			bp->b_wcred = NOCRED;
1603 		}
1604 		if (LIST_FIRST(&bp->b_dep) != NULL)
1605 			buf_deallocate(bp);
1606 		if (bp->b_xflags & BX_BKGRDINPROG)
1607 			panic("losing buffer 3");
1608 		LIST_REMOVE(bp, b_hash);
1609 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1610 
1611 		if (bp->b_bufsize)
1612 			allocbuf(bp, 0);
1613 
1614 		bp->b_flags = 0;
1615 		bp->b_ioflags = 0;
1616 		bp->b_xflags = 0;
1617 		bp->b_dev = NODEV;
1618 		bp->b_vp = NULL;
1619 		bp->b_blkno = bp->b_lblkno = 0;
1620 		bp->b_offset = NOOFFSET;
1621 		bp->b_iodone = 0;
1622 		bp->b_error = 0;
1623 		bp->b_resid = 0;
1624 		bp->b_bcount = 0;
1625 		bp->b_npages = 0;
1626 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1627 
1628 		LIST_INIT(&bp->b_dep);
1629 
1630 		/*
1631 		 * If we are defragging then free the buffer.
1632 		 */
1633 		if (defrag) {
1634 			bp->b_flags |= B_INVAL;
1635 			bfreekva(bp);
1636 			brelse(bp);
1637 			defrag = 0;
1638 			goto restart;
1639 		}
1640 
1641 		if (bufspace >= hibufspace)
1642 			flushingbufs = 1;
1643 		if (flushingbufs && bp->b_kvasize != 0) {
1644 			bp->b_flags |= B_INVAL;
1645 			bfreekva(bp);
1646 			brelse(bp);
1647 			goto restart;
1648 		}
1649 		if (bufspace < lobufspace)
1650 			flushingbufs = 0;
1651 		break;
1652 	}
1653 
1654 	/*
1655 	 * If we exhausted our list, sleep as appropriate.  We may have to
1656 	 * wakeup various daemons and write out some dirty buffers.
1657 	 *
1658 	 * Generally we are sleeping due to insufficient buffer space.
1659 	 */
1660 
1661 	if (bp == NULL) {
1662 		int flags;
1663 		char *waitmsg;
1664 
1665 		if (defrag) {
1666 			flags = VFS_BIO_NEED_BUFSPACE;
1667 			waitmsg = "nbufkv";
1668 		} else if (bufspace >= hibufspace) {
1669 			waitmsg = "nbufbs";
1670 			flags = VFS_BIO_NEED_BUFSPACE;
1671 		} else {
1672 			waitmsg = "newbuf";
1673 			flags = VFS_BIO_NEED_ANY;
1674 		}
1675 
1676 		bd_speedup();	/* heeeelp */
1677 
1678 		needsbuffer |= flags;
1679 		while (needsbuffer & flags) {
1680 			if (tsleep(&needsbuffer, (PRIBIO + 4) | slpflag,
1681 			    waitmsg, slptimeo))
1682 				return (NULL);
1683 		}
1684 	} else {
1685 		/*
1686 		 * We finally have a valid bp.  We aren't quite out of the
1687 		 * woods, we still have to reserve kva space.  In order
1688 		 * to keep fragmentation sane we only allocate kva in
1689 		 * BKVASIZE chunks.
1690 		 */
1691 		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1692 
1693 		if (maxsize != bp->b_kvasize) {
1694 			vm_offset_t addr = 0;
1695 
1696 			bfreekva(bp);
1697 
1698 			if (vm_map_findspace(buffer_map,
1699 				vm_map_min(buffer_map), maxsize, &addr)) {
1700 				/*
1701 				 * Uh oh.  Buffer map is to fragmented.  We
1702 				 * must defragment the map.
1703 				 */
1704 				++bufdefragcnt;
1705 				defrag = 1;
1706 				bp->b_flags |= B_INVAL;
1707 				brelse(bp);
1708 				goto restart;
1709 			}
1710 			if (addr) {
1711 				vm_map_insert(buffer_map, NULL, 0,
1712 					addr, addr + maxsize,
1713 					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1714 
1715 				bp->b_kvabase = (caddr_t) addr;
1716 				bp->b_kvasize = maxsize;
1717 				bufspace += bp->b_kvasize;
1718 				++bufreusecnt;
1719 			}
1720 		}
1721 		bp->b_data = bp->b_kvabase;
1722 	}
1723 	return(bp);
1724 }
1725 
1726 #if 0
1727 /*
1728  *	waitfreebuffers:
1729  *
1730  *	Wait for sufficient free buffers.  Only called from normal processes.
1731  */
1732 
1733 static void
1734 waitfreebuffers(int slpflag, int slptimeo)
1735 {
1736 	while (numfreebuffers < hifreebuffers) {
1737 		if (numfreebuffers >= hifreebuffers)
1738 			break;
1739 		needsbuffer |= VFS_BIO_NEED_FREE;
1740 		if (tsleep(&needsbuffer, (PRIBIO + 4)|slpflag, "biofre", slptimeo))
1741 			break;
1742 	}
1743 }
1744 
1745 #endif
1746 
1747 /*
1748  *	buf_daemon:
1749  *
1750  *	buffer flushing daemon.  Buffers are normally flushed by the
1751  *	update daemon but if it cannot keep up this process starts to
1752  *	take the load in an attempt to prevent getnewbuf() from blocking.
1753  */
1754 
1755 static struct proc *bufdaemonproc;
1756 static int bd_interval;
1757 static int bd_flushto;
1758 static int bd_flushinc;
1759 
1760 static struct kproc_desc buf_kp = {
1761 	"bufdaemon",
1762 	buf_daemon,
1763 	&bufdaemonproc
1764 };
1765 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1766 
1767 static void
1768 buf_daemon()
1769 {
1770 	int s;
1771 
1772 	mtx_enter(&Giant, MTX_DEF);
1773 
1774 	/*
1775 	 * This process needs to be suspended prior to shutdown sync.
1776 	 */
1777 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, bufdaemonproc,
1778 	    SHUTDOWN_PRI_LAST);
1779 
1780 	/*
1781 	 * This process is allowed to take the buffer cache to the limit
1782 	 */
1783 	curproc->p_flag |= P_BUFEXHAUST;
1784 	s = splbio();
1785 
1786 	bd_interval = 5 * hz;	/* dynamically adjusted */
1787 	bd_flushto = hidirtybuffers;	/* dynamically adjusted */
1788 	bd_flushinc = 1;
1789 
1790 	for (;;) {
1791 		kproc_suspend_loop(bufdaemonproc);
1792 
1793 		bd_request = 0;
1794 
1795 		/*
1796 		 * Do the flush.  Limit the number of buffers we flush in one
1797 		 * go.  The failure condition occurs when processes are writing
1798 		 * buffers faster then we can dispose of them.  In this case
1799 		 * we may be flushing so often that the previous set of flushes
1800 		 * have not had time to complete, causing us to run out of
1801 		 * physical buffers and block.
1802 		 */
1803 		{
1804 			int runcount = maxbdrun;
1805 
1806 			while (numdirtybuffers > bd_flushto && runcount) {
1807 				--runcount;
1808 				if (flushbufqueues() == 0)
1809 					break;
1810 			}
1811 		}
1812 
1813 		if (bd_request ||
1814 		    tsleep(&bd_request, PVM, "psleep", bd_interval) == 0) {
1815 			/*
1816 			 * Another request is pending or we were woken up
1817 			 * without timing out.  Flush more.
1818 			 */
1819 			--bd_flushto;
1820 			if (bd_flushto >= numdirtybuffers - 5) {
1821 				bd_flushto = numdirtybuffers - 10;
1822 				bd_flushinc = 1;
1823 			}
1824 			if (bd_flushto < 2)
1825 				bd_flushto = 2;
1826 		} else {
1827 			/*
1828 			 * We slept and timed out, we can slow down.
1829 			 */
1830 			bd_flushto += bd_flushinc;
1831 			if (bd_flushto > hidirtybuffers)
1832 				bd_flushto = hidirtybuffers;
1833 			++bd_flushinc;
1834 			if (bd_flushinc > hidirtybuffers / 20 + 1)
1835 				bd_flushinc = hidirtybuffers / 20 + 1;
1836 		}
1837 
1838 		/*
1839 		 * Set the interval on a linear scale based on hidirtybuffers
1840 		 * with a maximum frequency of 1/10 second.
1841 		 */
1842 		bd_interval = bd_flushto * 5 * hz / hidirtybuffers;
1843 		if (bd_interval < hz / 10)
1844 			bd_interval = hz / 10;
1845 	}
1846 }
1847 
1848 /*
1849  *	flushbufqueues:
1850  *
1851  *	Try to flush a buffer in the dirty queue.  We must be careful to
1852  *	free up B_INVAL buffers instead of write them, which NFS is
1853  *	particularly sensitive to.
1854  */
1855 
1856 static int
1857 flushbufqueues(void)
1858 {
1859 	struct buf *bp;
1860 	int r = 0;
1861 
1862 	bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1863 
1864 	while (bp) {
1865 		KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1866 		if ((bp->b_flags & B_DELWRI) != 0 &&
1867 		    (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1868 			if (bp->b_flags & B_INVAL) {
1869 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1870 					panic("flushbufqueues: locked buf");
1871 				bremfree(bp);
1872 				brelse(bp);
1873 				++r;
1874 				break;
1875 			}
1876 			if (LIST_FIRST(&bp->b_dep) != NULL &&
1877 			    (bp->b_flags & B_DEFERRED) == 0 &&
1878 			    buf_countdeps(bp, 0)) {
1879 				TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
1880 				    bp, b_freelist);
1881 				TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
1882 				    bp, b_freelist);
1883 				bp->b_flags |= B_DEFERRED;
1884 				bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1885 				continue;
1886 			}
1887 			vfs_bio_awrite(bp);
1888 			++r;
1889 			break;
1890 		}
1891 		bp = TAILQ_NEXT(bp, b_freelist);
1892 	}
1893 	return (r);
1894 }
1895 
1896 /*
1897  * Check to see if a block is currently memory resident.
1898  */
1899 struct buf *
1900 incore(struct vnode * vp, daddr_t blkno)
1901 {
1902 	struct buf *bp;
1903 
1904 	int s = splbio();
1905 	bp = gbincore(vp, blkno);
1906 	splx(s);
1907 	return (bp);
1908 }
1909 
1910 /*
1911  * Returns true if no I/O is needed to access the
1912  * associated VM object.  This is like incore except
1913  * it also hunts around in the VM system for the data.
1914  */
1915 
1916 int
1917 inmem(struct vnode * vp, daddr_t blkno)
1918 {
1919 	vm_object_t obj;
1920 	vm_offset_t toff, tinc, size;
1921 	vm_page_t m;
1922 	vm_ooffset_t off;
1923 
1924 	if (incore(vp, blkno))
1925 		return 1;
1926 	if (vp->v_mount == NULL)
1927 		return 0;
1928 	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
1929 		return 0;
1930 
1931 	size = PAGE_SIZE;
1932 	if (size > vp->v_mount->mnt_stat.f_iosize)
1933 		size = vp->v_mount->mnt_stat.f_iosize;
1934 	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
1935 
1936 	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1937 		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1938 		if (!m)
1939 			return 0;
1940 		tinc = size;
1941 		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
1942 			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
1943 		if (vm_page_is_valid(m,
1944 		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
1945 			return 0;
1946 	}
1947 	return 1;
1948 }
1949 
1950 /*
1951  *	vfs_setdirty:
1952  *
1953  *	Sets the dirty range for a buffer based on the status of the dirty
1954  *	bits in the pages comprising the buffer.
1955  *
1956  *	The range is limited to the size of the buffer.
1957  *
1958  *	This routine is primarily used by NFS, but is generalized for the
1959  *	B_VMIO case.
1960  */
1961 static void
1962 vfs_setdirty(struct buf *bp)
1963 {
1964 	int i;
1965 	vm_object_t object;
1966 
1967 	/*
1968 	 * Degenerate case - empty buffer
1969 	 */
1970 
1971 	if (bp->b_bufsize == 0)
1972 		return;
1973 
1974 	/*
1975 	 * We qualify the scan for modified pages on whether the
1976 	 * object has been flushed yet.  The OBJ_WRITEABLE flag
1977 	 * is not cleared simply by protecting pages off.
1978 	 */
1979 
1980 	if ((bp->b_flags & B_VMIO) == 0)
1981 		return;
1982 
1983 	object = bp->b_pages[0]->object;
1984 
1985 	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
1986 		printf("Warning: object %p writeable but not mightbedirty\n", object);
1987 	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
1988 		printf("Warning: object %p mightbedirty but not writeable\n", object);
1989 
1990 	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
1991 		vm_offset_t boffset;
1992 		vm_offset_t eoffset;
1993 
1994 		/*
1995 		 * test the pages to see if they have been modified directly
1996 		 * by users through the VM system.
1997 		 */
1998 		for (i = 0; i < bp->b_npages; i++) {
1999 			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
2000 			vm_page_test_dirty(bp->b_pages[i]);
2001 		}
2002 
2003 		/*
2004 		 * Calculate the encompassing dirty range, boffset and eoffset,
2005 		 * (eoffset - boffset) bytes.
2006 		 */
2007 
2008 		for (i = 0; i < bp->b_npages; i++) {
2009 			if (bp->b_pages[i]->dirty)
2010 				break;
2011 		}
2012 		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2013 
2014 		for (i = bp->b_npages - 1; i >= 0; --i) {
2015 			if (bp->b_pages[i]->dirty) {
2016 				break;
2017 			}
2018 		}
2019 		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2020 
2021 		/*
2022 		 * Fit it to the buffer.
2023 		 */
2024 
2025 		if (eoffset > bp->b_bcount)
2026 			eoffset = bp->b_bcount;
2027 
2028 		/*
2029 		 * If we have a good dirty range, merge with the existing
2030 		 * dirty range.
2031 		 */
2032 
2033 		if (boffset < eoffset) {
2034 			if (bp->b_dirtyoff > boffset)
2035 				bp->b_dirtyoff = boffset;
2036 			if (bp->b_dirtyend < eoffset)
2037 				bp->b_dirtyend = eoffset;
2038 		}
2039 	}
2040 }
2041 
2042 /*
2043  *	getblk:
2044  *
2045  *	Get a block given a specified block and offset into a file/device.
2046  *	The buffers B_DONE bit will be cleared on return, making it almost
2047  * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2048  *	return.  The caller should clear B_INVAL prior to initiating a
2049  *	READ.
2050  *
2051  *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2052  *	an existing buffer.
2053  *
2054  *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2055  *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2056  *	and then cleared based on the backing VM.  If the previous buffer is
2057  *	non-0-sized but invalid, B_CACHE will be cleared.
2058  *
2059  *	If getblk() must create a new buffer, the new buffer is returned with
2060  *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2061  *	case it is returned with B_INVAL clear and B_CACHE set based on the
2062  *	backing VM.
2063  *
2064  *	getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2065  *	B_CACHE bit is clear.
2066  *
2067  *	What this means, basically, is that the caller should use B_CACHE to
2068  *	determine whether the buffer is fully valid or not and should clear
2069  *	B_INVAL prior to issuing a read.  If the caller intends to validate
2070  *	the buffer by loading its data area with something, the caller needs
2071  *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2072  *	the caller should set B_CACHE ( as an optimization ), else the caller
2073  *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2074  *	a write attempt or if it was a successfull read.  If the caller
2075  *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2076  *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2077  */
2078 struct buf *
2079 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2080 {
2081 	struct buf *bp;
2082 	int s;
2083 	struct bufhashhdr *bh;
2084 
2085 	if (size > MAXBSIZE)
2086 		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2087 
2088 	s = splbio();
2089 loop:
2090 	/*
2091 	 * Block if we are low on buffers.   Certain processes are allowed
2092 	 * to completely exhaust the buffer cache.
2093          *
2094          * If this check ever becomes a bottleneck it may be better to
2095          * move it into the else, when gbincore() fails.  At the moment
2096          * it isn't a problem.
2097 	 *
2098 	 * XXX remove if 0 sections (clean this up after its proven)
2099          */
2100 #if 0
2101 	if (curproc == idleproc || (curproc->p_flag & P_BUFEXHAUST)) {
2102 #endif
2103 		if (numfreebuffers == 0) {
2104 			if (curproc == idleproc)
2105 				return NULL;
2106 			needsbuffer |= VFS_BIO_NEED_ANY;
2107 			tsleep(&needsbuffer, (PRIBIO + 4) | slpflag, "newbuf",
2108 			    slptimeo);
2109 		}
2110 #if 0
2111 	} else if (numfreebuffers < lofreebuffers) {
2112 		waitfreebuffers(slpflag, slptimeo);
2113 	}
2114 #endif
2115 
2116 	if ((bp = gbincore(vp, blkno))) {
2117 		/*
2118 		 * Buffer is in-core.  If the buffer is not busy, it must
2119 		 * be on a queue.
2120 		 */
2121 
2122 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2123 			if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2124 			    "getblk", slpflag, slptimeo) == ENOLCK)
2125 				goto loop;
2126 			splx(s);
2127 			return (struct buf *) NULL;
2128 		}
2129 
2130 		/*
2131 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2132 		 * invalid.  Ohterwise, for a non-VMIO buffer, B_CACHE is set
2133 		 * and for a VMIO buffer B_CACHE is adjusted according to the
2134 		 * backing VM cache.
2135 		 */
2136 		if (bp->b_flags & B_INVAL)
2137 			bp->b_flags &= ~B_CACHE;
2138 		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2139 			bp->b_flags |= B_CACHE;
2140 		bremfree(bp);
2141 
2142 		/*
2143 		 * check for size inconsistancies for non-VMIO case.
2144 		 */
2145 
2146 		if (bp->b_bcount != size) {
2147 			if ((bp->b_flags & B_VMIO) == 0 ||
2148 			    (size > bp->b_kvasize)) {
2149 				if (bp->b_flags & B_DELWRI) {
2150 					bp->b_flags |= B_NOCACHE;
2151 					BUF_WRITE(bp);
2152 				} else {
2153 					if ((bp->b_flags & B_VMIO) &&
2154 					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2155 						bp->b_flags |= B_RELBUF;
2156 						brelse(bp);
2157 					} else {
2158 						bp->b_flags |= B_NOCACHE;
2159 						BUF_WRITE(bp);
2160 					}
2161 				}
2162 				goto loop;
2163 			}
2164 		}
2165 
2166 		/*
2167 		 * If the size is inconsistant in the VMIO case, we can resize
2168 		 * the buffer.  This might lead to B_CACHE getting set or
2169 		 * cleared.  If the size has not changed, B_CACHE remains
2170 		 * unchanged from its previous state.
2171 		 */
2172 
2173 		if (bp->b_bcount != size)
2174 			allocbuf(bp, size);
2175 
2176 		KASSERT(bp->b_offset != NOOFFSET,
2177 		    ("getblk: no buffer offset"));
2178 
2179 		/*
2180 		 * A buffer with B_DELWRI set and B_CACHE clear must
2181 		 * be committed before we can return the buffer in
2182 		 * order to prevent the caller from issuing a read
2183 		 * ( due to B_CACHE not being set ) and overwriting
2184 		 * it.
2185 		 *
2186 		 * Most callers, including NFS and FFS, need this to
2187 		 * operate properly either because they assume they
2188 		 * can issue a read if B_CACHE is not set, or because
2189 		 * ( for example ) an uncached B_DELWRI might loop due
2190 		 * to softupdates re-dirtying the buffer.  In the latter
2191 		 * case, B_CACHE is set after the first write completes,
2192 		 * preventing further loops.
2193 		 */
2194 
2195 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2196 			BUF_WRITE(bp);
2197 			goto loop;
2198 		}
2199 
2200 		splx(s);
2201 		bp->b_flags &= ~B_DONE;
2202 	} else {
2203 		/*
2204 		 * Buffer is not in-core, create new buffer.  The buffer
2205 		 * returned by getnewbuf() is locked.  Note that the returned
2206 		 * buffer is also considered valid (not marked B_INVAL).
2207 		 */
2208 		int bsize, maxsize, vmio;
2209 		off_t offset;
2210 
2211 		if (vn_isdisk(vp, NULL))
2212 			bsize = DEV_BSIZE;
2213 		else if (vp->v_mountedhere)
2214 			bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2215 		else if (vp->v_mount)
2216 			bsize = vp->v_mount->mnt_stat.f_iosize;
2217 		else
2218 			bsize = size;
2219 
2220 		offset = (off_t)blkno * bsize;
2221 		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2222 		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2223 		maxsize = imax(maxsize, bsize);
2224 
2225 		if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2226 			if (slpflag || slptimeo) {
2227 				splx(s);
2228 				return NULL;
2229 			}
2230 			goto loop;
2231 		}
2232 
2233 		/*
2234 		 * This code is used to make sure that a buffer is not
2235 		 * created while the getnewbuf routine is blocked.
2236 		 * This can be a problem whether the vnode is locked or not.
2237 		 * If the buffer is created out from under us, we have to
2238 		 * throw away the one we just created.  There is now window
2239 		 * race because we are safely running at splbio() from the
2240 		 * point of the duplicate buffer creation through to here,
2241 		 * and we've locked the buffer.
2242 		 */
2243 		if (gbincore(vp, blkno)) {
2244 			bp->b_flags |= B_INVAL;
2245 			brelse(bp);
2246 			goto loop;
2247 		}
2248 
2249 		/*
2250 		 * Insert the buffer into the hash, so that it can
2251 		 * be found by incore.
2252 		 */
2253 		bp->b_blkno = bp->b_lblkno = blkno;
2254 		bp->b_offset = offset;
2255 
2256 		bgetvp(vp, bp);
2257 		LIST_REMOVE(bp, b_hash);
2258 		bh = bufhash(vp, blkno);
2259 		LIST_INSERT_HEAD(bh, bp, b_hash);
2260 
2261 		/*
2262 		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2263 		 * buffer size starts out as 0, B_CACHE will be set by
2264 		 * allocbuf() for the VMIO case prior to it testing the
2265 		 * backing store for validity.
2266 		 */
2267 
2268 		if (vmio) {
2269 			bp->b_flags |= B_VMIO;
2270 #if defined(VFS_BIO_DEBUG)
2271 			if (vp->v_type != VREG)
2272 				printf("getblk: vmioing file type %d???\n", vp->v_type);
2273 #endif
2274 		} else {
2275 			bp->b_flags &= ~B_VMIO;
2276 		}
2277 
2278 		allocbuf(bp, size);
2279 
2280 		splx(s);
2281 		bp->b_flags &= ~B_DONE;
2282 	}
2283 	return (bp);
2284 }
2285 
2286 /*
2287  * Get an empty, disassociated buffer of given size.  The buffer is initially
2288  * set to B_INVAL.
2289  */
2290 struct buf *
2291 geteblk(int size)
2292 {
2293 	struct buf *bp;
2294 	int s;
2295 	int maxsize;
2296 
2297 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2298 
2299 	s = splbio();
2300 	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2301 	splx(s);
2302 	allocbuf(bp, size);
2303 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2304 	return (bp);
2305 }
2306 
2307 
2308 /*
2309  * This code constitutes the buffer memory from either anonymous system
2310  * memory (in the case of non-VMIO operations) or from an associated
2311  * VM object (in the case of VMIO operations).  This code is able to
2312  * resize a buffer up or down.
2313  *
2314  * Note that this code is tricky, and has many complications to resolve
2315  * deadlock or inconsistant data situations.  Tread lightly!!!
2316  * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2317  * the caller.  Calling this code willy nilly can result in the loss of data.
2318  *
2319  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2320  * B_CACHE for the non-VMIO case.
2321  */
2322 
2323 int
2324 allocbuf(struct buf *bp, int size)
2325 {
2326 	int newbsize, mbsize;
2327 	int i;
2328 
2329 	if (BUF_REFCNT(bp) == 0)
2330 		panic("allocbuf: buffer not busy");
2331 
2332 	if (bp->b_kvasize < size)
2333 		panic("allocbuf: buffer too small");
2334 
2335 	if ((bp->b_flags & B_VMIO) == 0) {
2336 		caddr_t origbuf;
2337 		int origbufsize;
2338 		/*
2339 		 * Just get anonymous memory from the kernel.  Don't
2340 		 * mess with B_CACHE.
2341 		 */
2342 		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2343 #if !defined(NO_B_MALLOC)
2344 		if (bp->b_flags & B_MALLOC)
2345 			newbsize = mbsize;
2346 		else
2347 #endif
2348 			newbsize = round_page(size);
2349 
2350 		if (newbsize < bp->b_bufsize) {
2351 #if !defined(NO_B_MALLOC)
2352 			/*
2353 			 * malloced buffers are not shrunk
2354 			 */
2355 			if (bp->b_flags & B_MALLOC) {
2356 				if (newbsize) {
2357 					bp->b_bcount = size;
2358 				} else {
2359 					free(bp->b_data, M_BIOBUF);
2360 					bufmallocspace -= bp->b_bufsize;
2361 					runningbufspace -= bp->b_bufsize;
2362 					if (bp->b_bufsize)
2363 						bufspacewakeup();
2364 					bp->b_data = bp->b_kvabase;
2365 					bp->b_bufsize = 0;
2366 					bp->b_bcount = 0;
2367 					bp->b_flags &= ~B_MALLOC;
2368 				}
2369 				return 1;
2370 			}
2371 #endif
2372 			vm_hold_free_pages(
2373 			    bp,
2374 			    (vm_offset_t) bp->b_data + newbsize,
2375 			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2376 		} else if (newbsize > bp->b_bufsize) {
2377 #if !defined(NO_B_MALLOC)
2378 			/*
2379 			 * We only use malloced memory on the first allocation.
2380 			 * and revert to page-allocated memory when the buffer
2381 			 * grows.
2382 			 */
2383 			if ( (bufmallocspace < maxbufmallocspace) &&
2384 				(bp->b_bufsize == 0) &&
2385 				(mbsize <= PAGE_SIZE/2)) {
2386 
2387 				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2388 				bp->b_bufsize = mbsize;
2389 				bp->b_bcount = size;
2390 				bp->b_flags |= B_MALLOC;
2391 				bufmallocspace += mbsize;
2392 				runningbufspace += bp->b_bufsize;
2393 				return 1;
2394 			}
2395 #endif
2396 			origbuf = NULL;
2397 			origbufsize = 0;
2398 #if !defined(NO_B_MALLOC)
2399 			/*
2400 			 * If the buffer is growing on its other-than-first allocation,
2401 			 * then we revert to the page-allocation scheme.
2402 			 */
2403 			if (bp->b_flags & B_MALLOC) {
2404 				origbuf = bp->b_data;
2405 				origbufsize = bp->b_bufsize;
2406 				bp->b_data = bp->b_kvabase;
2407 				bufmallocspace -= bp->b_bufsize;
2408 				runningbufspace -= bp->b_bufsize;
2409 				if (bp->b_bufsize)
2410 					bufspacewakeup();
2411 				bp->b_bufsize = 0;
2412 				bp->b_flags &= ~B_MALLOC;
2413 				newbsize = round_page(newbsize);
2414 			}
2415 #endif
2416 			vm_hold_load_pages(
2417 			    bp,
2418 			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2419 			    (vm_offset_t) bp->b_data + newbsize);
2420 #if !defined(NO_B_MALLOC)
2421 			if (origbuf) {
2422 				bcopy(origbuf, bp->b_data, origbufsize);
2423 				free(origbuf, M_BIOBUF);
2424 			}
2425 #endif
2426 		}
2427 	} else {
2428 		vm_page_t m;
2429 		int desiredpages;
2430 
2431 		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2432 		desiredpages = (size == 0) ? 0 :
2433 			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2434 
2435 #if !defined(NO_B_MALLOC)
2436 		if (bp->b_flags & B_MALLOC)
2437 			panic("allocbuf: VMIO buffer can't be malloced");
2438 #endif
2439 		/*
2440 		 * Set B_CACHE initially if buffer is 0 length or will become
2441 		 * 0-length.
2442 		 */
2443 		if (size == 0 || bp->b_bufsize == 0)
2444 			bp->b_flags |= B_CACHE;
2445 
2446 		if (newbsize < bp->b_bufsize) {
2447 			/*
2448 			 * DEV_BSIZE aligned new buffer size is less then the
2449 			 * DEV_BSIZE aligned existing buffer size.  Figure out
2450 			 * if we have to remove any pages.
2451 			 */
2452 			if (desiredpages < bp->b_npages) {
2453 				for (i = desiredpages; i < bp->b_npages; i++) {
2454 					/*
2455 					 * the page is not freed here -- it
2456 					 * is the responsibility of
2457 					 * vnode_pager_setsize
2458 					 */
2459 					m = bp->b_pages[i];
2460 					KASSERT(m != bogus_page,
2461 					    ("allocbuf: bogus page found"));
2462 					while (vm_page_sleep_busy(m, TRUE, "biodep"))
2463 						;
2464 
2465 					bp->b_pages[i] = NULL;
2466 					vm_page_unwire(m, 0);
2467 				}
2468 				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2469 				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2470 				bp->b_npages = desiredpages;
2471 			}
2472 		} else if (size > bp->b_bcount) {
2473 			/*
2474 			 * We are growing the buffer, possibly in a
2475 			 * byte-granular fashion.
2476 			 */
2477 			struct vnode *vp;
2478 			vm_object_t obj;
2479 			vm_offset_t toff;
2480 			vm_offset_t tinc;
2481 
2482 			/*
2483 			 * Step 1, bring in the VM pages from the object,
2484 			 * allocating them if necessary.  We must clear
2485 			 * B_CACHE if these pages are not valid for the
2486 			 * range covered by the buffer.
2487 			 */
2488 
2489 			vp = bp->b_vp;
2490 			VOP_GETVOBJECT(vp, &obj);
2491 
2492 			while (bp->b_npages < desiredpages) {
2493 				vm_page_t m;
2494 				vm_pindex_t pi;
2495 
2496 				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2497 				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2498 					/*
2499 					 * note: must allocate system pages
2500 					 * since blocking here could intefere
2501 					 * with paging I/O, no matter which
2502 					 * process we are.
2503 					 */
2504 					m = vm_page_alloc(obj, pi, VM_ALLOC_SYSTEM);
2505 					if (m == NULL) {
2506 						VM_WAIT;
2507 						vm_pageout_deficit += desiredpages - bp->b_npages;
2508 					} else {
2509 						vm_page_wire(m);
2510 						vm_page_wakeup(m);
2511 						bp->b_flags &= ~B_CACHE;
2512 						bp->b_pages[bp->b_npages] = m;
2513 						++bp->b_npages;
2514 					}
2515 					continue;
2516 				}
2517 
2518 				/*
2519 				 * We found a page.  If we have to sleep on it,
2520 				 * retry because it might have gotten freed out
2521 				 * from under us.
2522 				 *
2523 				 * We can only test PG_BUSY here.  Blocking on
2524 				 * m->busy might lead to a deadlock:
2525 				 *
2526 				 *  vm_fault->getpages->cluster_read->allocbuf
2527 				 *
2528 				 */
2529 
2530 				if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2531 					continue;
2532 
2533 				/*
2534 				 * We have a good page.  Should we wakeup the
2535 				 * page daemon?
2536 				 */
2537 				if ((curproc != pageproc) &&
2538 				    ((m->queue - m->pc) == PQ_CACHE) &&
2539 				    ((cnt.v_free_count + cnt.v_cache_count) <
2540 					(cnt.v_free_min + cnt.v_cache_min))) {
2541 					pagedaemon_wakeup();
2542 				}
2543 				vm_page_flag_clear(m, PG_ZERO);
2544 				vm_page_wire(m);
2545 				bp->b_pages[bp->b_npages] = m;
2546 				++bp->b_npages;
2547 			}
2548 
2549 			/*
2550 			 * Step 2.  We've loaded the pages into the buffer,
2551 			 * we have to figure out if we can still have B_CACHE
2552 			 * set.  Note that B_CACHE is set according to the
2553 			 * byte-granular range ( bcount and size ), new the
2554 			 * aligned range ( newbsize ).
2555 			 *
2556 			 * The VM test is against m->valid, which is DEV_BSIZE
2557 			 * aligned.  Needless to say, the validity of the data
2558 			 * needs to also be DEV_BSIZE aligned.  Note that this
2559 			 * fails with NFS if the server or some other client
2560 			 * extends the file's EOF.  If our buffer is resized,
2561 			 * B_CACHE may remain set! XXX
2562 			 */
2563 
2564 			toff = bp->b_bcount;
2565 			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2566 
2567 			while ((bp->b_flags & B_CACHE) && toff < size) {
2568 				vm_pindex_t pi;
2569 
2570 				if (tinc > (size - toff))
2571 					tinc = size - toff;
2572 
2573 				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2574 				    PAGE_SHIFT;
2575 
2576 				vfs_buf_test_cache(
2577 				    bp,
2578 				    bp->b_offset,
2579 				    toff,
2580 				    tinc,
2581 				    bp->b_pages[pi]
2582 				);
2583 				toff += tinc;
2584 				tinc = PAGE_SIZE;
2585 			}
2586 
2587 			/*
2588 			 * Step 3, fixup the KVM pmap.  Remember that
2589 			 * bp->b_data is relative to bp->b_offset, but
2590 			 * bp->b_offset may be offset into the first page.
2591 			 */
2592 
2593 			bp->b_data = (caddr_t)
2594 			    trunc_page((vm_offset_t)bp->b_data);
2595 			pmap_qenter(
2596 			    (vm_offset_t)bp->b_data,
2597 			    bp->b_pages,
2598 			    bp->b_npages
2599 			);
2600 			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2601 			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2602 		}
2603 	}
2604 	runningbufspace += (newbsize - bp->b_bufsize);
2605 	if (newbsize < bp->b_bufsize)
2606 		bufspacewakeup();
2607 	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2608 	bp->b_bcount = size;		/* requested buffer size	*/
2609 	return 1;
2610 }
2611 
2612 /*
2613  *	bufwait:
2614  *
2615  *	Wait for buffer I/O completion, returning error status.  The buffer
2616  *	is left locked and B_DONE on return.  B_EINTR is converted into a EINTR
2617  *	error and cleared.
2618  */
2619 int
2620 bufwait(register struct buf * bp)
2621 {
2622 	int s;
2623 
2624 	s = splbio();
2625 	while ((bp->b_flags & B_DONE) == 0) {
2626 		if (bp->b_iocmd == BIO_READ)
2627 			tsleep(bp, PRIBIO, "biord", 0);
2628 		else
2629 			tsleep(bp, PRIBIO, "biowr", 0);
2630 	}
2631 	splx(s);
2632 	if (bp->b_flags & B_EINTR) {
2633 		bp->b_flags &= ~B_EINTR;
2634 		return (EINTR);
2635 	}
2636 	if (bp->b_ioflags & BIO_ERROR) {
2637 		return (bp->b_error ? bp->b_error : EIO);
2638 	} else {
2639 		return (0);
2640 	}
2641 }
2642 
2643  /*
2644   * Call back function from struct bio back up to struct buf.
2645   * The corresponding initialization lives in sys/conf.h:DEV_STRATEGY().
2646   */
2647 void
2648 bufdonebio(struct bio *bp)
2649 {
2650 	bufdone(bp->bio_caller2);
2651 }
2652 
2653 /*
2654  *	bufdone:
2655  *
2656  *	Finish I/O on a buffer, optionally calling a completion function.
2657  *	This is usually called from an interrupt so process blocking is
2658  *	not allowed.
2659  *
2660  *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2661  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
2662  *	assuming B_INVAL is clear.
2663  *
2664  *	For the VMIO case, we set B_CACHE if the op was a read and no
2665  *	read error occured, or if the op was a write.  B_CACHE is never
2666  *	set if the buffer is invalid or otherwise uncacheable.
2667  *
2668  *	biodone does not mess with B_INVAL, allowing the I/O routine or the
2669  *	initiator to leave B_INVAL set to brelse the buffer out of existance
2670  *	in the biodone routine.
2671  */
2672 void
2673 bufdone(struct buf *bp)
2674 {
2675 	int s, error;
2676 	void    (*biodone) __P((struct buf *));
2677 
2678 	s = splbio();
2679 
2680 	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2681 	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2682 
2683 	bp->b_flags |= B_DONE;
2684 
2685 	if (bp->b_iocmd == BIO_DELETE) {
2686 		brelse(bp);
2687 		splx(s);
2688 		return;
2689 	}
2690 
2691 	if (bp->b_iocmd == BIO_WRITE) {
2692 		vwakeup(bp);
2693 	}
2694 
2695 	/* call optional completion function if requested */
2696 	if (bp->b_iodone != NULL) {
2697 		biodone = bp->b_iodone;
2698 		bp->b_iodone = NULL;
2699 		(*biodone) (bp);
2700 		splx(s);
2701 		return;
2702 	}
2703 	if (LIST_FIRST(&bp->b_dep) != NULL)
2704 		buf_complete(bp);
2705 
2706 	if (bp->b_flags & B_VMIO) {
2707 		int i;
2708 		vm_ooffset_t foff;
2709 		vm_page_t m;
2710 		vm_object_t obj;
2711 		int iosize;
2712 		struct vnode *vp = bp->b_vp;
2713 
2714 		error = VOP_GETVOBJECT(vp, &obj);
2715 
2716 #if defined(VFS_BIO_DEBUG)
2717 		if (vp->v_usecount == 0) {
2718 			panic("biodone: zero vnode ref count");
2719 		}
2720 
2721 		if (error) {
2722 			panic("biodone: missing VM object");
2723 		}
2724 
2725 		if ((vp->v_flag & VOBJBUF) == 0) {
2726 			panic("biodone: vnode is not setup for merged cache");
2727 		}
2728 #endif
2729 
2730 		foff = bp->b_offset;
2731 		KASSERT(bp->b_offset != NOOFFSET,
2732 		    ("biodone: no buffer offset"));
2733 
2734 		if (error) {
2735 			panic("biodone: no object");
2736 		}
2737 #if defined(VFS_BIO_DEBUG)
2738 		if (obj->paging_in_progress < bp->b_npages) {
2739 			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2740 			    obj->paging_in_progress, bp->b_npages);
2741 		}
2742 #endif
2743 
2744 		/*
2745 		 * Set B_CACHE if the op was a normal read and no error
2746 		 * occured.  B_CACHE is set for writes in the b*write()
2747 		 * routines.
2748 		 */
2749 		iosize = bp->b_bcount - bp->b_resid;
2750 		if (bp->b_iocmd == BIO_READ &&
2751 		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
2752 		    !(bp->b_ioflags & BIO_ERROR)) {
2753 			bp->b_flags |= B_CACHE;
2754 		}
2755 
2756 		for (i = 0; i < bp->b_npages; i++) {
2757 			int bogusflag = 0;
2758 			int resid;
2759 
2760 			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2761 			if (resid > iosize)
2762 				resid = iosize;
2763 
2764 			/*
2765 			 * cleanup bogus pages, restoring the originals
2766 			 */
2767 			m = bp->b_pages[i];
2768 			if (m == bogus_page) {
2769 				bogusflag = 1;
2770 				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2771 				if (!m) {
2772 					panic("biodone: page disappeared!");
2773 #if defined(VFS_BIO_DEBUG)
2774 					printf("biodone: page disappeared\n");
2775 #endif
2776 					vm_object_pip_subtract(obj, 1);
2777 					bp->b_flags &= ~B_CACHE;
2778 					foff = (foff + PAGE_SIZE) &
2779 					    ~(off_t)PAGE_MASK;
2780 					iosize -= resid;
2781 					continue;
2782 				}
2783 				bp->b_pages[i] = m;
2784 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2785 			}
2786 #if defined(VFS_BIO_DEBUG)
2787 			if (OFF_TO_IDX(foff) != m->pindex) {
2788 				printf(
2789 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2790 				    (unsigned long)foff, m->pindex);
2791 			}
2792 #endif
2793 
2794 			/*
2795 			 * In the write case, the valid and clean bits are
2796 			 * already changed correctly ( see bdwrite() ), so we
2797 			 * only need to do this here in the read case.
2798 			 */
2799 			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
2800 				vfs_page_set_valid(bp, foff, i, m);
2801 			}
2802 			vm_page_flag_clear(m, PG_ZERO);
2803 
2804 			/*
2805 			 * when debugging new filesystems or buffer I/O methods, this
2806 			 * is the most common error that pops up.  if you see this, you
2807 			 * have not set the page busy flag correctly!!!
2808 			 */
2809 			if (m->busy == 0) {
2810 				printf("biodone: page busy < 0, "
2811 				    "pindex: %d, foff: 0x(%x,%x), "
2812 				    "resid: %d, index: %d\n",
2813 				    (int) m->pindex, (int)(foff >> 32),
2814 						(int) foff & 0xffffffff, resid, i);
2815 				if (!vn_isdisk(vp, NULL))
2816 					printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2817 					    bp->b_vp->v_mount->mnt_stat.f_iosize,
2818 					    (int) bp->b_lblkno,
2819 					    bp->b_flags, bp->b_npages);
2820 				else
2821 					printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2822 					    (int) bp->b_lblkno,
2823 					    bp->b_flags, bp->b_npages);
2824 				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2825 				    m->valid, m->dirty, m->wire_count);
2826 				panic("biodone: page busy < 0\n");
2827 			}
2828 			vm_page_io_finish(m);
2829 			vm_object_pip_subtract(obj, 1);
2830 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2831 			iosize -= resid;
2832 		}
2833 		if (obj)
2834 			vm_object_pip_wakeupn(obj, 0);
2835 	}
2836 	/*
2837 	 * For asynchronous completions, release the buffer now. The brelse
2838 	 * will do a wakeup there if necessary - so no need to do a wakeup
2839 	 * here in the async case. The sync case always needs to do a wakeup.
2840 	 */
2841 
2842 	if (bp->b_flags & B_ASYNC) {
2843 		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
2844 			brelse(bp);
2845 		else
2846 			bqrelse(bp);
2847 	} else {
2848 		wakeup(bp);
2849 	}
2850 	splx(s);
2851 }
2852 
2853 /*
2854  * This routine is called in lieu of iodone in the case of
2855  * incomplete I/O.  This keeps the busy status for pages
2856  * consistant.
2857  */
2858 void
2859 vfs_unbusy_pages(struct buf * bp)
2860 {
2861 	int i;
2862 
2863 	if (bp->b_flags & B_VMIO) {
2864 		struct vnode *vp = bp->b_vp;
2865 		vm_object_t obj;
2866 
2867 		VOP_GETVOBJECT(vp, &obj);
2868 
2869 		for (i = 0; i < bp->b_npages; i++) {
2870 			vm_page_t m = bp->b_pages[i];
2871 
2872 			if (m == bogus_page) {
2873 				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2874 				if (!m) {
2875 					panic("vfs_unbusy_pages: page missing\n");
2876 				}
2877 				bp->b_pages[i] = m;
2878 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2879 			}
2880 			vm_object_pip_subtract(obj, 1);
2881 			vm_page_flag_clear(m, PG_ZERO);
2882 			vm_page_io_finish(m);
2883 		}
2884 		vm_object_pip_wakeupn(obj, 0);
2885 	}
2886 }
2887 
2888 /*
2889  * vfs_page_set_valid:
2890  *
2891  *	Set the valid bits in a page based on the supplied offset.   The
2892  *	range is restricted to the buffer's size.
2893  *
2894  *	This routine is typically called after a read completes.
2895  */
2896 static void
2897 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2898 {
2899 	vm_ooffset_t soff, eoff;
2900 
2901 	/*
2902 	 * Start and end offsets in buffer.  eoff - soff may not cross a
2903 	 * page boundry or cross the end of the buffer.  The end of the
2904 	 * buffer, in this case, is our file EOF, not the allocation size
2905 	 * of the buffer.
2906 	 */
2907 	soff = off;
2908 	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2909 	if (eoff > bp->b_offset + bp->b_bcount)
2910 		eoff = bp->b_offset + bp->b_bcount;
2911 
2912 	/*
2913 	 * Set valid range.  This is typically the entire buffer and thus the
2914 	 * entire page.
2915 	 */
2916 	if (eoff > soff) {
2917 		vm_page_set_validclean(
2918 		    m,
2919 		   (vm_offset_t) (soff & PAGE_MASK),
2920 		   (vm_offset_t) (eoff - soff)
2921 		);
2922 	}
2923 }
2924 
2925 /*
2926  * This routine is called before a device strategy routine.
2927  * It is used to tell the VM system that paging I/O is in
2928  * progress, and treat the pages associated with the buffer
2929  * almost as being PG_BUSY.  Also the object paging_in_progress
2930  * flag is handled to make sure that the object doesn't become
2931  * inconsistant.
2932  *
2933  * Since I/O has not been initiated yet, certain buffer flags
2934  * such as BIO_ERROR or B_INVAL may be in an inconsistant state
2935  * and should be ignored.
2936  */
2937 void
2938 vfs_busy_pages(struct buf * bp, int clear_modify)
2939 {
2940 	int i, bogus;
2941 
2942 	if (bp->b_flags & B_VMIO) {
2943 		struct vnode *vp = bp->b_vp;
2944 		vm_object_t obj;
2945 		vm_ooffset_t foff;
2946 
2947 		VOP_GETVOBJECT(vp, &obj);
2948 		foff = bp->b_offset;
2949 		KASSERT(bp->b_offset != NOOFFSET,
2950 		    ("vfs_busy_pages: no buffer offset"));
2951 		vfs_setdirty(bp);
2952 
2953 retry:
2954 		for (i = 0; i < bp->b_npages; i++) {
2955 			vm_page_t m = bp->b_pages[i];
2956 			if (vm_page_sleep_busy(m, FALSE, "vbpage"))
2957 				goto retry;
2958 		}
2959 
2960 		bogus = 0;
2961 		for (i = 0; i < bp->b_npages; i++) {
2962 			vm_page_t m = bp->b_pages[i];
2963 
2964 			vm_page_flag_clear(m, PG_ZERO);
2965 			if ((bp->b_flags & B_CLUSTER) == 0) {
2966 				vm_object_pip_add(obj, 1);
2967 				vm_page_io_start(m);
2968 			}
2969 
2970 			/*
2971 			 * When readying a buffer for a read ( i.e
2972 			 * clear_modify == 0 ), it is important to do
2973 			 * bogus_page replacement for valid pages in
2974 			 * partially instantiated buffers.  Partially
2975 			 * instantiated buffers can, in turn, occur when
2976 			 * reconstituting a buffer from its VM backing store
2977 			 * base.  We only have to do this if B_CACHE is
2978 			 * clear ( which causes the I/O to occur in the
2979 			 * first place ).  The replacement prevents the read
2980 			 * I/O from overwriting potentially dirty VM-backed
2981 			 * pages.  XXX bogus page replacement is, uh, bogus.
2982 			 * It may not work properly with small-block devices.
2983 			 * We need to find a better way.
2984 			 */
2985 
2986 			vm_page_protect(m, VM_PROT_NONE);
2987 			if (clear_modify)
2988 				vfs_page_set_valid(bp, foff, i, m);
2989 			else if (m->valid == VM_PAGE_BITS_ALL &&
2990 				(bp->b_flags & B_CACHE) == 0) {
2991 				bp->b_pages[i] = bogus_page;
2992 				bogus++;
2993 			}
2994 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2995 		}
2996 		if (bogus)
2997 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2998 	}
2999 }
3000 
3001 /*
3002  * Tell the VM system that the pages associated with this buffer
3003  * are clean.  This is used for delayed writes where the data is
3004  * going to go to disk eventually without additional VM intevention.
3005  *
3006  * Note that while we only really need to clean through to b_bcount, we
3007  * just go ahead and clean through to b_bufsize.
3008  */
3009 static void
3010 vfs_clean_pages(struct buf * bp)
3011 {
3012 	int i;
3013 
3014 	if (bp->b_flags & B_VMIO) {
3015 		vm_ooffset_t foff;
3016 
3017 		foff = bp->b_offset;
3018 		KASSERT(bp->b_offset != NOOFFSET,
3019 		    ("vfs_clean_pages: no buffer offset"));
3020 		for (i = 0; i < bp->b_npages; i++) {
3021 			vm_page_t m = bp->b_pages[i];
3022 			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3023 			vm_ooffset_t eoff = noff;
3024 
3025 			if (eoff > bp->b_offset + bp->b_bufsize)
3026 				eoff = bp->b_offset + bp->b_bufsize;
3027 			vfs_page_set_valid(bp, foff, i, m);
3028 			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3029 			foff = noff;
3030 		}
3031 	}
3032 }
3033 
3034 /*
3035  *	vfs_bio_set_validclean:
3036  *
3037  *	Set the range within the buffer to valid and clean.  The range is
3038  *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3039  *	itself may be offset from the beginning of the first page.
3040  */
3041 
3042 void
3043 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3044 {
3045 	if (bp->b_flags & B_VMIO) {
3046 		int i;
3047 		int n;
3048 
3049 		/*
3050 		 * Fixup base to be relative to beginning of first page.
3051 		 * Set initial n to be the maximum number of bytes in the
3052 		 * first page that can be validated.
3053 		 */
3054 
3055 		base += (bp->b_offset & PAGE_MASK);
3056 		n = PAGE_SIZE - (base & PAGE_MASK);
3057 
3058 		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3059 			vm_page_t m = bp->b_pages[i];
3060 
3061 			if (n > size)
3062 				n = size;
3063 
3064 			vm_page_set_validclean(m, base & PAGE_MASK, n);
3065 			base += n;
3066 			size -= n;
3067 			n = PAGE_SIZE;
3068 		}
3069 	}
3070 }
3071 
3072 /*
3073  *	vfs_bio_clrbuf:
3074  *
3075  *	clear a buffer.  This routine essentially fakes an I/O, so we need
3076  *	to clear BIO_ERROR and B_INVAL.
3077  *
3078  *	Note that while we only theoretically need to clear through b_bcount,
3079  *	we go ahead and clear through b_bufsize.
3080  */
3081 
3082 void
3083 vfs_bio_clrbuf(struct buf *bp) {
3084 	int i, mask = 0;
3085 	caddr_t sa, ea;
3086 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3087 		bp->b_flags &= ~B_INVAL;
3088 		bp->b_ioflags &= ~BIO_ERROR;
3089 		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3090 		    (bp->b_offset & PAGE_MASK) == 0) {
3091 			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3092 			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3093 			    ((bp->b_pages[0]->valid & mask) != mask)) {
3094 				bzero(bp->b_data, bp->b_bufsize);
3095 			}
3096 			bp->b_pages[0]->valid |= mask;
3097 			bp->b_resid = 0;
3098 			return;
3099 		}
3100 		ea = sa = bp->b_data;
3101 		for(i=0;i<bp->b_npages;i++,sa=ea) {
3102 			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3103 			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3104 			ea = (caddr_t)(vm_offset_t)ulmin(
3105 			    (u_long)(vm_offset_t)ea,
3106 			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3107 			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3108 			if ((bp->b_pages[i]->valid & mask) == mask)
3109 				continue;
3110 			if ((bp->b_pages[i]->valid & mask) == 0) {
3111 				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3112 					bzero(sa, ea - sa);
3113 				}
3114 			} else {
3115 				for (; sa < ea; sa += DEV_BSIZE, j++) {
3116 					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3117 						(bp->b_pages[i]->valid & (1<<j)) == 0)
3118 						bzero(sa, DEV_BSIZE);
3119 				}
3120 			}
3121 			bp->b_pages[i]->valid |= mask;
3122 			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3123 		}
3124 		bp->b_resid = 0;
3125 	} else {
3126 		clrbuf(bp);
3127 	}
3128 }
3129 
3130 /*
3131  * vm_hold_load_pages and vm_hold_unload pages get pages into
3132  * a buffers address space.  The pages are anonymous and are
3133  * not associated with a file object.
3134  */
3135 void
3136 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3137 {
3138 	vm_offset_t pg;
3139 	vm_page_t p;
3140 	int index;
3141 
3142 	to = round_page(to);
3143 	from = round_page(from);
3144 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3145 
3146 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3147 
3148 tryagain:
3149 
3150 		/*
3151 		 * note: must allocate system pages since blocking here
3152 		 * could intefere with paging I/O, no matter which
3153 		 * process we are.
3154 		 */
3155 		p = vm_page_alloc(kernel_object,
3156 			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3157 		    VM_ALLOC_SYSTEM);
3158 		if (!p) {
3159 			vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3160 			VM_WAIT;
3161 			goto tryagain;
3162 		}
3163 		vm_page_wire(p);
3164 		p->valid = VM_PAGE_BITS_ALL;
3165 		vm_page_flag_clear(p, PG_ZERO);
3166 		pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3167 		bp->b_pages[index] = p;
3168 		vm_page_wakeup(p);
3169 	}
3170 	bp->b_npages = index;
3171 }
3172 
3173 void
3174 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3175 {
3176 	vm_offset_t pg;
3177 	vm_page_t p;
3178 	int index, newnpages;
3179 
3180 	from = round_page(from);
3181 	to = round_page(to);
3182 	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3183 
3184 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3185 		p = bp->b_pages[index];
3186 		if (p && (index < bp->b_npages)) {
3187 			if (p->busy) {
3188 				printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3189 					bp->b_blkno, bp->b_lblkno);
3190 			}
3191 			bp->b_pages[index] = NULL;
3192 			pmap_kremove(pg);
3193 			vm_page_busy(p);
3194 			vm_page_unwire(p, 0);
3195 			vm_page_free(p);
3196 		}
3197 	}
3198 	bp->b_npages = newnpages;
3199 }
3200 
3201 
3202 #include "opt_ddb.h"
3203 #ifdef DDB
3204 #include <ddb/ddb.h>
3205 
3206 DB_SHOW_COMMAND(buffer, db_show_buffer)
3207 {
3208 	/* get args */
3209 	struct buf *bp = (struct buf *)addr;
3210 
3211 	if (!have_addr) {
3212 		db_printf("usage: show buffer <addr>\n");
3213 		return;
3214 	}
3215 
3216 	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3217 	db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3218 		  "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3219 		  "b_blkno = %d, b_pblkno = %d\n",
3220 		  bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3221 		  major(bp->b_dev), minor(bp->b_dev),
3222 		  bp->b_data, bp->b_blkno, bp->b_pblkno);
3223 	if (bp->b_npages) {
3224 		int i;
3225 		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3226 		for (i = 0; i < bp->b_npages; i++) {
3227 			vm_page_t m;
3228 			m = bp->b_pages[i];
3229 			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3230 			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3231 			if ((i + 1) < bp->b_npages)
3232 				db_printf(",");
3233 		}
3234 		db_printf("\n");
3235 	}
3236 }
3237 #endif /* DDB */
3238