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