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