xref: /dragonfly/sys/kern/vfs_bio.c (revision e96fb831)
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: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
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/buf.h>
33 #include <sys/conf.h>
34 #include <sys/devicestat.h>
35 #include <sys/eventhandler.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/proc.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
47 #include <sys/dsched.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 #include <vm/vm_pager.h>
57 #include <vm/swap_pager.h>
58 
59 #include <sys/buf2.h>
60 #include <sys/thread2.h>
61 #include <sys/spinlock2.h>
62 #include <sys/mplock2.h>
63 #include <vm/vm_page2.h>
64 
65 #include "opt_ddb.h"
66 #ifdef DDB
67 #include <ddb/ddb.h>
68 #endif
69 
70 /*
71  * Buffer queues.
72  */
73 enum bufq_type {
74 	BQUEUE_NONE,    	/* not on any queue */
75 	BQUEUE_LOCKED,  	/* locked buffers */
76 	BQUEUE_CLEAN,   	/* non-B_DELWRI buffers */
77 	BQUEUE_DIRTY,   	/* B_DELWRI buffers */
78 	BQUEUE_DIRTY_HW,   	/* B_DELWRI buffers - heavy weight */
79 	BQUEUE_EMPTYKVA, 	/* empty buffer headers with KVA assignment */
80 	BQUEUE_EMPTY,    	/* empty buffer headers */
81 
82 	BUFFER_QUEUES		/* number of buffer queues */
83 };
84 
85 typedef enum bufq_type bufq_type_t;
86 
87 #define BD_WAKE_SIZE	16384
88 #define BD_WAKE_MASK	(BD_WAKE_SIZE - 1)
89 
90 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
91 static struct spinlock bufqspin = SPINLOCK_INITIALIZER(&bufqspin);
92 static struct spinlock bufcspin = SPINLOCK_INITIALIZER(&bufcspin);
93 
94 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
95 
96 struct buf *buf;		/* buffer header pool */
97 
98 static void vfs_clean_pages(struct buf *bp);
99 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
100 static void vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m);
101 static void vfs_vmio_release(struct buf *bp);
102 static int flushbufqueues(bufq_type_t q);
103 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
104 
105 static void bd_signal(int totalspace);
106 static void buf_daemon(void);
107 static void buf_daemon_hw(void);
108 
109 /*
110  * bogus page -- for I/O to/from partially complete buffers
111  * this is a temporary solution to the problem, but it is not
112  * really that bad.  it would be better to split the buffer
113  * for input in the case of buffers partially already in memory,
114  * but the code is intricate enough already.
115  */
116 vm_page_t bogus_page;
117 
118 /*
119  * These are all static, but make the ones we export globals so we do
120  * not need to use compiler magic.
121  */
122 long bufspace;			/* locked by buffer_map */
123 long maxbufspace;
124 static long bufmallocspace;	/* atomic ops */
125 long maxbufmallocspace, lobufspace, hibufspace;
126 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
127 static long lorunningspace;
128 static long hirunningspace;
129 static int runningbufreq;		/* locked by bufcspin */
130 static long dirtybufspace;		/* locked by bufcspin */
131 static int dirtybufcount;		/* locked by bufcspin */
132 static long dirtybufspacehw;		/* locked by bufcspin */
133 static int dirtybufcounthw;		/* locked by bufcspin */
134 static long runningbufspace;		/* locked by bufcspin */
135 static int runningbufcount;		/* locked by bufcspin */
136 long lodirtybufspace;
137 long hidirtybufspace;
138 static int getnewbufcalls;
139 static int getnewbufrestarts;
140 static int recoverbufcalls;
141 static int needsbuffer;		/* locked by bufcspin */
142 static int bd_request;		/* locked by bufcspin */
143 static int bd_request_hw;	/* locked by bufcspin */
144 static u_int bd_wake_ary[BD_WAKE_SIZE];
145 static u_int bd_wake_index;
146 static u_int vm_cycle_point = 40; /* 23-36 will migrate more act->inact */
147 static int debug_commit;
148 
149 static struct thread *bufdaemon_td;
150 static struct thread *bufdaemonhw_td;
151 static u_int lowmempgallocs;
152 static u_int lowmempgfails;
153 
154 /*
155  * Sysctls for operational control of the buffer cache.
156  */
157 SYSCTL_LONG(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
158 	"Number of dirty buffers to flush before bufdaemon becomes inactive");
159 SYSCTL_LONG(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
160 	"High watermark used to trigger explicit flushing of dirty buffers");
161 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
162 	"Minimum amount of buffer space required for active I/O");
163 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
164 	"Maximum amount of buffer space to usable for active I/O");
165 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgallocs, CTLFLAG_RW, &lowmempgallocs, 0,
166 	"Page allocations done during periods of very low free memory");
167 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgfails, CTLFLAG_RW, &lowmempgfails, 0,
168 	"Page allocations which failed during periods of very low free memory");
169 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
170 	"Recycle pages to active or inactive queue transition pt 0-64");
171 /*
172  * Sysctls determining current state of the buffer cache.
173  */
174 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
175 	"Total number of buffers in buffer cache");
176 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
177 	"Pending bytes of dirty buffers (all)");
178 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
179 	"Pending bytes of dirty buffers (heavy weight)");
180 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
181 	"Pending number of dirty buffers");
182 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
183 	"Pending number of dirty buffers (heavy weight)");
184 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
185 	"I/O bytes currently in progress due to asynchronous writes");
186 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
187 	"I/O buffers currently in progress due to asynchronous writes");
188 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
189 	"Hard limit on maximum amount of memory usable for buffer space");
190 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
191 	"Soft limit on maximum amount of memory usable for buffer space");
192 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
193 	"Minimum amount of memory to reserve for system buffer space");
194 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
195 	"Amount of memory available for buffers");
196 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
197 	0, "Maximum amount of memory reserved for buffers using malloc");
198 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
199 	"Amount of memory left for buffers using malloc-scheme");
200 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
201 	"New buffer header acquisition requests");
202 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
203 	0, "New buffer header acquisition restarts");
204 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
205 	"Recover VM space in an emergency");
206 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
207 	"Buffer acquisition restarts due to fragmented buffer map");
208 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
209 	"Amount of time KVA space was deallocated in an arbitrary buffer");
210 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
211 	"Amount of time buffer re-use operations were successful");
212 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
213 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
214 	"sizeof(struct buf)");
215 
216 char *buf_wmesg = BUF_WMESG;
217 
218 #define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
219 #define VFS_BIO_NEED_UNUSED02	0x02
220 #define VFS_BIO_NEED_UNUSED04	0x04
221 #define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
222 
223 /*
224  * bufspacewakeup:
225  *
226  *	Called when buffer space is potentially available for recovery.
227  *	getnewbuf() will block on this flag when it is unable to free
228  *	sufficient buffer space.  Buffer space becomes recoverable when
229  *	bp's get placed back in the queues.
230  */
231 static __inline void
232 bufspacewakeup(void)
233 {
234 	/*
235 	 * If someone is waiting for BUF space, wake them up.  Even
236 	 * though we haven't freed the kva space yet, the waiting
237 	 * process will be able to now.
238 	 */
239 	spin_lock(&bufcspin);
240 	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
241 		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
242 		spin_unlock(&bufcspin);
243 		wakeup(&needsbuffer);
244 	} else {
245 		spin_unlock(&bufcspin);
246 	}
247 }
248 
249 /*
250  * runningbufwakeup:
251  *
252  *	Accounting for I/O in progress.
253  *
254  */
255 static __inline void
256 runningbufwakeup(struct buf *bp)
257 {
258 	long totalspace;
259 	long limit;
260 
261 	if ((totalspace = bp->b_runningbufspace) != 0) {
262 		spin_lock(&bufcspin);
263 		runningbufspace -= totalspace;
264 		--runningbufcount;
265 		bp->b_runningbufspace = 0;
266 
267 		/*
268 		 * see waitrunningbufspace() for limit test.
269 		 */
270 		limit = hirunningspace * 3 / 6;
271 		if (runningbufreq && runningbufspace <= limit) {
272 			runningbufreq = 0;
273 			spin_unlock(&bufcspin);
274 			wakeup(&runningbufreq);
275 		} else {
276 			spin_unlock(&bufcspin);
277 		}
278 		bd_signal(totalspace);
279 	}
280 }
281 
282 /*
283  * bufcountwakeup:
284  *
285  *	Called when a buffer has been added to one of the free queues to
286  *	account for the buffer and to wakeup anyone waiting for free buffers.
287  *	This typically occurs when large amounts of metadata are being handled
288  *	by the buffer cache ( else buffer space runs out first, usually ).
289  *
290  * MPSAFE
291  */
292 static __inline void
293 bufcountwakeup(void)
294 {
295 	spin_lock(&bufcspin);
296 	if (needsbuffer) {
297 		needsbuffer &= ~VFS_BIO_NEED_ANY;
298 		spin_unlock(&bufcspin);
299 		wakeup(&needsbuffer);
300 	} else {
301 		spin_unlock(&bufcspin);
302 	}
303 }
304 
305 /*
306  * waitrunningbufspace()
307  *
308  * If runningbufspace exceeds 4/6 hirunningspace we block until
309  * runningbufspace drops to 3/6 hirunningspace.  We also block if another
310  * thread blocked here in order to be fair, even if runningbufspace
311  * is now lower than the limit.
312  *
313  * The caller may be using this function to block in a tight loop, we
314  * must block while runningbufspace is greater than at least
315  * hirunningspace * 3 / 6.
316  */
317 void
318 waitrunningbufspace(void)
319 {
320 	long limit = hirunningspace * 4 / 6;
321 
322 	if (runningbufspace > limit || runningbufreq) {
323 		spin_lock(&bufcspin);
324 		while (runningbufspace > limit || runningbufreq) {
325 			runningbufreq = 1;
326 			ssleep(&runningbufreq, &bufcspin, 0, "wdrn1", 0);
327 		}
328 		spin_unlock(&bufcspin);
329 	}
330 }
331 
332 /*
333  * buf_dirty_count_severe:
334  *
335  *	Return true if we have too many dirty buffers.
336  */
337 int
338 buf_dirty_count_severe(void)
339 {
340 	return (runningbufspace + dirtybufspace >= hidirtybufspace ||
341 	        dirtybufcount >= nbuf / 2);
342 }
343 
344 /*
345  * Return true if the amount of running I/O is severe and BIOQ should
346  * start bursting.
347  */
348 int
349 buf_runningbufspace_severe(void)
350 {
351 	return (runningbufspace >= hirunningspace * 4 / 6);
352 }
353 
354 /*
355  * vfs_buf_test_cache:
356  *
357  * Called when a buffer is extended.  This function clears the B_CACHE
358  * bit if the newly extended portion of the buffer does not contain
359  * valid data.
360  *
361  * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
362  * cache buffers.  The VM pages remain dirty, as someone had mmap()'d
363  * them while a clean buffer was present.
364  */
365 static __inline__
366 void
367 vfs_buf_test_cache(struct buf *bp,
368 		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
369 		  vm_page_t m)
370 {
371 	if (bp->b_flags & B_CACHE) {
372 		int base = (foff + off) & PAGE_MASK;
373 		if (vm_page_is_valid(m, base, size) == 0)
374 			bp->b_flags &= ~B_CACHE;
375 	}
376 }
377 
378 /*
379  * bd_speedup()
380  *
381  * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
382  * low water mark.
383  *
384  * MPSAFE
385  */
386 static __inline__
387 void
388 bd_speedup(void)
389 {
390 	if (dirtybufspace < lodirtybufspace && dirtybufcount < nbuf / 2)
391 		return;
392 
393 	if (bd_request == 0 &&
394 	    (dirtybufspace - dirtybufspacehw > lodirtybufspace / 2 ||
395 	     dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
396 		spin_lock(&bufcspin);
397 		bd_request = 1;
398 		spin_unlock(&bufcspin);
399 		wakeup(&bd_request);
400 	}
401 	if (bd_request_hw == 0 &&
402 	    (dirtybufspacehw > lodirtybufspace / 2 ||
403 	     dirtybufcounthw >= nbuf / 2)) {
404 		spin_lock(&bufcspin);
405 		bd_request_hw = 1;
406 		spin_unlock(&bufcspin);
407 		wakeup(&bd_request_hw);
408 	}
409 }
410 
411 /*
412  * bd_heatup()
413  *
414  *	Get the buf_daemon heated up when the number of running and dirty
415  *	buffers exceeds the mid-point.
416  *
417  *	Return the total number of dirty bytes past the second mid point
418  *	as a measure of how much excess dirty data there is in the system.
419  *
420  * MPSAFE
421  */
422 int
423 bd_heatup(void)
424 {
425 	long mid1;
426 	long mid2;
427 	long totalspace;
428 
429 	mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
430 
431 	totalspace = runningbufspace + dirtybufspace;
432 	if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
433 		bd_speedup();
434 		mid2 = mid1 + (hidirtybufspace - mid1) / 2;
435 		if (totalspace >= mid2)
436 			return(totalspace - mid2);
437 	}
438 	return(0);
439 }
440 
441 /*
442  * bd_wait()
443  *
444  *	Wait for the buffer cache to flush (totalspace) bytes worth of
445  *	buffers, then return.
446  *
447  *	Regardless this function blocks while the number of dirty buffers
448  *	exceeds hidirtybufspace.
449  *
450  * MPSAFE
451  */
452 void
453 bd_wait(int totalspace)
454 {
455 	u_int i;
456 	int count;
457 
458 	if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
459 		return;
460 
461 	while (totalspace > 0) {
462 		bd_heatup();
463 		if (totalspace > runningbufspace + dirtybufspace)
464 			totalspace = runningbufspace + dirtybufspace;
465 		count = totalspace / BKVASIZE;
466 		if (count >= BD_WAKE_SIZE)
467 			count = BD_WAKE_SIZE - 1;
468 
469 		spin_lock(&bufcspin);
470 		i = (bd_wake_index + count) & BD_WAKE_MASK;
471 		++bd_wake_ary[i];
472 
473 		/*
474 		 * This is not a strict interlock, so we play a bit loose
475 		 * with locking access to dirtybufspace*
476 		 */
477 		tsleep_interlock(&bd_wake_ary[i], 0);
478 		spin_unlock(&bufcspin);
479 		tsleep(&bd_wake_ary[i], PINTERLOCKED, "flstik", hz);
480 
481 		totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
482 	}
483 }
484 
485 /*
486  * bd_signal()
487  *
488  *	This function is called whenever runningbufspace or dirtybufspace
489  *	is reduced.  Track threads waiting for run+dirty buffer I/O
490  *	complete.
491  *
492  * MPSAFE
493  */
494 static void
495 bd_signal(int totalspace)
496 {
497 	u_int i;
498 
499 	if (totalspace > 0) {
500 		if (totalspace > BKVASIZE * BD_WAKE_SIZE)
501 			totalspace = BKVASIZE * BD_WAKE_SIZE;
502 		spin_lock(&bufcspin);
503 		while (totalspace > 0) {
504 			i = bd_wake_index++;
505 			i &= BD_WAKE_MASK;
506 			if (bd_wake_ary[i]) {
507 				bd_wake_ary[i] = 0;
508 				spin_unlock(&bufcspin);
509 				wakeup(&bd_wake_ary[i]);
510 				spin_lock(&bufcspin);
511 			}
512 			totalspace -= BKVASIZE;
513 		}
514 		spin_unlock(&bufcspin);
515 	}
516 }
517 
518 /*
519  * BIO tracking support routines.
520  *
521  * Release a ref on a bio_track.  Wakeup requests are atomically released
522  * along with the last reference so bk_active will never wind up set to
523  * only 0x80000000.
524  *
525  * MPSAFE
526  */
527 static
528 void
529 bio_track_rel(struct bio_track *track)
530 {
531 	int	active;
532 	int	desired;
533 
534 	/*
535 	 * Shortcut
536 	 */
537 	active = track->bk_active;
538 	if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
539 		return;
540 
541 	/*
542 	 * Full-on.  Note that the wait flag is only atomically released on
543 	 * the 1->0 count transition.
544 	 *
545 	 * We check for a negative count transition using bit 30 since bit 31
546 	 * has a different meaning.
547 	 */
548 	for (;;) {
549 		desired = (active & 0x7FFFFFFF) - 1;
550 		if (desired)
551 			desired |= active & 0x80000000;
552 		if (atomic_cmpset_int(&track->bk_active, active, desired)) {
553 			if (desired & 0x40000000)
554 				panic("bio_track_rel: bad count: %p\n", track);
555 			if (active & 0x80000000)
556 				wakeup(track);
557 			break;
558 		}
559 		active = track->bk_active;
560 	}
561 }
562 
563 /*
564  * Wait for the tracking count to reach 0.
565  *
566  * Use atomic ops such that the wait flag is only set atomically when
567  * bk_active is non-zero.
568  *
569  * MPSAFE
570  */
571 int
572 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
573 {
574 	int	active;
575 	int	desired;
576 	int	error;
577 
578 	/*
579 	 * Shortcut
580 	 */
581 	if (track->bk_active == 0)
582 		return(0);
583 
584 	/*
585 	 * Full-on.  Note that the wait flag may only be atomically set if
586 	 * the active count is non-zero.
587 	 *
588 	 * NOTE: We cannot optimize active == desired since a wakeup could
589 	 *	 clear active prior to our tsleep_interlock().
590 	 */
591 	error = 0;
592 	while ((active = track->bk_active) != 0) {
593 		cpu_ccfence();
594 		desired = active | 0x80000000;
595 		tsleep_interlock(track, slp_flags);
596 		if (atomic_cmpset_int(&track->bk_active, active, desired)) {
597 			error = tsleep(track, slp_flags | PINTERLOCKED,
598 				       "trwait", slp_timo);
599 			if (error)
600 				break;
601 		}
602 	}
603 	return (error);
604 }
605 
606 /*
607  * bufinit:
608  *
609  *	Load time initialisation of the buffer cache, called from machine
610  *	dependant initialization code.
611  */
612 void
613 bufinit(void)
614 {
615 	struct buf *bp;
616 	vm_offset_t bogus_offset;
617 	int i;
618 
619 	/* next, make a null set of free lists */
620 	for (i = 0; i < BUFFER_QUEUES; i++)
621 		TAILQ_INIT(&bufqueues[i]);
622 
623 	/* finally, initialize each buffer header and stick on empty q */
624 	for (i = 0; i < nbuf; i++) {
625 		bp = &buf[i];
626 		bzero(bp, sizeof *bp);
627 		bp->b_flags = B_INVAL;	/* we're just an empty header */
628 		bp->b_cmd = BUF_CMD_DONE;
629 		bp->b_qindex = BQUEUE_EMPTY;
630 		initbufbio(bp);
631 		xio_init(&bp->b_xio);
632 		buf_dep_init(bp);
633 		TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
634 	}
635 
636 	/*
637 	 * maxbufspace is the absolute maximum amount of buffer space we are
638 	 * allowed to reserve in KVM and in real terms.  The absolute maximum
639 	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
640 	 * used by most other processes.  The differential is required to
641 	 * ensure that buf_daemon is able to run when other processes might
642 	 * be blocked waiting for buffer space.
643 	 *
644 	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
645 	 * this may result in KVM fragmentation which is not handled optimally
646 	 * by the system.
647 	 */
648 	maxbufspace = (long)nbuf * BKVASIZE;
649 	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
650 	lobufspace = hibufspace - MAXBSIZE;
651 
652 	lorunningspace = 512 * 1024;
653 	/* hirunningspace -- see below */
654 
655 	/*
656 	 * Limit the amount of malloc memory since it is wired permanently
657 	 * into the kernel space.  Even though this is accounted for in
658 	 * the buffer allocation, we don't want the malloced region to grow
659 	 * uncontrolled.  The malloc scheme improves memory utilization
660 	 * significantly on average (small) directories.
661 	 */
662 	maxbufmallocspace = hibufspace / 20;
663 
664 	/*
665 	 * Reduce the chance of a deadlock occuring by limiting the number
666 	 * of delayed-write dirty buffers we allow to stack up.
667 	 *
668 	 * We don't want too much actually queued to the device at once
669 	 * (XXX this needs to be per-mount!), because the buffers will
670 	 * wind up locked for a very long period of time while the I/O
671 	 * drains.
672 	 */
673 	hidirtybufspace = hibufspace / 2;	/* dirty + running */
674 	hirunningspace = hibufspace / 16;	/* locked & queued to device */
675 	if (hirunningspace < 1024 * 1024)
676 		hirunningspace = 1024 * 1024;
677 
678 	dirtybufspace = 0;
679 	dirtybufspacehw = 0;
680 
681 	lodirtybufspace = hidirtybufspace / 2;
682 
683 	/*
684 	 * Maximum number of async ops initiated per buf_daemon loop.  This is
685 	 * somewhat of a hack at the moment, we really need to limit ourselves
686 	 * based on the number of bytes of I/O in-transit that were initiated
687 	 * from buf_daemon.
688 	 */
689 
690 	bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
691 	vm_object_hold(&kernel_object);
692 	bogus_page = vm_page_alloc(&kernel_object,
693 				   (bogus_offset >> PAGE_SHIFT),
694 				   VM_ALLOC_NORMAL);
695 	vm_object_drop(&kernel_object);
696 	vmstats.v_wire_count++;
697 
698 }
699 
700 /*
701  * Initialize the embedded bio structures, typically used by
702  * deprecated code which tries to allocate its own struct bufs.
703  */
704 void
705 initbufbio(struct buf *bp)
706 {
707 	bp->b_bio1.bio_buf = bp;
708 	bp->b_bio1.bio_prev = NULL;
709 	bp->b_bio1.bio_offset = NOOFFSET;
710 	bp->b_bio1.bio_next = &bp->b_bio2;
711 	bp->b_bio1.bio_done = NULL;
712 	bp->b_bio1.bio_flags = 0;
713 
714 	bp->b_bio2.bio_buf = bp;
715 	bp->b_bio2.bio_prev = &bp->b_bio1;
716 	bp->b_bio2.bio_offset = NOOFFSET;
717 	bp->b_bio2.bio_next = NULL;
718 	bp->b_bio2.bio_done = NULL;
719 	bp->b_bio2.bio_flags = 0;
720 
721 	BUF_LOCKINIT(bp);
722 }
723 
724 /*
725  * Reinitialize the embedded bio structures as well as any additional
726  * translation cache layers.
727  */
728 void
729 reinitbufbio(struct buf *bp)
730 {
731 	struct bio *bio;
732 
733 	for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
734 		bio->bio_done = NULL;
735 		bio->bio_offset = NOOFFSET;
736 	}
737 }
738 
739 /*
740  * Undo the effects of an initbufbio().
741  */
742 void
743 uninitbufbio(struct buf *bp)
744 {
745 	dsched_exit_buf(bp);
746 	BUF_LOCKFREE(bp);
747 }
748 
749 /*
750  * Push another BIO layer onto an existing BIO and return it.  The new
751  * BIO layer may already exist, holding cached translation data.
752  */
753 struct bio *
754 push_bio(struct bio *bio)
755 {
756 	struct bio *nbio;
757 
758 	if ((nbio = bio->bio_next) == NULL) {
759 		int index = bio - &bio->bio_buf->b_bio_array[0];
760 		if (index >= NBUF_BIO - 1) {
761 			panic("push_bio: too many layers bp %p\n",
762 				bio->bio_buf);
763 		}
764 		nbio = &bio->bio_buf->b_bio_array[index + 1];
765 		bio->bio_next = nbio;
766 		nbio->bio_prev = bio;
767 		nbio->bio_buf = bio->bio_buf;
768 		nbio->bio_offset = NOOFFSET;
769 		nbio->bio_done = NULL;
770 		nbio->bio_next = NULL;
771 	}
772 	KKASSERT(nbio->bio_done == NULL);
773 	return(nbio);
774 }
775 
776 /*
777  * Pop a BIO translation layer, returning the previous layer.  The
778  * must have been previously pushed.
779  */
780 struct bio *
781 pop_bio(struct bio *bio)
782 {
783 	return(bio->bio_prev);
784 }
785 
786 void
787 clearbiocache(struct bio *bio)
788 {
789 	while (bio) {
790 		bio->bio_offset = NOOFFSET;
791 		bio = bio->bio_next;
792 	}
793 }
794 
795 /*
796  * bfreekva:
797  *
798  *	Free the KVA allocation for buffer 'bp'.
799  *
800  *	Must be called from a critical section as this is the only locking for
801  *	buffer_map.
802  *
803  *	Since this call frees up buffer space, we call bufspacewakeup().
804  *
805  * MPALMOSTSAFE
806  */
807 static void
808 bfreekva(struct buf *bp)
809 {
810 	int count;
811 
812 	if (bp->b_kvasize) {
813 		++buffreekvacnt;
814 		count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
815 		vm_map_lock(&buffer_map);
816 		bufspace -= bp->b_kvasize;
817 		vm_map_delete(&buffer_map,
818 		    (vm_offset_t) bp->b_kvabase,
819 		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
820 		    &count
821 		);
822 		vm_map_unlock(&buffer_map);
823 		vm_map_entry_release(count);
824 		bp->b_kvasize = 0;
825 		bp->b_kvabase = NULL;
826 		bufspacewakeup();
827 	}
828 }
829 
830 /*
831  * bremfree:
832  *
833  *	Remove the buffer from the appropriate free list.
834  */
835 static __inline void
836 _bremfree(struct buf *bp)
837 {
838 	if (bp->b_qindex != BQUEUE_NONE) {
839 		KASSERT(BUF_REFCNTNB(bp) == 1,
840 				("bremfree: bp %p not locked",bp));
841 		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
842 		bp->b_qindex = BQUEUE_NONE;
843 	} else {
844 		if (BUF_REFCNTNB(bp) <= 1)
845 			panic("bremfree: removing a buffer not on a queue");
846 	}
847 }
848 
849 void
850 bremfree(struct buf *bp)
851 {
852 	spin_lock(&bufqspin);
853 	_bremfree(bp);
854 	spin_unlock(&bufqspin);
855 }
856 
857 static void
858 bremfree_locked(struct buf *bp)
859 {
860 	_bremfree(bp);
861 }
862 
863 /*
864  * This version of bread issues any required I/O asyncnronously and
865  * makes a callback on completion.
866  *
867  * The callback must check whether BIO_DONE is set in the bio and issue
868  * the bpdone(bp, 0) if it isn't.  The callback is responsible for clearing
869  * BIO_DONE and disposing of the I/O (bqrelse()ing it).
870  */
871 void
872 breadcb(struct vnode *vp, off_t loffset, int size,
873 	void (*func)(struct bio *), void *arg)
874 {
875 	struct buf *bp;
876 
877 	bp = getblk(vp, loffset, size, 0, 0);
878 
879 	/* if not found in cache, do some I/O */
880 	if ((bp->b_flags & B_CACHE) == 0) {
881 		bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
882 		bp->b_cmd = BUF_CMD_READ;
883 		bp->b_bio1.bio_done = func;
884 		bp->b_bio1.bio_caller_info1.ptr = arg;
885 		vfs_busy_pages(vp, bp);
886 		BUF_KERNPROC(bp);
887 		vn_strategy(vp, &bp->b_bio1);
888 	} else if (func) {
889 		/*
890 		 * Since we are issuing the callback synchronously it cannot
891 		 * race the BIO_DONE, so no need for atomic ops here.
892 		 */
893 		/*bp->b_bio1.bio_done = func;*/
894 		bp->b_bio1.bio_caller_info1.ptr = arg;
895 		bp->b_bio1.bio_flags |= BIO_DONE;
896 		func(&bp->b_bio1);
897 	} else {
898 		bqrelse(bp);
899 	}
900 }
901 
902 /*
903  * breadnx() - Terminal function for bread() and breadn().
904  *
905  * This function will start asynchronous I/O on read-ahead blocks as well
906  * as satisfy the primary request.
907  *
908  * We must clear B_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE is
909  * set, the buffer is valid and we do not have to do anything.
910  */
911 int
912 breadnx(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
913 	int *rabsize, int cnt, struct buf **bpp)
914 {
915 	struct buf *bp, *rabp;
916 	int i;
917 	int rv = 0, readwait = 0;
918 
919 	if (*bpp)
920 		bp = *bpp;
921 	else
922 		*bpp = bp = getblk(vp, loffset, size, 0, 0);
923 
924 	/* if not found in cache, do some I/O */
925 	if ((bp->b_flags & B_CACHE) == 0) {
926 		bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
927 		bp->b_cmd = BUF_CMD_READ;
928 		bp->b_bio1.bio_done = biodone_sync;
929 		bp->b_bio1.bio_flags |= BIO_SYNC;
930 		vfs_busy_pages(vp, bp);
931 		vn_strategy(vp, &bp->b_bio1);
932 		++readwait;
933 	}
934 
935 	for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
936 		if (inmem(vp, *raoffset))
937 			continue;
938 		rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
939 
940 		if ((rabp->b_flags & B_CACHE) == 0) {
941 			rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
942 			rabp->b_cmd = BUF_CMD_READ;
943 			vfs_busy_pages(vp, rabp);
944 			BUF_KERNPROC(rabp);
945 			vn_strategy(vp, &rabp->b_bio1);
946 		} else {
947 			brelse(rabp);
948 		}
949 	}
950 	if (readwait)
951 		rv = biowait(&bp->b_bio1, "biord");
952 	return (rv);
953 }
954 
955 /*
956  * bwrite:
957  *
958  *	Synchronous write, waits for completion.
959  *
960  *	Write, release buffer on completion.  (Done by iodone
961  *	if async).  Do not bother writing anything if the buffer
962  *	is invalid.
963  *
964  *	Note that we set B_CACHE here, indicating that buffer is
965  *	fully valid and thus cacheable.  This is true even of NFS
966  *	now so we set it generally.  This could be set either here
967  *	or in biodone() since the I/O is synchronous.  We put it
968  *	here.
969  */
970 int
971 bwrite(struct buf *bp)
972 {
973 	int error;
974 
975 	if (bp->b_flags & B_INVAL) {
976 		brelse(bp);
977 		return (0);
978 	}
979 	if (BUF_REFCNTNB(bp) == 0)
980 		panic("bwrite: buffer is not busy???");
981 
982 	/* Mark the buffer clean */
983 	bundirty(bp);
984 
985 	bp->b_flags &= ~(B_ERROR | B_EINTR);
986 	bp->b_flags |= B_CACHE;
987 	bp->b_cmd = BUF_CMD_WRITE;
988 	bp->b_bio1.bio_done = biodone_sync;
989 	bp->b_bio1.bio_flags |= BIO_SYNC;
990 	vfs_busy_pages(bp->b_vp, bp);
991 
992 	/*
993 	 * Normal bwrites pipeline writes.  NOTE: b_bufsize is only
994 	 * valid for vnode-backed buffers.
995 	 */
996 	bsetrunningbufspace(bp, bp->b_bufsize);
997 	vn_strategy(bp->b_vp, &bp->b_bio1);
998 	error = biowait(&bp->b_bio1, "biows");
999 	brelse(bp);
1000 
1001 	return (error);
1002 }
1003 
1004 /*
1005  * bawrite:
1006  *
1007  *	Asynchronous write.  Start output on a buffer, but do not wait for
1008  *	it to complete.  The buffer is released when the output completes.
1009  *
1010  *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1011  *	B_INVAL buffers.  Not us.
1012  */
1013 void
1014 bawrite(struct buf *bp)
1015 {
1016 	if (bp->b_flags & B_INVAL) {
1017 		brelse(bp);
1018 		return;
1019 	}
1020 	if (BUF_REFCNTNB(bp) == 0)
1021 		panic("bwrite: buffer is not busy???");
1022 
1023 	/* Mark the buffer clean */
1024 	bundirty(bp);
1025 
1026 	bp->b_flags &= ~(B_ERROR | B_EINTR);
1027 	bp->b_flags |= B_CACHE;
1028 	bp->b_cmd = BUF_CMD_WRITE;
1029 	KKASSERT(bp->b_bio1.bio_done == NULL);
1030 	vfs_busy_pages(bp->b_vp, bp);
1031 
1032 	/*
1033 	 * Normal bwrites pipeline writes.  NOTE: b_bufsize is only
1034 	 * valid for vnode-backed buffers.
1035 	 */
1036 	bsetrunningbufspace(bp, bp->b_bufsize);
1037 	BUF_KERNPROC(bp);
1038 	vn_strategy(bp->b_vp, &bp->b_bio1);
1039 }
1040 
1041 /*
1042  * bowrite:
1043  *
1044  *	Ordered write.  Start output on a buffer, and flag it so that the
1045  *	device will write it in the order it was queued.  The buffer is
1046  *	released when the output completes.  bwrite() ( or the VOP routine
1047  *	anyway ) is responsible for handling B_INVAL buffers.
1048  */
1049 int
1050 bowrite(struct buf *bp)
1051 {
1052 	bp->b_flags |= B_ORDERED;
1053 	bawrite(bp);
1054 	return (0);
1055 }
1056 
1057 /*
1058  * bdwrite:
1059  *
1060  *	Delayed write. (Buffer is marked dirty).  Do not bother writing
1061  *	anything if the buffer is marked invalid.
1062  *
1063  *	Note that since the buffer must be completely valid, we can safely
1064  *	set B_CACHE.  In fact, we have to set B_CACHE here rather then in
1065  *	biodone() in order to prevent getblk from writing the buffer
1066  *	out synchronously.
1067  */
1068 void
1069 bdwrite(struct buf *bp)
1070 {
1071 	if (BUF_REFCNTNB(bp) == 0)
1072 		panic("bdwrite: buffer is not busy");
1073 
1074 	if (bp->b_flags & B_INVAL) {
1075 		brelse(bp);
1076 		return;
1077 	}
1078 	bdirty(bp);
1079 
1080 	if (dsched_is_clear_buf_priv(bp))
1081 		dsched_new_buf(bp);
1082 
1083 	/*
1084 	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
1085 	 * true even of NFS now.
1086 	 */
1087 	bp->b_flags |= B_CACHE;
1088 
1089 	/*
1090 	 * This bmap keeps the system from needing to do the bmap later,
1091 	 * perhaps when the system is attempting to do a sync.  Since it
1092 	 * is likely that the indirect block -- or whatever other datastructure
1093 	 * that the filesystem needs is still in memory now, it is a good
1094 	 * thing to do this.  Note also, that if the pageout daemon is
1095 	 * requesting a sync -- there might not be enough memory to do
1096 	 * the bmap then...  So, this is important to do.
1097 	 */
1098 	if (bp->b_bio2.bio_offset == NOOFFSET) {
1099 		VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1100 			 NULL, NULL, BUF_CMD_WRITE);
1101 	}
1102 
1103 	/*
1104 	 * Because the underlying pages may still be mapped and
1105 	 * writable trying to set the dirty buffer (b_dirtyoff/end)
1106 	 * range here will be inaccurate.
1107 	 *
1108 	 * However, we must still clean the pages to satisfy the
1109 	 * vnode_pager and pageout daemon, so theythink the pages
1110 	 * have been "cleaned".  What has really occured is that
1111 	 * they've been earmarked for later writing by the buffer
1112 	 * cache.
1113 	 *
1114 	 * So we get the b_dirtyoff/end update but will not actually
1115 	 * depend on it (NFS that is) until the pages are busied for
1116 	 * writing later on.
1117 	 */
1118 	vfs_clean_pages(bp);
1119 	bqrelse(bp);
1120 
1121 	/*
1122 	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1123 	 * due to the softdep code.
1124 	 */
1125 }
1126 
1127 /*
1128  * Fake write - return pages to VM system as dirty, leave the buffer clean.
1129  * This is used by tmpfs.
1130  *
1131  * It is important for any VFS using this routine to NOT use it for
1132  * IO_SYNC or IO_ASYNC operations which occur when the system really
1133  * wants to flush VM pages to backing store.
1134  */
1135 void
1136 buwrite(struct buf *bp)
1137 {
1138 	vm_page_t m;
1139 	int i;
1140 
1141 	/*
1142 	 * Only works for VMIO buffers.  If the buffer is already
1143 	 * marked for delayed-write we can't avoid the bdwrite().
1144 	 */
1145 	if ((bp->b_flags & B_VMIO) == 0 || (bp->b_flags & B_DELWRI)) {
1146 		bdwrite(bp);
1147 		return;
1148 	}
1149 
1150 	/*
1151 	 * Set valid & dirty.
1152 	 */
1153 	for (i = 0; i < bp->b_xio.xio_npages; i++) {
1154 		m = bp->b_xio.xio_pages[i];
1155 		vfs_dirty_one_page(bp, i, m);
1156 	}
1157 	bqrelse(bp);
1158 }
1159 
1160 /*
1161  * bdirty:
1162  *
1163  *	Turn buffer into delayed write request by marking it B_DELWRI.
1164  *	B_RELBUF and B_NOCACHE must be cleared.
1165  *
1166  *	We reassign the buffer to itself to properly update it in the
1167  *	dirty/clean lists.
1168  *
1169  *	Must be called from a critical section.
1170  *	The buffer must be on BQUEUE_NONE.
1171  */
1172 void
1173 bdirty(struct buf *bp)
1174 {
1175 	KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1176 	if (bp->b_flags & B_NOCACHE) {
1177 		kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
1178 		bp->b_flags &= ~B_NOCACHE;
1179 	}
1180 	if (bp->b_flags & B_INVAL) {
1181 		kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
1182 	}
1183 	bp->b_flags &= ~B_RELBUF;
1184 
1185 	if ((bp->b_flags & B_DELWRI) == 0) {
1186 		lwkt_gettoken(&bp->b_vp->v_token);
1187 		bp->b_flags |= B_DELWRI;
1188 		reassignbuf(bp);
1189 		lwkt_reltoken(&bp->b_vp->v_token);
1190 
1191 		spin_lock(&bufcspin);
1192 		++dirtybufcount;
1193 		dirtybufspace += bp->b_bufsize;
1194 		if (bp->b_flags & B_HEAVY) {
1195 			++dirtybufcounthw;
1196 			dirtybufspacehw += bp->b_bufsize;
1197 		}
1198 		spin_unlock(&bufcspin);
1199 
1200 		bd_heatup();
1201 	}
1202 }
1203 
1204 /*
1205  * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1206  * needs to be flushed with a different buf_daemon thread to avoid
1207  * deadlocks.  B_HEAVY also imposes restrictions in getnewbuf().
1208  */
1209 void
1210 bheavy(struct buf *bp)
1211 {
1212 	if ((bp->b_flags & B_HEAVY) == 0) {
1213 		bp->b_flags |= B_HEAVY;
1214 		if (bp->b_flags & B_DELWRI) {
1215 			spin_lock(&bufcspin);
1216 			++dirtybufcounthw;
1217 			dirtybufspacehw += bp->b_bufsize;
1218 			spin_unlock(&bufcspin);
1219 		}
1220 	}
1221 }
1222 
1223 /*
1224  * bundirty:
1225  *
1226  *	Clear B_DELWRI for buffer.
1227  *
1228  *	Must be called from a critical section.
1229  *
1230  *	The buffer is typically on BQUEUE_NONE but there is one case in
1231  *	brelse() that calls this function after placing the buffer on
1232  *	a different queue.
1233  *
1234  * MPSAFE
1235  */
1236 void
1237 bundirty(struct buf *bp)
1238 {
1239 	if (bp->b_flags & B_DELWRI) {
1240 		lwkt_gettoken(&bp->b_vp->v_token);
1241 		bp->b_flags &= ~B_DELWRI;
1242 		reassignbuf(bp);
1243 		lwkt_reltoken(&bp->b_vp->v_token);
1244 
1245 		spin_lock(&bufcspin);
1246 		--dirtybufcount;
1247 		dirtybufspace -= bp->b_bufsize;
1248 		if (bp->b_flags & B_HEAVY) {
1249 			--dirtybufcounthw;
1250 			dirtybufspacehw -= bp->b_bufsize;
1251 		}
1252 		spin_unlock(&bufcspin);
1253 
1254 		bd_signal(bp->b_bufsize);
1255 	}
1256 	/*
1257 	 * Since it is now being written, we can clear its deferred write flag.
1258 	 */
1259 	bp->b_flags &= ~B_DEFERRED;
1260 }
1261 
1262 /*
1263  * Set the b_runningbufspace field, used to track how much I/O is
1264  * in progress at any given moment.
1265  */
1266 void
1267 bsetrunningbufspace(struct buf *bp, int bytes)
1268 {
1269 	bp->b_runningbufspace = bytes;
1270 	if (bytes) {
1271 		spin_lock(&bufcspin);
1272 		runningbufspace += bytes;
1273 		++runningbufcount;
1274 		spin_unlock(&bufcspin);
1275 	}
1276 }
1277 
1278 /*
1279  * brelse:
1280  *
1281  *	Release a busy buffer and, if requested, free its resources.  The
1282  *	buffer will be stashed in the appropriate bufqueue[] allowing it
1283  *	to be accessed later as a cache entity or reused for other purposes.
1284  *
1285  * MPALMOSTSAFE
1286  */
1287 void
1288 brelse(struct buf *bp)
1289 {
1290 #ifdef INVARIANTS
1291 	int saved_flags = bp->b_flags;
1292 #endif
1293 
1294 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1295 
1296 	/*
1297 	 * If B_NOCACHE is set we are being asked to destroy the buffer and
1298 	 * its backing store.  Clear B_DELWRI.
1299 	 *
1300 	 * B_NOCACHE is set in two cases: (1) when the caller really wants
1301 	 * to destroy the buffer and backing store and (2) when the caller
1302 	 * wants to destroy the buffer and backing store after a write
1303 	 * completes.
1304 	 */
1305 	if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1306 		bundirty(bp);
1307 	}
1308 
1309 	if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1310 		/*
1311 		 * A re-dirtied buffer is only subject to destruction
1312 		 * by B_INVAL.  B_ERROR and B_NOCACHE are ignored.
1313 		 */
1314 		/* leave buffer intact */
1315 	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1316 		   (bp->b_bufsize <= 0)) {
1317 		/*
1318 		 * Either a failed read or we were asked to free or not
1319 		 * cache the buffer.  This path is reached with B_DELWRI
1320 		 * set only if B_INVAL is already set.  B_NOCACHE governs
1321 		 * backing store destruction.
1322 		 *
1323 		 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1324 		 * buffer cannot be immediately freed.
1325 		 */
1326 		bp->b_flags |= B_INVAL;
1327 		if (LIST_FIRST(&bp->b_dep) != NULL)
1328 			buf_deallocate(bp);
1329 		if (bp->b_flags & B_DELWRI) {
1330 			spin_lock(&bufcspin);
1331 			--dirtybufcount;
1332 			dirtybufspace -= bp->b_bufsize;
1333 			if (bp->b_flags & B_HEAVY) {
1334 				--dirtybufcounthw;
1335 				dirtybufspacehw -= bp->b_bufsize;
1336 			}
1337 			spin_unlock(&bufcspin);
1338 
1339 			bd_signal(bp->b_bufsize);
1340 		}
1341 		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1342 	}
1343 
1344 	/*
1345 	 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1346 	 * or if b_refs is non-zero.
1347 	 *
1348 	 * If vfs_vmio_release() is called with either bit set, the
1349 	 * underlying pages may wind up getting freed causing a previous
1350 	 * write (bdwrite()) to get 'lost' because pages associated with
1351 	 * a B_DELWRI bp are marked clean.  Pages associated with a
1352 	 * B_LOCKED buffer may be mapped by the filesystem.
1353 	 *
1354 	 * If we want to release the buffer ourselves (rather then the
1355 	 * originator asking us to release it), give the originator a
1356 	 * chance to countermand the release by setting B_LOCKED.
1357 	 *
1358 	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1359 	 * if B_DELWRI is set.
1360 	 *
1361 	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1362 	 * on pages to return pages to the VM page queues.
1363 	 */
1364 	if ((bp->b_flags & (B_DELWRI | B_LOCKED)) || bp->b_refs) {
1365 		bp->b_flags &= ~B_RELBUF;
1366 	} else if (vm_page_count_severe()) {
1367 		if (LIST_FIRST(&bp->b_dep) != NULL)
1368 			buf_deallocate(bp);		/* can set B_LOCKED */
1369 		if (bp->b_flags & (B_DELWRI | B_LOCKED))
1370 			bp->b_flags &= ~B_RELBUF;
1371 		else
1372 			bp->b_flags |= B_RELBUF;
1373 	}
1374 
1375 	/*
1376 	 * Make sure b_cmd is clear.  It may have already been cleared by
1377 	 * biodone().
1378 	 *
1379 	 * At this point destroying the buffer is governed by the B_INVAL
1380 	 * or B_RELBUF flags.
1381 	 */
1382 	bp->b_cmd = BUF_CMD_DONE;
1383 	dsched_exit_buf(bp);
1384 
1385 	/*
1386 	 * VMIO buffer rundown.  Make sure the VM page array is restored
1387 	 * after an I/O may have replaces some of the pages with bogus pages
1388 	 * in order to not destroy dirty pages in a fill-in read.
1389 	 *
1390 	 * Note that due to the code above, if a buffer is marked B_DELWRI
1391 	 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1392 	 * B_INVAL may still be set, however.
1393 	 *
1394 	 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1395 	 * but not the backing store.   B_NOCACHE will destroy the backing
1396 	 * store.
1397 	 *
1398 	 * Note that dirty NFS buffers contain byte-granular write ranges
1399 	 * and should not be destroyed w/ B_INVAL even if the backing store
1400 	 * is left intact.
1401 	 */
1402 	if (bp->b_flags & B_VMIO) {
1403 		/*
1404 		 * Rundown for VMIO buffers which are not dirty NFS buffers.
1405 		 */
1406 		int i, j, resid;
1407 		vm_page_t m;
1408 		off_t foff;
1409 		vm_pindex_t poff;
1410 		vm_object_t obj;
1411 		struct vnode *vp;
1412 
1413 		vp = bp->b_vp;
1414 
1415 		/*
1416 		 * Get the base offset and length of the buffer.  Note that
1417 		 * in the VMIO case if the buffer block size is not
1418 		 * page-aligned then b_data pointer may not be page-aligned.
1419 		 * But our b_xio.xio_pages array *IS* page aligned.
1420 		 *
1421 		 * block sizes less then DEV_BSIZE (usually 512) are not
1422 		 * supported due to the page granularity bits (m->valid,
1423 		 * m->dirty, etc...).
1424 		 *
1425 		 * See man buf(9) for more information
1426 		 */
1427 
1428 		resid = bp->b_bufsize;
1429 		foff = bp->b_loffset;
1430 
1431 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
1432 			m = bp->b_xio.xio_pages[i];
1433 			vm_page_flag_clear(m, PG_ZERO);
1434 			/*
1435 			 * If we hit a bogus page, fixup *all* of them
1436 			 * now.  Note that we left these pages wired
1437 			 * when we removed them so they had better exist,
1438 			 * and they cannot be ripped out from under us so
1439 			 * no critical section protection is necessary.
1440 			 */
1441 			if (m == bogus_page) {
1442 				obj = vp->v_object;
1443 				poff = OFF_TO_IDX(bp->b_loffset);
1444 
1445 				vm_object_hold(obj);
1446 				for (j = i; j < bp->b_xio.xio_npages; j++) {
1447 					vm_page_t mtmp;
1448 
1449 					mtmp = bp->b_xio.xio_pages[j];
1450 					if (mtmp == bogus_page) {
1451 						mtmp = vm_page_lookup(obj, poff + j);
1452 						if (!mtmp) {
1453 							panic("brelse: page missing");
1454 						}
1455 						bp->b_xio.xio_pages[j] = mtmp;
1456 					}
1457 				}
1458 				bp->b_flags &= ~B_HASBOGUS;
1459 				vm_object_drop(obj);
1460 
1461 				if ((bp->b_flags & B_INVAL) == 0) {
1462 					pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1463 						bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1464 				}
1465 				m = bp->b_xio.xio_pages[i];
1466 			}
1467 
1468 			/*
1469 			 * Invalidate the backing store if B_NOCACHE is set
1470 			 * (e.g. used with vinvalbuf()).  If this is NFS
1471 			 * we impose a requirement that the block size be
1472 			 * a multiple of PAGE_SIZE and create a temporary
1473 			 * hack to basically invalidate the whole page.  The
1474 			 * problem is that NFS uses really odd buffer sizes
1475 			 * especially when tracking piecemeal writes and
1476 			 * it also vinvalbuf()'s a lot, which would result
1477 			 * in only partial page validation and invalidation
1478 			 * here.  If the file page is mmap()'d, however,
1479 			 * all the valid bits get set so after we invalidate
1480 			 * here we would end up with weird m->valid values
1481 			 * like 0xfc.  nfs_getpages() can't handle this so
1482 			 * we clear all the valid bits for the NFS case
1483 			 * instead of just some of them.
1484 			 *
1485 			 * The real bug is the VM system having to set m->valid
1486 			 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1487 			 * itself is an artifact of the whole 512-byte
1488 			 * granular mess that exists to support odd block
1489 			 * sizes and UFS meta-data block sizes (e.g. 6144).
1490 			 * A complete rewrite is required.
1491 			 *
1492 			 * XXX
1493 			 */
1494 			if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1495 				int poffset = foff & PAGE_MASK;
1496 				int presid;
1497 
1498 				presid = PAGE_SIZE - poffset;
1499 				if (bp->b_vp->v_tag == VT_NFS &&
1500 				    bp->b_vp->v_type == VREG) {
1501 					; /* entire page */
1502 				} else if (presid > resid) {
1503 					presid = resid;
1504 				}
1505 				KASSERT(presid >= 0, ("brelse: extra page"));
1506 				vm_page_set_invalid(m, poffset, presid);
1507 
1508 				/*
1509 				 * Also make sure any swap cache is removed
1510 				 * as it is now stale (HAMMER in particular
1511 				 * uses B_NOCACHE to deal with buffer
1512 				 * aliasing).
1513 				 */
1514 				swap_pager_unswapped(m);
1515 			}
1516 			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1517 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1518 		}
1519 		if (bp->b_flags & (B_INVAL | B_RELBUF))
1520 			vfs_vmio_release(bp);
1521 	} else {
1522 		/*
1523 		 * Rundown for non-VMIO buffers.
1524 		 */
1525 		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1526 			if (bp->b_bufsize)
1527 				allocbuf(bp, 0);
1528 			KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1529 			if (bp->b_vp)
1530 				brelvp(bp);
1531 		}
1532 	}
1533 
1534 	if (bp->b_qindex != BQUEUE_NONE)
1535 		panic("brelse: free buffer onto another queue???");
1536 	if (BUF_REFCNTNB(bp) > 1) {
1537 		/* Temporary panic to verify exclusive locking */
1538 		/* This panic goes away when we allow shared refs */
1539 		panic("brelse: multiple refs");
1540 		/* NOT REACHED */
1541 		return;
1542 	}
1543 
1544 	/*
1545 	 * Figure out the correct queue to place the cleaned up buffer on.
1546 	 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1547 	 * disassociated from their vnode.
1548 	 */
1549 	spin_lock(&bufqspin);
1550 	if (bp->b_flags & B_LOCKED) {
1551 		/*
1552 		 * Buffers that are locked are placed in the locked queue
1553 		 * immediately, regardless of their state.
1554 		 */
1555 		bp->b_qindex = BQUEUE_LOCKED;
1556 		TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1557 	} else if (bp->b_bufsize == 0) {
1558 		/*
1559 		 * Buffers with no memory.  Due to conditionals near the top
1560 		 * of brelse() such buffers should probably already be
1561 		 * marked B_INVAL and disassociated from their vnode.
1562 		 */
1563 		bp->b_flags |= B_INVAL;
1564 		KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1565 		KKASSERT((bp->b_flags & B_HASHED) == 0);
1566 		if (bp->b_kvasize) {
1567 			bp->b_qindex = BQUEUE_EMPTYKVA;
1568 		} else {
1569 			bp->b_qindex = BQUEUE_EMPTY;
1570 		}
1571 		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1572 	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1573 		/*
1574 		 * Buffers with junk contents.   Again these buffers had better
1575 		 * already be disassociated from their vnode.
1576 		 */
1577 		KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1578 		KKASSERT((bp->b_flags & B_HASHED) == 0);
1579 		bp->b_flags |= B_INVAL;
1580 		bp->b_qindex = BQUEUE_CLEAN;
1581 		TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1582 	} else {
1583 		/*
1584 		 * Remaining buffers.  These buffers are still associated with
1585 		 * their vnode.
1586 		 */
1587 		switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1588 		case B_DELWRI:
1589 		    bp->b_qindex = BQUEUE_DIRTY;
1590 		    TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1591 		    break;
1592 		case B_DELWRI | B_HEAVY:
1593 		    bp->b_qindex = BQUEUE_DIRTY_HW;
1594 		    TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1595 				      b_freelist);
1596 		    break;
1597 		default:
1598 		    /*
1599 		     * NOTE: Buffers are always placed at the end of the
1600 		     * queue.  If B_AGE is not set the buffer will cycle
1601 		     * through the queue twice.
1602 		     */
1603 		    bp->b_qindex = BQUEUE_CLEAN;
1604 		    TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1605 		    break;
1606 		}
1607 	}
1608 	spin_unlock(&bufqspin);
1609 
1610 	/*
1611 	 * If B_INVAL, clear B_DELWRI.  We've already placed the buffer
1612 	 * on the correct queue.
1613 	 */
1614 	if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1615 		bundirty(bp);
1616 
1617 	/*
1618 	 * The bp is on an appropriate queue unless locked.  If it is not
1619 	 * locked or dirty we can wakeup threads waiting for buffer space.
1620 	 *
1621 	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1622 	 * if B_INVAL is set ).
1623 	 */
1624 	if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1625 		bufcountwakeup();
1626 
1627 	/*
1628 	 * Something we can maybe free or reuse
1629 	 */
1630 	if (bp->b_bufsize || bp->b_kvasize)
1631 		bufspacewakeup();
1632 
1633 	/*
1634 	 * Clean up temporary flags and unlock the buffer.
1635 	 */
1636 	bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
1637 	BUF_UNLOCK(bp);
1638 }
1639 
1640 /*
1641  * bqrelse:
1642  *
1643  *	Release a buffer back to the appropriate queue but do not try to free
1644  *	it.  The buffer is expected to be used again soon.
1645  *
1646  *	bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1647  *	biodone() to requeue an async I/O on completion.  It is also used when
1648  *	known good buffers need to be requeued but we think we may need the data
1649  *	again soon.
1650  *
1651  *	XXX we should be able to leave the B_RELBUF hint set on completion.
1652  *
1653  * MPSAFE
1654  */
1655 void
1656 bqrelse(struct buf *bp)
1657 {
1658 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1659 
1660 	if (bp->b_qindex != BQUEUE_NONE)
1661 		panic("bqrelse: free buffer onto another queue???");
1662 	if (BUF_REFCNTNB(bp) > 1) {
1663 		/* do not release to free list */
1664 		panic("bqrelse: multiple refs");
1665 		return;
1666 	}
1667 
1668 	buf_act_advance(bp);
1669 
1670 	spin_lock(&bufqspin);
1671 	if (bp->b_flags & B_LOCKED) {
1672 		/*
1673 		 * Locked buffers are released to the locked queue.  However,
1674 		 * if the buffer is dirty it will first go into the dirty
1675 		 * queue and later on after the I/O completes successfully it
1676 		 * will be released to the locked queue.
1677 		 */
1678 		bp->b_qindex = BQUEUE_LOCKED;
1679 		TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1680 	} else if (bp->b_flags & B_DELWRI) {
1681 		bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1682 			       BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1683 		TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1684 	} else if (vm_page_count_severe()) {
1685 		/*
1686 		 * We are too low on memory, we have to try to free the
1687 		 * buffer (most importantly: the wired pages making up its
1688 		 * backing store) *now*.
1689 		 */
1690 		spin_unlock(&bufqspin);
1691 		brelse(bp);
1692 		return;
1693 	} else {
1694 		bp->b_qindex = BQUEUE_CLEAN;
1695 		TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1696 	}
1697 	spin_unlock(&bufqspin);
1698 
1699 	if ((bp->b_flags & B_LOCKED) == 0 &&
1700 	    ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1701 		bufcountwakeup();
1702 	}
1703 
1704 	/*
1705 	 * Something we can maybe free or reuse.
1706 	 */
1707 	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1708 		bufspacewakeup();
1709 
1710 	/*
1711 	 * Final cleanup and unlock.  Clear bits that are only used while a
1712 	 * buffer is actively locked.
1713 	 */
1714 	bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
1715 	dsched_exit_buf(bp);
1716 	BUF_UNLOCK(bp);
1717 }
1718 
1719 /*
1720  * Hold a buffer, preventing it from being reused.  This will prevent
1721  * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1722  * operations.  If a B_INVAL operation occurs the buffer will remain held
1723  * but the underlying pages may get ripped out.
1724  *
1725  * These functions are typically used in VOP_READ/VOP_WRITE functions
1726  * to hold a buffer during a copyin or copyout, preventing deadlocks
1727  * or recursive lock panics when read()/write() is used over mmap()'d
1728  * space.
1729  *
1730  * NOTE: bqhold() requires that the buffer be locked at the time of the
1731  *	 hold.  bqdrop() has no requirements other than the buffer having
1732  *	 previously been held.
1733  */
1734 void
1735 bqhold(struct buf *bp)
1736 {
1737 	atomic_add_int(&bp->b_refs, 1);
1738 }
1739 
1740 void
1741 bqdrop(struct buf *bp)
1742 {
1743 	KKASSERT(bp->b_refs > 0);
1744 	atomic_add_int(&bp->b_refs, -1);
1745 }
1746 
1747 /*
1748  * vfs_vmio_release:
1749  *
1750  *	Return backing pages held by the buffer 'bp' back to the VM system
1751  *	if possible.  The pages are freed if they are no longer valid or
1752  *	attempt to free if it was used for direct I/O otherwise they are
1753  *	sent to the page cache.
1754  *
1755  *	Pages that were marked busy are left alone and skipped.
1756  *
1757  *	The KVA mapping (b_data) for the underlying pages is removed by
1758  *	this function.
1759  */
1760 static void
1761 vfs_vmio_release(struct buf *bp)
1762 {
1763 	int i;
1764 	vm_page_t m;
1765 
1766 	for (i = 0; i < bp->b_xio.xio_npages; i++) {
1767 		m = bp->b_xio.xio_pages[i];
1768 		bp->b_xio.xio_pages[i] = NULL;
1769 
1770 		vm_page_busy_wait(m, FALSE, "vmiopg");
1771 
1772 		/*
1773 		 * The VFS is telling us this is not a meta-data buffer
1774 		 * even if it is backed by a block device.
1775 		 */
1776 		if (bp->b_flags & B_NOTMETA)
1777 			vm_page_flag_set(m, PG_NOTMETA);
1778 
1779 		/*
1780 		 * This is a very important bit of code.  We try to track
1781 		 * VM page use whether the pages are wired into the buffer
1782 		 * cache or not.  While wired into the buffer cache the
1783 		 * bp tracks the act_count.
1784 		 *
1785 		 * We can choose to place unwired pages on the inactive
1786 		 * queue (0) or active queue (1).  If we place too many
1787 		 * on the active queue the queue will cycle the act_count
1788 		 * on pages we'd like to keep, just from single-use pages
1789 		 * (such as when doing a tar-up or file scan).
1790 		 */
1791 		if (bp->b_act_count < vm_cycle_point)
1792 			vm_page_unwire(m, 0);
1793 		else
1794 			vm_page_unwire(m, 1);
1795 
1796 		/*
1797 		 * We don't mess with busy pages, it is the responsibility
1798 		 * of the process that busied the pages to deal with them.
1799 		 *
1800 		 * However, the caller may have marked the page invalid and
1801 		 * we must still make sure the page is no longer mapped.
1802 		 */
1803 		if ((m->flags & PG_BUSY) || (m->busy != 0)) {
1804 			vm_page_protect(m, VM_PROT_NONE);
1805 			vm_page_wakeup(m);
1806 			continue;
1807 		}
1808 
1809 		if (m->wire_count == 0) {
1810 			vm_page_flag_clear(m, PG_ZERO);
1811 			/*
1812 			 * Might as well free the page if we can and it has
1813 			 * no valid data.  We also free the page if the
1814 			 * buffer was used for direct I/O.
1815 			 */
1816 #if 0
1817 			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1818 					m->hold_count == 0) {
1819 				vm_page_protect(m, VM_PROT_NONE);
1820 				vm_page_free(m);
1821 			} else
1822 #endif
1823 			/*
1824 			 * Cache the page if we are really low on free
1825 			 * pages.
1826 			 *
1827 			 * Also bypass the active and inactive queues
1828 			 * if B_NOTMETA is set.  This flag is set by HAMMER
1829 			 * on a regular file buffer when double buffering
1830 			 * is enabled or on a block device buffer representing
1831 			 * file data when double buffering is not enabled.
1832 			 * The flag prevents two copies of the same data from
1833 			 * being cached for long periods of time.
1834 			 */
1835 			if (bp->b_flags & B_DIRECT) {
1836 				vm_page_wakeup(m);
1837 				vm_page_try_to_free(m);
1838 			} else if ((bp->b_flags & B_NOTMETA) ||
1839 				   vm_page_count_severe()) {
1840 				m->act_count = bp->b_act_count;
1841 				vm_page_wakeup(m);
1842 				vm_page_try_to_cache(m);
1843 			} else {
1844 				m->act_count = bp->b_act_count;
1845 				vm_page_wakeup(m);
1846 			}
1847 		} else {
1848 			vm_page_wakeup(m);
1849 		}
1850 	}
1851 
1852 	pmap_qremove(trunc_page((vm_offset_t) bp->b_data),
1853 		     bp->b_xio.xio_npages);
1854 	if (bp->b_bufsize) {
1855 		bufspacewakeup();
1856 		bp->b_bufsize = 0;
1857 	}
1858 	bp->b_xio.xio_npages = 0;
1859 	bp->b_flags &= ~B_VMIO;
1860 	KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1861 	if (bp->b_vp)
1862 		brelvp(bp);
1863 }
1864 
1865 /*
1866  * vfs_bio_awrite:
1867  *
1868  *	Implement clustered async writes for clearing out B_DELWRI buffers.
1869  *	This is much better then the old way of writing only one buffer at
1870  *	a time.  Note that we may not be presented with the buffers in the
1871  *	correct order, so we search for the cluster in both directions.
1872  *
1873  *	The buffer is locked on call.
1874  */
1875 int
1876 vfs_bio_awrite(struct buf *bp)
1877 {
1878 	int i;
1879 	int j;
1880 	off_t loffset = bp->b_loffset;
1881 	struct vnode *vp = bp->b_vp;
1882 	int nbytes;
1883 	struct buf *bpa;
1884 	int nwritten;
1885 	int size;
1886 
1887 	/*
1888 	 * right now we support clustered writing only to regular files.  If
1889 	 * we find a clusterable block we could be in the middle of a cluster
1890 	 * rather then at the beginning.
1891 	 *
1892 	 * NOTE: b_bio1 contains the logical loffset and is aliased
1893 	 * to b_loffset.  b_bio2 contains the translated block number.
1894 	 */
1895 	if ((vp->v_type == VREG) &&
1896 	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1897 	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1898 
1899 		size = vp->v_mount->mnt_stat.f_iosize;
1900 
1901 		for (i = size; i < MAXPHYS; i += size) {
1902 			if ((bpa = findblk(vp, loffset + i, FINDBLK_TEST)) &&
1903 			    BUF_REFCNT(bpa) == 0 &&
1904 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1905 			    (B_DELWRI | B_CLUSTEROK)) &&
1906 			    (bpa->b_bufsize == size)) {
1907 				if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1908 				    (bpa->b_bio2.bio_offset !=
1909 				     bp->b_bio2.bio_offset + i))
1910 					break;
1911 			} else {
1912 				break;
1913 			}
1914 		}
1915 		for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1916 			if ((bpa = findblk(vp, loffset - j, FINDBLK_TEST)) &&
1917 			    BUF_REFCNT(bpa) == 0 &&
1918 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1919 			    (B_DELWRI | B_CLUSTEROK)) &&
1920 			    (bpa->b_bufsize == size)) {
1921 				if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1922 				    (bpa->b_bio2.bio_offset !=
1923 				     bp->b_bio2.bio_offset - j))
1924 					break;
1925 			} else {
1926 				break;
1927 			}
1928 		}
1929 		j -= size;
1930 		nbytes = (i + j);
1931 
1932 		/*
1933 		 * this is a possible cluster write
1934 		 */
1935 		if (nbytes != size) {
1936 			BUF_UNLOCK(bp);
1937 			nwritten = cluster_wbuild(vp, size,
1938 						  loffset - j, nbytes);
1939 			return nwritten;
1940 		}
1941 	}
1942 
1943 	/*
1944 	 * default (old) behavior, writing out only one block
1945 	 *
1946 	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1947 	 */
1948 	nwritten = bp->b_bufsize;
1949 	bremfree(bp);
1950 	bawrite(bp);
1951 
1952 	return nwritten;
1953 }
1954 
1955 /*
1956  * getnewbuf:
1957  *
1958  *	Find and initialize a new buffer header, freeing up existing buffers
1959  *	in the bufqueues as necessary.  The new buffer is returned locked.
1960  *
1961  *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1962  *	buffer away, the caller must set B_INVAL prior to calling brelse().
1963  *
1964  *	We block if:
1965  *		We have insufficient buffer headers
1966  *		We have insufficient buffer space
1967  *		buffer_map is too fragmented ( space reservation fails )
1968  *		If we have to flush dirty buffers ( but we try to avoid this )
1969  *
1970  *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1971  *	Instead we ask the buf daemon to do it for us.  We attempt to
1972  *	avoid piecemeal wakeups of the pageout daemon.
1973  *
1974  * MPALMOSTSAFE
1975  */
1976 struct buf *
1977 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1978 {
1979 	struct buf *bp;
1980 	struct buf *nbp;
1981 	int defrag = 0;
1982 	int nqindex;
1983 	int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1984 	static int flushingbufs;
1985 
1986 	/*
1987 	 * We can't afford to block since we might be holding a vnode lock,
1988 	 * which may prevent system daemons from running.  We deal with
1989 	 * low-memory situations by proactively returning memory and running
1990 	 * async I/O rather then sync I/O.
1991 	 */
1992 
1993 	++getnewbufcalls;
1994 	--getnewbufrestarts;
1995 restart:
1996 	++getnewbufrestarts;
1997 
1998 	/*
1999 	 * Setup for scan.  If we do not have enough free buffers,
2000 	 * we setup a degenerate case that immediately fails.  Note
2001 	 * that if we are specially marked process, we are allowed to
2002 	 * dip into our reserves.
2003 	 *
2004 	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
2005 	 *
2006 	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
2007 	 * However, there are a number of cases (defragging, reusing, ...)
2008 	 * where we cannot backup.
2009 	 */
2010 	nqindex = BQUEUE_EMPTYKVA;
2011 	spin_lock(&bufqspin);
2012 	nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
2013 
2014 	if (nbp == NULL) {
2015 		/*
2016 		 * If no EMPTYKVA buffers and we are either
2017 		 * defragging or reusing, locate a CLEAN buffer
2018 		 * to free or reuse.  If bufspace useage is low
2019 		 * skip this step so we can allocate a new buffer.
2020 		 */
2021 		if (defrag || bufspace >= lobufspace) {
2022 			nqindex = BQUEUE_CLEAN;
2023 			nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2024 		}
2025 
2026 		/*
2027 		 * If we could not find or were not allowed to reuse a
2028 		 * CLEAN buffer, check to see if it is ok to use an EMPTY
2029 		 * buffer.  We can only use an EMPTY buffer if allocating
2030 		 * its KVA would not otherwise run us out of buffer space.
2031 		 */
2032 		if (nbp == NULL && defrag == 0 &&
2033 		    bufspace + maxsize < hibufspace) {
2034 			nqindex = BQUEUE_EMPTY;
2035 			nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
2036 		}
2037 	}
2038 
2039 	/*
2040 	 * Run scan, possibly freeing data and/or kva mappings on the fly
2041 	 * depending.
2042 	 *
2043 	 * WARNING!  bufqspin is held!
2044 	 */
2045 	while ((bp = nbp) != NULL) {
2046 		int qindex = nqindex;
2047 
2048 		nbp = TAILQ_NEXT(bp, b_freelist);
2049 
2050 		/*
2051 		 * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
2052 		 * cycles through the queue twice before being selected.
2053 		 */
2054 		if (qindex == BQUEUE_CLEAN &&
2055 		    (bp->b_flags & B_AGE) == 0 && nbp) {
2056 			bp->b_flags |= B_AGE;
2057 			TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
2058 			TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
2059 			continue;
2060 		}
2061 
2062 		/*
2063 		 * Calculate next bp ( we can only use it if we do not block
2064 		 * or do other fancy things ).
2065 		 */
2066 		if (nbp == NULL) {
2067 			switch(qindex) {
2068 			case BQUEUE_EMPTY:
2069 				nqindex = BQUEUE_EMPTYKVA;
2070 				if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
2071 					break;
2072 				/* fall through */
2073 			case BQUEUE_EMPTYKVA:
2074 				nqindex = BQUEUE_CLEAN;
2075 				if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
2076 					break;
2077 				/* fall through */
2078 			case BQUEUE_CLEAN:
2079 				/*
2080 				 * nbp is NULL.
2081 				 */
2082 				break;
2083 			}
2084 		}
2085 
2086 		/*
2087 		 * Sanity Checks
2088 		 */
2089 		KASSERT(bp->b_qindex == qindex,
2090 			("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2091 
2092 		/*
2093 		 * Note: we no longer distinguish between VMIO and non-VMIO
2094 		 * buffers.
2095 		 */
2096 		KASSERT((bp->b_flags & B_DELWRI) == 0,
2097 			("delwri buffer %p found in queue %d", bp, qindex));
2098 
2099 		/*
2100 		 * Do not try to reuse a buffer with a non-zero b_refs.
2101 		 * This is an unsynchronized test.  A synchronized test
2102 		 * is also performed after we lock the buffer.
2103 		 */
2104 		if (bp->b_refs)
2105 			continue;
2106 
2107 		/*
2108 		 * If we are defragging then we need a buffer with
2109 		 * b_kvasize != 0.  XXX this situation should no longer
2110 		 * occur, if defrag is non-zero the buffer's b_kvasize
2111 		 * should also be non-zero at this point.  XXX
2112 		 */
2113 		if (defrag && bp->b_kvasize == 0) {
2114 			kprintf("Warning: defrag empty buffer %p\n", bp);
2115 			continue;
2116 		}
2117 
2118 		/*
2119 		 * Start freeing the bp.  This is somewhat involved.  nbp
2120 		 * remains valid only for BQUEUE_EMPTY[KVA] bp's.  Buffers
2121 		 * on the clean list must be disassociated from their
2122 		 * current vnode.  Buffers on the empty[kva] lists have
2123 		 * already been disassociated.
2124 		 *
2125 		 * b_refs is checked after locking along with queue changes.
2126 		 * We must check here to deal with zero->nonzero transitions
2127 		 * made by the owner of the buffer lock, which is used by
2128 		 * VFS's to hold the buffer while issuing an unlocked
2129 		 * uiomove()s.  We cannot invalidate the buffer's pages
2130 		 * for this case.  Once we successfully lock a buffer the
2131 		 * only 0->1 transitions of b_refs will occur via findblk().
2132 		 *
2133 		 * We must also check for queue changes after successful
2134 		 * locking as the current lock holder may dispose of the
2135 		 * buffer and change its queue.
2136 		 */
2137 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2138 			spin_unlock(&bufqspin);
2139 			tsleep(&bd_request, 0, "gnbxxx", (hz + 99) / 100);
2140 			goto restart;
2141 		}
2142 		if (bp->b_qindex != qindex || bp->b_refs) {
2143 			spin_unlock(&bufqspin);
2144 			BUF_UNLOCK(bp);
2145 			goto restart;
2146 		}
2147 		bremfree_locked(bp);
2148 		spin_unlock(&bufqspin);
2149 
2150 		/*
2151 		 * Dependancies must be handled before we disassociate the
2152 		 * vnode.
2153 		 *
2154 		 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2155 		 * be immediately disassociated.  HAMMER then becomes
2156 		 * responsible for releasing the buffer.
2157 		 *
2158 		 * NOTE: bufqspin is UNLOCKED now.
2159 		 */
2160 		if (LIST_FIRST(&bp->b_dep) != NULL) {
2161 			buf_deallocate(bp);
2162 			if (bp->b_flags & B_LOCKED) {
2163 				bqrelse(bp);
2164 				goto restart;
2165 			}
2166 			KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2167 		}
2168 
2169 		if (qindex == BQUEUE_CLEAN) {
2170 			if (bp->b_flags & B_VMIO)
2171 				vfs_vmio_release(bp);
2172 			if (bp->b_vp)
2173 				brelvp(bp);
2174 		}
2175 
2176 		/*
2177 		 * NOTE:  nbp is now entirely invalid.  We can only restart
2178 		 * the scan from this point on.
2179 		 *
2180 		 * Get the rest of the buffer freed up.  b_kva* is still
2181 		 * valid after this operation.
2182 		 */
2183 		KASSERT(bp->b_vp == NULL,
2184 			("bp3 %p flags %08x vnode %p qindex %d "
2185 			 "unexpectededly still associated!",
2186 			 bp, bp->b_flags, bp->b_vp, qindex));
2187 		KKASSERT((bp->b_flags & B_HASHED) == 0);
2188 
2189 		/*
2190 		 * critical section protection is not required when
2191 		 * scrapping a buffer's contents because it is already
2192 		 * wired.
2193 		 */
2194 		if (bp->b_bufsize)
2195 			allocbuf(bp, 0);
2196 
2197 		bp->b_flags = B_BNOCLIP;
2198 		bp->b_cmd = BUF_CMD_DONE;
2199 		bp->b_vp = NULL;
2200 		bp->b_error = 0;
2201 		bp->b_resid = 0;
2202 		bp->b_bcount = 0;
2203 		bp->b_xio.xio_npages = 0;
2204 		bp->b_dirtyoff = bp->b_dirtyend = 0;
2205 		bp->b_act_count = ACT_INIT;
2206 		reinitbufbio(bp);
2207 		KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2208 		buf_dep_init(bp);
2209 		if (blkflags & GETBLK_BHEAVY)
2210 			bp->b_flags |= B_HEAVY;
2211 
2212 		/*
2213 		 * If we are defragging then free the buffer.
2214 		 */
2215 		if (defrag) {
2216 			bp->b_flags |= B_INVAL;
2217 			bfreekva(bp);
2218 			brelse(bp);
2219 			defrag = 0;
2220 			goto restart;
2221 		}
2222 
2223 		/*
2224 		 * If we are overcomitted then recover the buffer and its
2225 		 * KVM space.  This occurs in rare situations when multiple
2226 		 * processes are blocked in getnewbuf() or allocbuf().
2227 		 */
2228 		if (bufspace >= hibufspace)
2229 			flushingbufs = 1;
2230 		if (flushingbufs && bp->b_kvasize != 0) {
2231 			bp->b_flags |= B_INVAL;
2232 			bfreekva(bp);
2233 			brelse(bp);
2234 			goto restart;
2235 		}
2236 		if (bufspace < lobufspace)
2237 			flushingbufs = 0;
2238 
2239 		/*
2240 		 * b_refs can transition to a non-zero value while we hold
2241 		 * the buffer locked due to a findblk().  Our brelvp() above
2242 		 * interlocked any future possible transitions due to
2243 		 * findblk()s.
2244 		 *
2245 		 * If we find b_refs to be non-zero we can destroy the
2246 		 * buffer's contents but we cannot yet reuse the buffer.
2247 		 */
2248 		if (bp->b_refs) {
2249 			bp->b_flags |= B_INVAL;
2250 			bfreekva(bp);
2251 			brelse(bp);
2252 			goto restart;
2253 		}
2254 		break;
2255 		/* NOT REACHED, bufqspin not held */
2256 	}
2257 
2258 	/*
2259 	 * If we exhausted our list, sleep as appropriate.  We may have to
2260 	 * wakeup various daemons and write out some dirty buffers.
2261 	 *
2262 	 * Generally we are sleeping due to insufficient buffer space.
2263 	 *
2264 	 * NOTE: bufqspin is held if bp is NULL, else it is not held.
2265 	 */
2266 	if (bp == NULL) {
2267 		int flags;
2268 		char *waitmsg;
2269 
2270 		spin_unlock(&bufqspin);
2271 		if (defrag) {
2272 			flags = VFS_BIO_NEED_BUFSPACE;
2273 			waitmsg = "nbufkv";
2274 		} else if (bufspace >= hibufspace) {
2275 			waitmsg = "nbufbs";
2276 			flags = VFS_BIO_NEED_BUFSPACE;
2277 		} else {
2278 			waitmsg = "newbuf";
2279 			flags = VFS_BIO_NEED_ANY;
2280 		}
2281 
2282 		bd_speedup();	/* heeeelp */
2283 		spin_lock(&bufcspin);
2284 		needsbuffer |= flags;
2285 		while (needsbuffer & flags) {
2286 			if (ssleep(&needsbuffer, &bufcspin,
2287 				   slpflags, waitmsg, slptimeo)) {
2288 				spin_unlock(&bufcspin);
2289 				return (NULL);
2290 			}
2291 		}
2292 		spin_unlock(&bufcspin);
2293 	} else {
2294 		/*
2295 		 * We finally have a valid bp.  We aren't quite out of the
2296 		 * woods, we still have to reserve kva space.  In order
2297 		 * to keep fragmentation sane we only allocate kva in
2298 		 * BKVASIZE chunks.
2299 		 *
2300 		 * (bufqspin is not held)
2301 		 */
2302 		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2303 
2304 		if (maxsize != bp->b_kvasize) {
2305 			vm_offset_t addr = 0;
2306 			int count;
2307 
2308 			bfreekva(bp);
2309 
2310 			count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2311 			vm_map_lock(&buffer_map);
2312 
2313 			if (vm_map_findspace(&buffer_map,
2314 				    vm_map_min(&buffer_map), maxsize,
2315 				    maxsize, 0, &addr)) {
2316 				/*
2317 				 * Uh oh.  Buffer map is too fragmented.  We
2318 				 * must defragment the map.
2319 				 */
2320 				vm_map_unlock(&buffer_map);
2321 				vm_map_entry_release(count);
2322 				++bufdefragcnt;
2323 				defrag = 1;
2324 				bp->b_flags |= B_INVAL;
2325 				brelse(bp);
2326 				goto restart;
2327 			}
2328 			if (addr) {
2329 				vm_map_insert(&buffer_map, &count,
2330 					NULL, 0,
2331 					addr, addr + maxsize,
2332 					VM_MAPTYPE_NORMAL,
2333 					VM_PROT_ALL, VM_PROT_ALL,
2334 					MAP_NOFAULT);
2335 
2336 				bp->b_kvabase = (caddr_t) addr;
2337 				bp->b_kvasize = maxsize;
2338 				bufspace += bp->b_kvasize;
2339 				++bufreusecnt;
2340 			}
2341 			vm_map_unlock(&buffer_map);
2342 			vm_map_entry_release(count);
2343 		}
2344 		bp->b_data = bp->b_kvabase;
2345 	}
2346 	return(bp);
2347 }
2348 
2349 /*
2350  * This routine is called in an emergency to recover VM pages from the
2351  * buffer cache by cashing in clean buffers.  The idea is to recover
2352  * enough pages to be able to satisfy a stuck bio_page_alloc().
2353  *
2354  * MPSAFE
2355  */
2356 static int
2357 recoverbufpages(void)
2358 {
2359 	struct buf *bp;
2360 	int bytes = 0;
2361 
2362 	++recoverbufcalls;
2363 
2364 	spin_lock(&bufqspin);
2365 	while (bytes < MAXBSIZE) {
2366 		bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2367 		if (bp == NULL)
2368 			break;
2369 
2370 		/*
2371 		 * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
2372 		 * cycles through the queue twice before being selected.
2373 		 */
2374 		if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
2375 			bp->b_flags |= B_AGE;
2376 			TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
2377 			TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
2378 					  bp, b_freelist);
2379 			continue;
2380 		}
2381 
2382 		/*
2383 		 * Sanity Checks
2384 		 */
2385 		KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
2386 		KKASSERT((bp->b_flags & B_DELWRI) == 0);
2387 
2388 		/*
2389 		 * Start freeing the bp.  This is somewhat involved.
2390 		 *
2391 		 * Buffers on the clean list must be disassociated from
2392 		 * their current vnode
2393 		 */
2394 
2395 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2396 			kprintf("recoverbufpages: warning, locked buf %p, "
2397 				"race corrected\n",
2398 				bp);
2399 			ssleep(&bd_request, &bufqspin, 0, "gnbxxx", hz / 100);
2400 			continue;
2401 		}
2402 		if (bp->b_qindex != BQUEUE_CLEAN) {
2403 			kprintf("recoverbufpages: warning, BUF_LOCK blocked "
2404 				"unexpectedly on buf %p index %d, race "
2405 				"corrected\n",
2406 				bp, bp->b_qindex);
2407 			BUF_UNLOCK(bp);
2408 			continue;
2409 		}
2410 		bremfree_locked(bp);
2411 		spin_unlock(&bufqspin);
2412 
2413 		/*
2414 		 * Dependancies must be handled before we disassociate the
2415 		 * vnode.
2416 		 *
2417 		 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2418 		 * be immediately disassociated.  HAMMER then becomes
2419 		 * responsible for releasing the buffer.
2420 		 */
2421 		if (LIST_FIRST(&bp->b_dep) != NULL) {
2422 			buf_deallocate(bp);
2423 			if (bp->b_flags & B_LOCKED) {
2424 				bqrelse(bp);
2425 				spin_lock(&bufqspin);
2426 				continue;
2427 			}
2428 			KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2429 		}
2430 
2431 		bytes += bp->b_bufsize;
2432 
2433 		if (bp->b_flags & B_VMIO) {
2434 			bp->b_flags |= B_DIRECT;    /* try to free pages */
2435 			vfs_vmio_release(bp);
2436 		}
2437 		if (bp->b_vp)
2438 			brelvp(bp);
2439 
2440 		KKASSERT(bp->b_vp == NULL);
2441 		KKASSERT((bp->b_flags & B_HASHED) == 0);
2442 
2443 		/*
2444 		 * critical section protection is not required when
2445 		 * scrapping a buffer's contents because it is already
2446 		 * wired.
2447 		 */
2448 		if (bp->b_bufsize)
2449 			allocbuf(bp, 0);
2450 
2451 		bp->b_flags = B_BNOCLIP;
2452 		bp->b_cmd = BUF_CMD_DONE;
2453 		bp->b_vp = NULL;
2454 		bp->b_error = 0;
2455 		bp->b_resid = 0;
2456 		bp->b_bcount = 0;
2457 		bp->b_xio.xio_npages = 0;
2458 		bp->b_dirtyoff = bp->b_dirtyend = 0;
2459 		reinitbufbio(bp);
2460 		KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2461 		buf_dep_init(bp);
2462 		bp->b_flags |= B_INVAL;
2463 		/* bfreekva(bp); */
2464 		brelse(bp);
2465 		spin_lock(&bufqspin);
2466 	}
2467 	spin_unlock(&bufqspin);
2468 	return(bytes);
2469 }
2470 
2471 /*
2472  * buf_daemon:
2473  *
2474  *	Buffer flushing daemon.  Buffers are normally flushed by the
2475  *	update daemon but if it cannot keep up this process starts to
2476  *	take the load in an attempt to prevent getnewbuf() from blocking.
2477  *
2478  *	Once a flush is initiated it does not stop until the number
2479  *	of buffers falls below lodirtybuffers, but we will wake up anyone
2480  *	waiting at the mid-point.
2481  */
2482 
2483 static struct kproc_desc buf_kp = {
2484 	"bufdaemon",
2485 	buf_daemon,
2486 	&bufdaemon_td
2487 };
2488 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2489 	kproc_start, &buf_kp)
2490 
2491 static struct kproc_desc bufhw_kp = {
2492 	"bufdaemon_hw",
2493 	buf_daemon_hw,
2494 	&bufdaemonhw_td
2495 };
2496 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2497 	kproc_start, &bufhw_kp)
2498 
2499 /*
2500  * MPSAFE thread
2501  */
2502 static void
2503 buf_daemon1(struct thread *td, int queue, int (*buf_limit_fn)(long),
2504 	    int *bd_req)
2505 {
2506 	long limit;
2507 
2508 	/*
2509 	 * This process needs to be suspended prior to shutdown sync.
2510 	 */
2511 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2512 			      td, SHUTDOWN_PRI_LAST);
2513 	curthread->td_flags |= TDF_SYSTHREAD;
2514 
2515 	/*
2516 	 * This process is allowed to take the buffer cache to the limit
2517 	 */
2518 	for (;;) {
2519 		kproc_suspend_loop();
2520 
2521 		/*
2522 		 * Do the flush as long as the number of dirty buffers
2523 		 * (including those running) exceeds lodirtybufspace.
2524 		 *
2525 		 * When flushing limit running I/O to hirunningspace
2526 		 * Do the flush.  Limit the amount of in-transit I/O we
2527 		 * allow to build up, otherwise we would completely saturate
2528 		 * the I/O system.  Wakeup any waiting processes before we
2529 		 * normally would so they can run in parallel with our drain.
2530 		 *
2531 		 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2532 		 * but because we split the operation into two threads we
2533 		 * have to cut it in half for each thread.
2534 		 */
2535 		waitrunningbufspace();
2536 		limit = lodirtybufspace / 2;
2537 		while (buf_limit_fn(limit)) {
2538 			if (flushbufqueues(queue) == 0)
2539 				break;
2540 			if (runningbufspace < hirunningspace)
2541 				continue;
2542 			waitrunningbufspace();
2543 		}
2544 
2545 		/*
2546 		 * We reached our low water mark, reset the
2547 		 * request and sleep until we are needed again.
2548 		 * The sleep is just so the suspend code works.
2549 		 */
2550 		spin_lock(&bufcspin);
2551 		if (*bd_req == 0)
2552 			ssleep(bd_req, &bufcspin, 0, "psleep", hz);
2553 		*bd_req = 0;
2554 		spin_unlock(&bufcspin);
2555 	}
2556 }
2557 
2558 static int
2559 buf_daemon_limit(long limit)
2560 {
2561 	return (runningbufspace + dirtybufspace > limit ||
2562 		dirtybufcount - dirtybufcounthw >= nbuf / 2);
2563 }
2564 
2565 static int
2566 buf_daemon_hw_limit(long limit)
2567 {
2568 	return (runningbufspace + dirtybufspacehw > limit ||
2569 		dirtybufcounthw >= nbuf / 2);
2570 }
2571 
2572 static void
2573 buf_daemon(void)
2574 {
2575 	buf_daemon1(bufdaemon_td, BQUEUE_DIRTY, buf_daemon_limit,
2576 		    &bd_request);
2577 }
2578 
2579 static void
2580 buf_daemon_hw(void)
2581 {
2582 	buf_daemon1(bufdaemonhw_td, BQUEUE_DIRTY_HW, buf_daemon_hw_limit,
2583 		    &bd_request_hw);
2584 }
2585 
2586 /*
2587  * flushbufqueues:
2588  *
2589  *	Try to flush a buffer in the dirty queue.  We must be careful to
2590  *	free up B_INVAL buffers instead of write them, which NFS is
2591  *	particularly sensitive to.
2592  *
2593  *	B_RELBUF may only be set by VFSs.  We do set B_AGE to indicate
2594  *	that we really want to try to get the buffer out and reuse it
2595  *	due to the write load on the machine.
2596  *
2597  *	We must lock the buffer in order to check its validity before we
2598  *	can mess with its contents.  bufqspin isn't enough.
2599  */
2600 static int
2601 flushbufqueues(bufq_type_t q)
2602 {
2603 	struct buf *bp;
2604 	int r = 0;
2605 	int spun;
2606 
2607 	spin_lock(&bufqspin);
2608 	spun = 1;
2609 
2610 	bp = TAILQ_FIRST(&bufqueues[q]);
2611 	while (bp) {
2612 		if ((bp->b_flags & B_DELWRI) == 0) {
2613 			kprintf("Unexpected clean buffer %p\n", bp);
2614 			bp = TAILQ_NEXT(bp, b_freelist);
2615 			continue;
2616 		}
2617 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2618 			bp = TAILQ_NEXT(bp, b_freelist);
2619 			continue;
2620 		}
2621 		KKASSERT(bp->b_qindex == q);
2622 
2623 		/*
2624 		 * Must recheck B_DELWRI after successfully locking
2625 		 * the buffer.
2626 		 */
2627 		if ((bp->b_flags & B_DELWRI) == 0) {
2628 			BUF_UNLOCK(bp);
2629 			bp = TAILQ_NEXT(bp, b_freelist);
2630 			continue;
2631 		}
2632 
2633 		if (bp->b_flags & B_INVAL) {
2634 			_bremfree(bp);
2635 			spin_unlock(&bufqspin);
2636 			spun = 0;
2637 			brelse(bp);
2638 			++r;
2639 			break;
2640 		}
2641 
2642 		spin_unlock(&bufqspin);
2643 		lwkt_yield();
2644 		spun = 0;
2645 
2646 		if (LIST_FIRST(&bp->b_dep) != NULL &&
2647 		    (bp->b_flags & B_DEFERRED) == 0 &&
2648 		    buf_countdeps(bp, 0)) {
2649 			spin_lock(&bufqspin);
2650 			spun = 1;
2651 			TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2652 			TAILQ_INSERT_TAIL(&bufqueues[q], bp, b_freelist);
2653 			bp->b_flags |= B_DEFERRED;
2654 			BUF_UNLOCK(bp);
2655 			bp = TAILQ_FIRST(&bufqueues[q]);
2656 			continue;
2657 		}
2658 
2659 		/*
2660 		 * If the buffer has a dependancy, buf_checkwrite() must
2661 		 * also return 0 for us to be able to initate the write.
2662 		 *
2663 		 * If the buffer is flagged B_ERROR it may be requeued
2664 		 * over and over again, we try to avoid a live lock.
2665 		 *
2666 		 * NOTE: buf_checkwrite is MPSAFE.
2667 		 */
2668 		if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
2669 			bremfree(bp);
2670 			brelse(bp);
2671 		} else if (bp->b_flags & B_ERROR) {
2672 			tsleep(bp, 0, "bioer", 1);
2673 			bp->b_flags &= ~B_AGE;
2674 			vfs_bio_awrite(bp);
2675 		} else {
2676 			bp->b_flags |= B_AGE;
2677 			vfs_bio_awrite(bp);
2678 		}
2679 		++r;
2680 		break;
2681 	}
2682 	if (spun)
2683 		spin_unlock(&bufqspin);
2684 	return (r);
2685 }
2686 
2687 /*
2688  * inmem:
2689  *
2690  *	Returns true if no I/O is needed to access the associated VM object.
2691  *	This is like findblk except it also hunts around in the VM system for
2692  *	the data.
2693  *
2694  *	Note that we ignore vm_page_free() races from interrupts against our
2695  *	lookup, since if the caller is not protected our return value will not
2696  *	be any more valid then otherwise once we exit the critical section.
2697  */
2698 int
2699 inmem(struct vnode *vp, off_t loffset)
2700 {
2701 	vm_object_t obj;
2702 	vm_offset_t toff, tinc, size;
2703 	vm_page_t m;
2704 	int res = 1;
2705 
2706 	if (findblk(vp, loffset, FINDBLK_TEST))
2707 		return 1;
2708 	if (vp->v_mount == NULL)
2709 		return 0;
2710 	if ((obj = vp->v_object) == NULL)
2711 		return 0;
2712 
2713 	size = PAGE_SIZE;
2714 	if (size > vp->v_mount->mnt_stat.f_iosize)
2715 		size = vp->v_mount->mnt_stat.f_iosize;
2716 
2717 	vm_object_hold(obj);
2718 	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2719 		m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2720 		if (m == NULL) {
2721 			res = 0;
2722 			break;
2723 		}
2724 		tinc = size;
2725 		if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2726 			tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2727 		if (vm_page_is_valid(m,
2728 		    (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0) {
2729 			res = 0;
2730 			break;
2731 		}
2732 	}
2733 	vm_object_drop(obj);
2734 	return (res);
2735 }
2736 
2737 /*
2738  * findblk:
2739  *
2740  *	Locate and return the specified buffer.  Unless flagged otherwise,
2741  *	a locked buffer will be returned if it exists or NULL if it does not.
2742  *
2743  *	findblk()'d buffers are still on the bufqueues and if you intend
2744  *	to use your (locked NON-TEST) buffer you need to bremfree(bp)
2745  *	and possibly do other stuff to it.
2746  *
2747  *	FINDBLK_TEST	- Do not lock the buffer.  The caller is responsible
2748  *			  for locking the buffer and ensuring that it remains
2749  *			  the desired buffer after locking.
2750  *
2751  *	FINDBLK_NBLOCK	- Lock the buffer non-blocking.  If we are unable
2752  *			  to acquire the lock we return NULL, even if the
2753  *			  buffer exists.
2754  *
2755  *	FINDBLK_REF	- Returns the buffer ref'd, which prevents normal
2756  *			  reuse by getnewbuf() but does not prevent
2757  *			  disassociation (B_INVAL).  Used to avoid deadlocks
2758  *			  against random (vp,loffset)s due to reassignment.
2759  *
2760  *	(0)		- Lock the buffer blocking.
2761  *
2762  * MPSAFE
2763  */
2764 struct buf *
2765 findblk(struct vnode *vp, off_t loffset, int flags)
2766 {
2767 	struct buf *bp;
2768 	int lkflags;
2769 
2770 	lkflags = LK_EXCLUSIVE;
2771 	if (flags & FINDBLK_NBLOCK)
2772 		lkflags |= LK_NOWAIT;
2773 
2774 	for (;;) {
2775 		/*
2776 		 * Lookup.  Ref the buf while holding v_token to prevent
2777 		 * reuse (but does not prevent diassociation).
2778 		 */
2779 		lwkt_gettoken_shared(&vp->v_token);
2780 		bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2781 		if (bp == NULL) {
2782 			lwkt_reltoken(&vp->v_token);
2783 			return(NULL);
2784 		}
2785 		bqhold(bp);
2786 		lwkt_reltoken(&vp->v_token);
2787 
2788 		/*
2789 		 * If testing only break and return bp, do not lock.
2790 		 */
2791 		if (flags & FINDBLK_TEST)
2792 			break;
2793 
2794 		/*
2795 		 * Lock the buffer, return an error if the lock fails.
2796 		 * (only FINDBLK_NBLOCK can cause the lock to fail).
2797 		 */
2798 		if (BUF_LOCK(bp, lkflags)) {
2799 			atomic_subtract_int(&bp->b_refs, 1);
2800 			/* bp = NULL; not needed */
2801 			return(NULL);
2802 		}
2803 
2804 		/*
2805 		 * Revalidate the locked buf before allowing it to be
2806 		 * returned.
2807 		 */
2808 		if (bp->b_vp == vp && bp->b_loffset == loffset)
2809 			break;
2810 		atomic_subtract_int(&bp->b_refs, 1);
2811 		BUF_UNLOCK(bp);
2812 	}
2813 
2814 	/*
2815 	 * Success
2816 	 */
2817 	if ((flags & FINDBLK_REF) == 0)
2818 		atomic_subtract_int(&bp->b_refs, 1);
2819 	return(bp);
2820 }
2821 
2822 /*
2823  * getcacheblk:
2824  *
2825  *	Similar to getblk() except only returns the buffer if it is
2826  *	B_CACHE and requires no other manipulation.  Otherwise NULL
2827  *	is returned.
2828  *
2829  *	If B_RAM is set the buffer might be just fine, but we return
2830  *	NULL anyway because we want the code to fall through to the
2831  *	cluster read.  Otherwise read-ahead breaks.
2832  *
2833  *	If blksize is 0 the buffer cache buffer must already be fully
2834  *	cached.
2835  *
2836  *	If blksize is non-zero getblk() will be used, allowing a buffer
2837  *	to be reinstantiated from its VM backing store.  The buffer must
2838  *	still be fully cached after reinstantiation to be returned.
2839  */
2840 struct buf *
2841 getcacheblk(struct vnode *vp, off_t loffset, int blksize)
2842 {
2843 	struct buf *bp;
2844 
2845 	if (blksize) {
2846 		bp = getblk(vp, loffset, blksize, 0, 0);
2847 		if (bp) {
2848 			if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2849 			    B_CACHE) {
2850 				bp->b_flags &= ~B_AGE;
2851 			} else {
2852 				brelse(bp);
2853 				bp = NULL;
2854 			}
2855 		}
2856 	} else {
2857 		bp = findblk(vp, loffset, 0);
2858 		if (bp) {
2859 			if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2860 			    B_CACHE) {
2861 				bp->b_flags &= ~B_AGE;
2862 				bremfree(bp);
2863 			} else {
2864 				BUF_UNLOCK(bp);
2865 				bp = NULL;
2866 			}
2867 		}
2868 	}
2869 	return (bp);
2870 }
2871 
2872 /*
2873  * getblk:
2874  *
2875  *	Get a block given a specified block and offset into a file/device.
2876  * 	B_INVAL may or may not be set on return.  The caller should clear
2877  *	B_INVAL prior to initiating a READ.
2878  *
2879  *	IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2880  *	IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2881  *	OR SET B_INVAL BEFORE RETIRING IT.  If you retire a getblk'd buffer
2882  *	without doing any of those things the system will likely believe
2883  *	the buffer to be valid (especially if it is not B_VMIO), and the
2884  *	next getblk() will return the buffer with B_CACHE set.
2885  *
2886  *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2887  *	an existing buffer.
2888  *
2889  *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2890  *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2891  *	and then cleared based on the backing VM.  If the previous buffer is
2892  *	non-0-sized but invalid, B_CACHE will be cleared.
2893  *
2894  *	If getblk() must create a new buffer, the new buffer is returned with
2895  *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2896  *	case it is returned with B_INVAL clear and B_CACHE set based on the
2897  *	backing VM.
2898  *
2899  *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2900  *	B_CACHE bit is clear.
2901  *
2902  *	What this means, basically, is that the caller should use B_CACHE to
2903  *	determine whether the buffer is fully valid or not and should clear
2904  *	B_INVAL prior to issuing a read.  If the caller intends to validate
2905  *	the buffer by loading its data area with something, the caller needs
2906  *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2907  *	the caller should set B_CACHE ( as an optimization ), else the caller
2908  *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2909  *	a write attempt or if it was a successfull read.  If the caller
2910  *	intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2911  *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2912  *
2913  *	getblk flags:
2914  *
2915  *	GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2916  *	GETBLK_BHEAVY - heavy-weight buffer cache buffer
2917  *
2918  * MPALMOSTSAFE
2919  */
2920 struct buf *
2921 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2922 {
2923 	struct buf *bp;
2924 	int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2925 	int error;
2926 	int lkflags;
2927 
2928 	if (size > MAXBSIZE)
2929 		panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2930 	if (vp->v_object == NULL)
2931 		panic("getblk: vnode %p has no object!", vp);
2932 
2933 loop:
2934 	if ((bp = findblk(vp, loffset, FINDBLK_REF | FINDBLK_TEST)) != NULL) {
2935 		/*
2936 		 * The buffer was found in the cache, but we need to lock it.
2937 		 * We must acquire a ref on the bp to prevent reuse, but
2938 		 * this will not prevent disassociation (brelvp()) so we
2939 		 * must recheck (vp,loffset) after acquiring the lock.
2940 		 *
2941 		 * Without the ref the buffer could potentially be reused
2942 		 * before we acquire the lock and create a deadlock
2943 		 * situation between the thread trying to reuse the buffer
2944 		 * and us due to the fact that we would wind up blocking
2945 		 * on a random (vp,loffset).
2946 		 */
2947 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2948 			if (blkflags & GETBLK_NOWAIT) {
2949 				bqdrop(bp);
2950 				return(NULL);
2951 			}
2952 			lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2953 			if (blkflags & GETBLK_PCATCH)
2954 				lkflags |= LK_PCATCH;
2955 			error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2956 			if (error) {
2957 				bqdrop(bp);
2958 				if (error == ENOLCK)
2959 					goto loop;
2960 				return (NULL);
2961 			}
2962 			/* buffer may have changed on us */
2963 		}
2964 		bqdrop(bp);
2965 
2966 		/*
2967 		 * Once the buffer has been locked, make sure we didn't race
2968 		 * a buffer recyclement.  Buffers that are no longer hashed
2969 		 * will have b_vp == NULL, so this takes care of that check
2970 		 * as well.
2971 		 */
2972 		if (bp->b_vp != vp || bp->b_loffset != loffset) {
2973 			kprintf("Warning buffer %p (vp %p loffset %lld) "
2974 				"was recycled\n",
2975 				bp, vp, (long long)loffset);
2976 			BUF_UNLOCK(bp);
2977 			goto loop;
2978 		}
2979 
2980 		/*
2981 		 * If SZMATCH any pre-existing buffer must be of the requested
2982 		 * size or NULL is returned.  The caller absolutely does not
2983 		 * want getblk() to bwrite() the buffer on a size mismatch.
2984 		 */
2985 		if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2986 			BUF_UNLOCK(bp);
2987 			return(NULL);
2988 		}
2989 
2990 		/*
2991 		 * All vnode-based buffers must be backed by a VM object.
2992 		 */
2993 		KKASSERT(bp->b_flags & B_VMIO);
2994 		KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2995 		bp->b_flags &= ~B_AGE;
2996 
2997 		/*
2998 		 * Make sure that B_INVAL buffers do not have a cached
2999 		 * block number translation.
3000 		 */
3001 		if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
3002 			kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
3003 				" did not have cleared bio_offset cache\n",
3004 				bp, vp, (long long)loffset);
3005 			clearbiocache(&bp->b_bio2);
3006 		}
3007 
3008 		/*
3009 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
3010 		 * invalid.
3011 		 */
3012 		if (bp->b_flags & B_INVAL)
3013 			bp->b_flags &= ~B_CACHE;
3014 		bremfree(bp);
3015 
3016 		/*
3017 		 * Any size inconsistancy with a dirty buffer or a buffer
3018 		 * with a softupdates dependancy must be resolved.  Resizing
3019 		 * the buffer in such circumstances can lead to problems.
3020 		 *
3021 		 * Dirty or dependant buffers are written synchronously.
3022 		 * Other types of buffers are simply released and
3023 		 * reconstituted as they may be backed by valid, dirty VM
3024 		 * pages (but not marked B_DELWRI).
3025 		 *
3026 		 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
3027 		 * and may be left over from a prior truncation (and thus
3028 		 * no longer represent the actual EOF point), so we
3029 		 * definitely do not want to B_NOCACHE the backing store.
3030 		 */
3031 		if (size != bp->b_bcount) {
3032 			if (bp->b_flags & B_DELWRI) {
3033 				bp->b_flags |= B_RELBUF;
3034 				bwrite(bp);
3035 			} else if (LIST_FIRST(&bp->b_dep)) {
3036 				bp->b_flags |= B_RELBUF;
3037 				bwrite(bp);
3038 			} else {
3039 				bp->b_flags |= B_RELBUF;
3040 				brelse(bp);
3041 			}
3042 			goto loop;
3043 		}
3044 		KKASSERT(size <= bp->b_kvasize);
3045 		KASSERT(bp->b_loffset != NOOFFSET,
3046 			("getblk: no buffer offset"));
3047 
3048 		/*
3049 		 * A buffer with B_DELWRI set and B_CACHE clear must
3050 		 * be committed before we can return the buffer in
3051 		 * order to prevent the caller from issuing a read
3052 		 * ( due to B_CACHE not being set ) and overwriting
3053 		 * it.
3054 		 *
3055 		 * Most callers, including NFS and FFS, need this to
3056 		 * operate properly either because they assume they
3057 		 * can issue a read if B_CACHE is not set, or because
3058 		 * ( for example ) an uncached B_DELWRI might loop due
3059 		 * to softupdates re-dirtying the buffer.  In the latter
3060 		 * case, B_CACHE is set after the first write completes,
3061 		 * preventing further loops.
3062 		 *
3063 		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
3064 		 * above while extending the buffer, we cannot allow the
3065 		 * buffer to remain with B_CACHE set after the write
3066 		 * completes or it will represent a corrupt state.  To
3067 		 * deal with this we set B_NOCACHE to scrap the buffer
3068 		 * after the write.
3069 		 *
3070 		 * XXX Should this be B_RELBUF instead of B_NOCACHE?
3071 		 *     I'm not even sure this state is still possible
3072 		 *     now that getblk() writes out any dirty buffers
3073 		 *     on size changes.
3074 		 *
3075 		 * We might be able to do something fancy, like setting
3076 		 * B_CACHE in bwrite() except if B_DELWRI is already set,
3077 		 * so the below call doesn't set B_CACHE, but that gets real
3078 		 * confusing.  This is much easier.
3079 		 */
3080 
3081 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3082 			kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
3083 				"and CACHE clear, b_flags %08x\n",
3084 				bp, (intmax_t)bp->b_loffset, bp->b_flags);
3085 			bp->b_flags |= B_NOCACHE;
3086 			bwrite(bp);
3087 			goto loop;
3088 		}
3089 	} else {
3090 		/*
3091 		 * Buffer is not in-core, create new buffer.  The buffer
3092 		 * returned by getnewbuf() is locked.  Note that the returned
3093 		 * buffer is also considered valid (not marked B_INVAL).
3094 		 *
3095 		 * Calculating the offset for the I/O requires figuring out
3096 		 * the block size.  We use DEV_BSIZE for VBLK or VCHR and
3097 		 * the mount's f_iosize otherwise.  If the vnode does not
3098 		 * have an associated mount we assume that the passed size is
3099 		 * the block size.
3100 		 *
3101 		 * Note that vn_isdisk() cannot be used here since it may
3102 		 * return a failure for numerous reasons.   Note that the
3103 		 * buffer size may be larger then the block size (the caller
3104 		 * will use block numbers with the proper multiple).  Beware
3105 		 * of using any v_* fields which are part of unions.  In
3106 		 * particular, in DragonFly the mount point overloading
3107 		 * mechanism uses the namecache only and the underlying
3108 		 * directory vnode is not a special case.
3109 		 */
3110 		int bsize, maxsize;
3111 
3112 		if (vp->v_type == VBLK || vp->v_type == VCHR)
3113 			bsize = DEV_BSIZE;
3114 		else if (vp->v_mount)
3115 			bsize = vp->v_mount->mnt_stat.f_iosize;
3116 		else
3117 			bsize = size;
3118 
3119 		maxsize = size + (loffset & PAGE_MASK);
3120 		maxsize = imax(maxsize, bsize);
3121 
3122 		bp = getnewbuf(blkflags, slptimeo, size, maxsize);
3123 		if (bp == NULL) {
3124 			if (slpflags || slptimeo)
3125 				return NULL;
3126 			goto loop;
3127 		}
3128 
3129 		/*
3130 		 * Atomically insert the buffer into the hash, so that it can
3131 		 * be found by findblk().
3132 		 *
3133 		 * If bgetvp() returns non-zero a collision occured, and the
3134 		 * bp will not be associated with the vnode.
3135 		 *
3136 		 * Make sure the translation layer has been cleared.
3137 		 */
3138 		bp->b_loffset = loffset;
3139 		bp->b_bio2.bio_offset = NOOFFSET;
3140 		/* bp->b_bio2.bio_next = NULL; */
3141 
3142 		if (bgetvp(vp, bp, size)) {
3143 			bp->b_flags |= B_INVAL;
3144 			brelse(bp);
3145 			goto loop;
3146 		}
3147 
3148 		/*
3149 		 * All vnode-based buffers must be backed by a VM object.
3150 		 */
3151 		KKASSERT(vp->v_object != NULL);
3152 		bp->b_flags |= B_VMIO;
3153 		KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3154 
3155 		allocbuf(bp, size);
3156 	}
3157 	KKASSERT(dsched_is_clear_buf_priv(bp));
3158 	return (bp);
3159 }
3160 
3161 /*
3162  * regetblk(bp)
3163  *
3164  * Reacquire a buffer that was previously released to the locked queue,
3165  * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3166  * set B_LOCKED (which handles the acquisition race).
3167  *
3168  * To this end, either B_LOCKED must be set or the dependancy list must be
3169  * non-empty.
3170  *
3171  * MPSAFE
3172  */
3173 void
3174 regetblk(struct buf *bp)
3175 {
3176 	KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
3177 	BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
3178 	bremfree(bp);
3179 }
3180 
3181 /*
3182  * geteblk:
3183  *
3184  *	Get an empty, disassociated buffer of given size.  The buffer is
3185  *	initially set to B_INVAL.
3186  *
3187  *	critical section protection is not required for the allocbuf()
3188  *	call because races are impossible here.
3189  *
3190  * MPALMOSTSAFE
3191  */
3192 struct buf *
3193 geteblk(int size)
3194 {
3195 	struct buf *bp;
3196 	int maxsize;
3197 
3198 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
3199 
3200 	while ((bp = getnewbuf(0, 0, size, maxsize)) == NULL)
3201 		;
3202 	allocbuf(bp, size);
3203 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
3204 	KKASSERT(dsched_is_clear_buf_priv(bp));
3205 	return (bp);
3206 }
3207 
3208 
3209 /*
3210  * allocbuf:
3211  *
3212  *	This code constitutes the buffer memory from either anonymous system
3213  *	memory (in the case of non-VMIO operations) or from an associated
3214  *	VM object (in the case of VMIO operations).  This code is able to
3215  *	resize a buffer up or down.
3216  *
3217  *	Note that this code is tricky, and has many complications to resolve
3218  *	deadlock or inconsistant data situations.  Tread lightly!!!
3219  *	There are B_CACHE and B_DELWRI interactions that must be dealt with by
3220  *	the caller.  Calling this code willy nilly can result in the loss of
3221  *	data.
3222  *
3223  *	allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
3224  *	B_CACHE for the non-VMIO case.
3225  *
3226  *	This routine does not need to be called from a critical section but you
3227  *	must own the buffer.
3228  *
3229  * MPSAFE
3230  */
3231 int
3232 allocbuf(struct buf *bp, int size)
3233 {
3234 	int newbsize, mbsize;
3235 	int i;
3236 
3237 	if (BUF_REFCNT(bp) == 0)
3238 		panic("allocbuf: buffer not busy");
3239 
3240 	if (bp->b_kvasize < size)
3241 		panic("allocbuf: buffer too small");
3242 
3243 	if ((bp->b_flags & B_VMIO) == 0) {
3244 		caddr_t origbuf;
3245 		int origbufsize;
3246 		/*
3247 		 * Just get anonymous memory from the kernel.  Don't
3248 		 * mess with B_CACHE.
3249 		 */
3250 		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3251 		if (bp->b_flags & B_MALLOC)
3252 			newbsize = mbsize;
3253 		else
3254 			newbsize = round_page(size);
3255 
3256 		if (newbsize < bp->b_bufsize) {
3257 			/*
3258 			 * Malloced buffers are not shrunk
3259 			 */
3260 			if (bp->b_flags & B_MALLOC) {
3261 				if (newbsize) {
3262 					bp->b_bcount = size;
3263 				} else {
3264 					kfree(bp->b_data, M_BIOBUF);
3265 					if (bp->b_bufsize) {
3266 						atomic_subtract_long(&bufmallocspace, bp->b_bufsize);
3267 						bufspacewakeup();
3268 						bp->b_bufsize = 0;
3269 					}
3270 					bp->b_data = bp->b_kvabase;
3271 					bp->b_bcount = 0;
3272 					bp->b_flags &= ~B_MALLOC;
3273 				}
3274 				return 1;
3275 			}
3276 			vm_hold_free_pages(
3277 			    bp,
3278 			    (vm_offset_t) bp->b_data + newbsize,
3279 			    (vm_offset_t) bp->b_data + bp->b_bufsize);
3280 		} else if (newbsize > bp->b_bufsize) {
3281 			/*
3282 			 * We only use malloced memory on the first allocation.
3283 			 * and revert to page-allocated memory when the buffer
3284 			 * grows.
3285 			 */
3286 			if ((bufmallocspace < maxbufmallocspace) &&
3287 				(bp->b_bufsize == 0) &&
3288 				(mbsize <= PAGE_SIZE/2)) {
3289 
3290 				bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3291 				bp->b_bufsize = mbsize;
3292 				bp->b_bcount = size;
3293 				bp->b_flags |= B_MALLOC;
3294 				atomic_add_long(&bufmallocspace, mbsize);
3295 				return 1;
3296 			}
3297 			origbuf = NULL;
3298 			origbufsize = 0;
3299 			/*
3300 			 * If the buffer is growing on its other-than-first
3301 			 * allocation, then we revert to the page-allocation
3302 			 * scheme.
3303 			 */
3304 			if (bp->b_flags & B_MALLOC) {
3305 				origbuf = bp->b_data;
3306 				origbufsize = bp->b_bufsize;
3307 				bp->b_data = bp->b_kvabase;
3308 				if (bp->b_bufsize) {
3309 					atomic_subtract_long(&bufmallocspace,
3310 							     bp->b_bufsize);
3311 					bufspacewakeup();
3312 					bp->b_bufsize = 0;
3313 				}
3314 				bp->b_flags &= ~B_MALLOC;
3315 				newbsize = round_page(newbsize);
3316 			}
3317 			vm_hold_load_pages(
3318 			    bp,
3319 			    (vm_offset_t) bp->b_data + bp->b_bufsize,
3320 			    (vm_offset_t) bp->b_data + newbsize);
3321 			if (origbuf) {
3322 				bcopy(origbuf, bp->b_data, origbufsize);
3323 				kfree(origbuf, M_BIOBUF);
3324 			}
3325 		}
3326 	} else {
3327 		vm_page_t m;
3328 		int desiredpages;
3329 
3330 		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3331 		desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3332 				newbsize + PAGE_MASK) >> PAGE_SHIFT;
3333 		KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3334 
3335 		if (bp->b_flags & B_MALLOC)
3336 			panic("allocbuf: VMIO buffer can't be malloced");
3337 		/*
3338 		 * Set B_CACHE initially if buffer is 0 length or will become
3339 		 * 0-length.
3340 		 */
3341 		if (size == 0 || bp->b_bufsize == 0)
3342 			bp->b_flags |= B_CACHE;
3343 
3344 		if (newbsize < bp->b_bufsize) {
3345 			/*
3346 			 * DEV_BSIZE aligned new buffer size is less then the
3347 			 * DEV_BSIZE aligned existing buffer size.  Figure out
3348 			 * if we have to remove any pages.
3349 			 */
3350 			if (desiredpages < bp->b_xio.xio_npages) {
3351 				for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3352 					/*
3353 					 * the page is not freed here -- it
3354 					 * is the responsibility of
3355 					 * vnode_pager_setsize
3356 					 */
3357 					m = bp->b_xio.xio_pages[i];
3358 					KASSERT(m != bogus_page,
3359 					    ("allocbuf: bogus page found"));
3360 					vm_page_busy_wait(m, TRUE, "biodep");
3361 					bp->b_xio.xio_pages[i] = NULL;
3362 					vm_page_unwire(m, 0);
3363 					vm_page_wakeup(m);
3364 				}
3365 				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3366 				    (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3367 				bp->b_xio.xio_npages = desiredpages;
3368 			}
3369 		} else if (size > bp->b_bcount) {
3370 			/*
3371 			 * We are growing the buffer, possibly in a
3372 			 * byte-granular fashion.
3373 			 */
3374 			struct vnode *vp;
3375 			vm_object_t obj;
3376 			vm_offset_t toff;
3377 			vm_offset_t tinc;
3378 
3379 			/*
3380 			 * Step 1, bring in the VM pages from the object,
3381 			 * allocating them if necessary.  We must clear
3382 			 * B_CACHE if these pages are not valid for the
3383 			 * range covered by the buffer.
3384 			 *
3385 			 * critical section protection is required to protect
3386 			 * against interrupts unbusying and freeing pages
3387 			 * between our vm_page_lookup() and our
3388 			 * busycheck/wiring call.
3389 			 */
3390 			vp = bp->b_vp;
3391 			obj = vp->v_object;
3392 
3393 			vm_object_hold(obj);
3394 			while (bp->b_xio.xio_npages < desiredpages) {
3395 				vm_page_t m;
3396 				vm_pindex_t pi;
3397 				int error;
3398 
3399 				pi = OFF_TO_IDX(bp->b_loffset) +
3400 				     bp->b_xio.xio_npages;
3401 
3402 				/*
3403 				 * Blocking on m->busy might lead to a
3404 				 * deadlock:
3405 				 *
3406 				 *  vm_fault->getpages->cluster_read->allocbuf
3407 				 */
3408 				m = vm_page_lookup_busy_try(obj, pi, FALSE,
3409 							    &error);
3410 				if (error) {
3411 					vm_page_sleep_busy(m, FALSE, "pgtblk");
3412 					continue;
3413 				}
3414 				if (m == NULL) {
3415 					/*
3416 					 * note: must allocate system pages
3417 					 * since blocking here could intefere
3418 					 * with paging I/O, no matter which
3419 					 * process we are.
3420 					 */
3421 					m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
3422 					if (m) {
3423 						vm_page_wire(m);
3424 						vm_page_flag_clear(m, PG_ZERO);
3425 						vm_page_wakeup(m);
3426 						bp->b_flags &= ~B_CACHE;
3427 						bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3428 						++bp->b_xio.xio_npages;
3429 					}
3430 					continue;
3431 				}
3432 
3433 				/*
3434 				 * We found a page and were able to busy it.
3435 				 */
3436 				vm_page_flag_clear(m, PG_ZERO);
3437 				vm_page_wire(m);
3438 				vm_page_wakeup(m);
3439 				bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3440 				++bp->b_xio.xio_npages;
3441 				if (bp->b_act_count < m->act_count)
3442 					bp->b_act_count = m->act_count;
3443 			}
3444 			vm_object_drop(obj);
3445 
3446 			/*
3447 			 * Step 2.  We've loaded the pages into the buffer,
3448 			 * we have to figure out if we can still have B_CACHE
3449 			 * set.  Note that B_CACHE is set according to the
3450 			 * byte-granular range ( bcount and size ), not the
3451 			 * aligned range ( newbsize ).
3452 			 *
3453 			 * The VM test is against m->valid, which is DEV_BSIZE
3454 			 * aligned.  Needless to say, the validity of the data
3455 			 * needs to also be DEV_BSIZE aligned.  Note that this
3456 			 * fails with NFS if the server or some other client
3457 			 * extends the file's EOF.  If our buffer is resized,
3458 			 * B_CACHE may remain set! XXX
3459 			 */
3460 
3461 			toff = bp->b_bcount;
3462 			tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3463 
3464 			while ((bp->b_flags & B_CACHE) && toff < size) {
3465 				vm_pindex_t pi;
3466 
3467 				if (tinc > (size - toff))
3468 					tinc = size - toff;
3469 
3470 				pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
3471 				    PAGE_SHIFT;
3472 
3473 				vfs_buf_test_cache(
3474 				    bp,
3475 				    bp->b_loffset,
3476 				    toff,
3477 				    tinc,
3478 				    bp->b_xio.xio_pages[pi]
3479 				);
3480 				toff += tinc;
3481 				tinc = PAGE_SIZE;
3482 			}
3483 
3484 			/*
3485 			 * Step 3, fixup the KVM pmap.  Remember that
3486 			 * bp->b_data is relative to bp->b_loffset, but
3487 			 * bp->b_loffset may be offset into the first page.
3488 			 */
3489 
3490 			bp->b_data = (caddr_t)
3491 			    trunc_page((vm_offset_t)bp->b_data);
3492 			pmap_qenter(
3493 			    (vm_offset_t)bp->b_data,
3494 			    bp->b_xio.xio_pages,
3495 			    bp->b_xio.xio_npages
3496 			);
3497 			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3498 			    (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3499 		}
3500 	}
3501 
3502 	/* adjust space use on already-dirty buffer */
3503 	if (bp->b_flags & B_DELWRI) {
3504 		spin_lock(&bufcspin);
3505 		dirtybufspace += newbsize - bp->b_bufsize;
3506 		if (bp->b_flags & B_HEAVY)
3507 			dirtybufspacehw += newbsize - bp->b_bufsize;
3508 		spin_unlock(&bufcspin);
3509 	}
3510 	if (newbsize < bp->b_bufsize)
3511 		bufspacewakeup();
3512 	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
3513 	bp->b_bcount = size;		/* requested buffer size	*/
3514 	return 1;
3515 }
3516 
3517 /*
3518  * biowait:
3519  *
3520  *	Wait for buffer I/O completion, returning error status. B_EINTR
3521  *	is converted into an EINTR error but not cleared (since a chain
3522  *	of biowait() calls may occur).
3523  *
3524  *	On return bpdone() will have been called but the buffer will remain
3525  *	locked and will not have been brelse()'d.
3526  *
3527  *	NOTE!  If a timeout is specified and ETIMEDOUT occurs the I/O is
3528  *	likely still in progress on return.
3529  *
3530  *	NOTE!  This operation is on a BIO, not a BUF.
3531  *
3532  *	NOTE!  BIO_DONE is cleared by vn_strategy()
3533  *
3534  * MPSAFE
3535  */
3536 static __inline int
3537 _biowait(struct bio *bio, const char *wmesg, int to)
3538 {
3539 	struct buf *bp = bio->bio_buf;
3540 	u_int32_t flags;
3541 	u_int32_t nflags;
3542 	int error;
3543 
3544 	KKASSERT(bio == &bp->b_bio1);
3545 	for (;;) {
3546 		flags = bio->bio_flags;
3547 		if (flags & BIO_DONE)
3548 			break;
3549 		nflags = flags | BIO_WANT;
3550 		tsleep_interlock(bio, 0);
3551 		if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3552 			if (wmesg)
3553 				error = tsleep(bio, PINTERLOCKED, wmesg, to);
3554 			else if (bp->b_cmd == BUF_CMD_READ)
3555 				error = tsleep(bio, PINTERLOCKED, "biord", to);
3556 			else
3557 				error = tsleep(bio, PINTERLOCKED, "biowr", to);
3558 			if (error) {
3559 				kprintf("tsleep error biowait %d\n", error);
3560 				return (error);
3561 			}
3562 		}
3563 	}
3564 
3565 	/*
3566 	 * Finish up.
3567 	 */
3568 	KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3569 	bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3570 	if (bp->b_flags & B_EINTR)
3571 		return (EINTR);
3572 	if (bp->b_flags & B_ERROR)
3573 		return (bp->b_error ? bp->b_error : EIO);
3574 	return (0);
3575 }
3576 
3577 int
3578 biowait(struct bio *bio, const char *wmesg)
3579 {
3580 	return(_biowait(bio, wmesg, 0));
3581 }
3582 
3583 int
3584 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3585 {
3586 	return(_biowait(bio, wmesg, to));
3587 }
3588 
3589 /*
3590  * This associates a tracking count with an I/O.  vn_strategy() and
3591  * dev_dstrategy() do this automatically but there are a few cases
3592  * where a vnode or device layer is bypassed when a block translation
3593  * is cached.  In such cases bio_start_transaction() may be called on
3594  * the bypassed layers so the system gets an I/O in progress indication
3595  * for those higher layers.
3596  */
3597 void
3598 bio_start_transaction(struct bio *bio, struct bio_track *track)
3599 {
3600 	bio->bio_track = track;
3601 	if (dsched_is_clear_buf_priv(bio->bio_buf))
3602 		dsched_new_buf(bio->bio_buf);
3603 	bio_track_ref(track);
3604 }
3605 
3606 /*
3607  * Initiate I/O on a vnode.
3608  *
3609  * SWAPCACHE OPERATION:
3610  *
3611  *	Real buffer cache buffers have a non-NULL bp->b_vp.  Unfortunately
3612  *	devfs also uses b_vp for fake buffers so we also have to check
3613  *	that B_PAGING is 0.  In this case the passed 'vp' is probably the
3614  *	underlying block device.  The swap assignments are related to the
3615  *	buffer cache buffer's b_vp, not the passed vp.
3616  *
3617  *	The passed vp == bp->b_vp only in the case where the strategy call
3618  *	is made on the vp itself for its own buffers (a regular file or
3619  *	block device vp).  The filesystem usually then re-calls vn_strategy()
3620  *	after translating the request to an underlying device.
3621  *
3622  *	Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3623  *	underlying buffer cache buffers.
3624  *
3625  *	We can only deal with page-aligned buffers at the moment, because
3626  *	we can't tell what the real dirty state for pages straddling a buffer
3627  *	are.
3628  *
3629  *	In order to call swap_pager_strategy() we must provide the VM object
3630  *	and base offset for the underlying buffer cache pages so it can find
3631  *	the swap blocks.
3632  */
3633 void
3634 vn_strategy(struct vnode *vp, struct bio *bio)
3635 {
3636 	struct bio_track *track;
3637 	struct buf *bp = bio->bio_buf;
3638 
3639 	KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3640 
3641 	/*
3642 	 * Set when an I/O is issued on the bp.  Cleared by consumers
3643 	 * (aka HAMMER), allowing the consumer to determine if I/O had
3644 	 * actually occurred.
3645 	 */
3646 	bp->b_flags |= B_IODEBUG;
3647 
3648 	/*
3649 	 * Handle the swap cache intercept.
3650 	 */
3651 	if (vn_cache_strategy(vp, bio))
3652 		return;
3653 
3654 	/*
3655 	 * Otherwise do the operation through the filesystem
3656 	 */
3657         if (bp->b_cmd == BUF_CMD_READ)
3658                 track = &vp->v_track_read;
3659         else
3660                 track = &vp->v_track_write;
3661 	KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3662 	bio->bio_track = track;
3663 	if (dsched_is_clear_buf_priv(bio->bio_buf))
3664 		dsched_new_buf(bio->bio_buf);
3665 	bio_track_ref(track);
3666         vop_strategy(*vp->v_ops, vp, bio);
3667 }
3668 
3669 static void vn_cache_strategy_callback(struct bio *bio);
3670 
3671 int
3672 vn_cache_strategy(struct vnode *vp, struct bio *bio)
3673 {
3674 	struct buf *bp = bio->bio_buf;
3675 	struct bio *nbio;
3676 	vm_object_t object;
3677 	vm_page_t m;
3678 	int i;
3679 
3680 	/*
3681 	 * Is this buffer cache buffer suitable for reading from
3682 	 * the swap cache?
3683 	 */
3684 	if (vm_swapcache_read_enable == 0 ||
3685 	    bp->b_cmd != BUF_CMD_READ ||
3686 	    ((bp->b_flags & B_CLUSTER) == 0 &&
3687 	     (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) ||
3688 	    ((int)bp->b_loffset & PAGE_MASK) != 0 ||
3689 	    (bp->b_bcount & PAGE_MASK) != 0) {
3690 		return(0);
3691 	}
3692 
3693 	/*
3694 	 * Figure out the original VM object (it will match the underlying
3695 	 * VM pages).  Note that swap cached data uses page indices relative
3696 	 * to that object, not relative to bio->bio_offset.
3697 	 */
3698 	if (bp->b_flags & B_CLUSTER)
3699 		object = vp->v_object;
3700 	else
3701 		object = bp->b_vp->v_object;
3702 
3703 	/*
3704 	 * In order to be able to use the swap cache all underlying VM
3705 	 * pages must be marked as such, and we can't have any bogus pages.
3706 	 */
3707 	for (i = 0; i < bp->b_xio.xio_npages; ++i) {
3708 		m = bp->b_xio.xio_pages[i];
3709 		if ((m->flags & PG_SWAPPED) == 0)
3710 			break;
3711 		if (m == bogus_page)
3712 			break;
3713 	}
3714 
3715 	/*
3716 	 * If we are good then issue the I/O using swap_pager_strategy().
3717 	 *
3718 	 * We can only do this if the buffer actually supports object-backed
3719 	 * I/O.  If it doesn't npages will be 0.
3720 	 */
3721 	if (i && i == bp->b_xio.xio_npages) {
3722 		m = bp->b_xio.xio_pages[0];
3723 		nbio = push_bio(bio);
3724 		nbio->bio_done = vn_cache_strategy_callback;
3725 		nbio->bio_offset = ptoa(m->pindex);
3726 		KKASSERT(m->object == object);
3727 		swap_pager_strategy(object, nbio);
3728 		return(1);
3729 	}
3730 	return(0);
3731 }
3732 
3733 /*
3734  * This is a bit of a hack but since the vn_cache_strategy() function can
3735  * override a VFS's strategy function we must make sure that the bio, which
3736  * is probably bio2, doesn't leak an unexpected offset value back to the
3737  * filesystem.  The filesystem (e.g. UFS) might otherwise assume that the
3738  * bio went through its own file strategy function and the the bio2 offset
3739  * is a cached disk offset when, in fact, it isn't.
3740  */
3741 static void
3742 vn_cache_strategy_callback(struct bio *bio)
3743 {
3744 	bio->bio_offset = NOOFFSET;
3745 	biodone(pop_bio(bio));
3746 }
3747 
3748 /*
3749  * bpdone:
3750  *
3751  *	Finish I/O on a buffer after all BIOs have been processed.
3752  *	Called when the bio chain is exhausted or by biowait.  If called
3753  *	by biowait, elseit is typically 0.
3754  *
3755  *	bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3756  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3757  *	assuming B_INVAL is clear.
3758  *
3759  *	For the VMIO case, we set B_CACHE if the op was a read and no
3760  *	read error occured, or if the op was a write.  B_CACHE is never
3761  *	set if the buffer is invalid or otherwise uncacheable.
3762  *
3763  *	bpdone does not mess with B_INVAL, allowing the I/O routine or the
3764  *	initiator to leave B_INVAL set to brelse the buffer out of existance
3765  *	in the biodone routine.
3766  */
3767 void
3768 bpdone(struct buf *bp, int elseit)
3769 {
3770 	buf_cmd_t cmd;
3771 
3772 	KASSERT(BUF_REFCNTNB(bp) > 0,
3773 		("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3774 	KASSERT(bp->b_cmd != BUF_CMD_DONE,
3775 		("biodone: bp %p already done!", bp));
3776 
3777 	/*
3778 	 * No more BIOs are left.  All completion functions have been dealt
3779 	 * with, now we clean up the buffer.
3780 	 */
3781 	cmd = bp->b_cmd;
3782 	bp->b_cmd = BUF_CMD_DONE;
3783 
3784 	/*
3785 	 * Only reads and writes are processed past this point.
3786 	 */
3787 	if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3788 		if (cmd == BUF_CMD_FREEBLKS)
3789 			bp->b_flags |= B_NOCACHE;
3790 		if (elseit)
3791 			brelse(bp);
3792 		return;
3793 	}
3794 
3795 	/*
3796 	 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3797 	 * a lot worse.  XXX - move this above the clearing of b_cmd
3798 	 */
3799 	if (LIST_FIRST(&bp->b_dep) != NULL)
3800 		buf_complete(bp);	/* MPSAFE */
3801 
3802 	/*
3803 	 * A failed write must re-dirty the buffer unless B_INVAL
3804 	 * was set.  Only applicable to normal buffers (with VPs).
3805 	 * vinum buffers may not have a vp.
3806 	 */
3807 	if (cmd == BUF_CMD_WRITE &&
3808 	    (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3809 		bp->b_flags &= ~B_NOCACHE;
3810 		if (bp->b_vp)
3811 			bdirty(bp);
3812 	}
3813 
3814 	if (bp->b_flags & B_VMIO) {
3815 		int i;
3816 		vm_ooffset_t foff;
3817 		vm_page_t m;
3818 		vm_object_t obj;
3819 		int iosize;
3820 		struct vnode *vp = bp->b_vp;
3821 
3822 		obj = vp->v_object;
3823 
3824 #if defined(VFS_BIO_DEBUG)
3825 		if (vp->v_auxrefs == 0)
3826 			panic("biodone: zero vnode hold count");
3827 		if ((vp->v_flag & VOBJBUF) == 0)
3828 			panic("biodone: vnode is not setup for merged cache");
3829 #endif
3830 
3831 		foff = bp->b_loffset;
3832 		KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3833 		KASSERT(obj != NULL, ("biodone: missing VM object"));
3834 
3835 #if defined(VFS_BIO_DEBUG)
3836 		if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3837 			kprintf("biodone: paging in progress(%d) < "
3838 				"bp->b_xio.xio_npages(%d)\n",
3839 				obj->paging_in_progress,
3840 				bp->b_xio.xio_npages);
3841 		}
3842 #endif
3843 
3844 		/*
3845 		 * Set B_CACHE if the op was a normal read and no error
3846 		 * occured.  B_CACHE is set for writes in the b*write()
3847 		 * routines.
3848 		 */
3849 		iosize = bp->b_bcount - bp->b_resid;
3850 		if (cmd == BUF_CMD_READ &&
3851 		    (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3852 			bp->b_flags |= B_CACHE;
3853 		}
3854 
3855 		vm_object_hold(obj);
3856 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
3857 			int bogusflag = 0;
3858 			int resid;
3859 
3860 			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3861 			if (resid > iosize)
3862 				resid = iosize;
3863 
3864 			/*
3865 			 * cleanup bogus pages, restoring the originals.  Since
3866 			 * the originals should still be wired, we don't have
3867 			 * to worry about interrupt/freeing races destroying
3868 			 * the VM object association.
3869 			 */
3870 			m = bp->b_xio.xio_pages[i];
3871 			if (m == bogus_page) {
3872 				bogusflag = 1;
3873 				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3874 				if (m == NULL)
3875 					panic("biodone: page disappeared");
3876 				bp->b_xio.xio_pages[i] = m;
3877 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3878 					bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3879 			}
3880 #if defined(VFS_BIO_DEBUG)
3881 			if (OFF_TO_IDX(foff) != m->pindex) {
3882 				kprintf("biodone: foff(%lu)/m->pindex(%ld) "
3883 					"mismatch\n",
3884 					(unsigned long)foff, (long)m->pindex);
3885 			}
3886 #endif
3887 
3888 			/*
3889 			 * In the write case, the valid and clean bits are
3890 			 * already changed correctly (see bdwrite()), so we
3891 			 * only need to do this here in the read case.
3892 			 */
3893 			vm_page_busy_wait(m, FALSE, "bpdpgw");
3894 			if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3895 				vfs_clean_one_page(bp, i, m);
3896 			}
3897 			vm_page_flag_clear(m, PG_ZERO);
3898 
3899 			/*
3900 			 * when debugging new filesystems or buffer I/O
3901 			 * methods, this is the most common error that pops
3902 			 * up.  if you see this, you have not set the page
3903 			 * busy flag correctly!!!
3904 			 */
3905 			if (m->busy == 0) {
3906 				kprintf("biodone: page busy < 0, "
3907 				    "pindex: %d, foff: 0x(%x,%x), "
3908 				    "resid: %d, index: %d\n",
3909 				    (int) m->pindex, (int)(foff >> 32),
3910 						(int) foff & 0xffffffff, resid, i);
3911 				if (!vn_isdisk(vp, NULL))
3912 					kprintf(" iosize: %ld, loffset: %lld, "
3913 						"flags: 0x%08x, npages: %d\n",
3914 					    bp->b_vp->v_mount->mnt_stat.f_iosize,
3915 					    (long long)bp->b_loffset,
3916 					    bp->b_flags, bp->b_xio.xio_npages);
3917 				else
3918 					kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3919 					    (long long)bp->b_loffset,
3920 					    bp->b_flags, bp->b_xio.xio_npages);
3921 				kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3922 				    m->valid, m->dirty, m->wire_count);
3923 				panic("biodone: page busy < 0");
3924 			}
3925 			vm_page_io_finish(m);
3926 			vm_page_wakeup(m);
3927 			vm_object_pip_wakeup(obj);
3928 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3929 			iosize -= resid;
3930 		}
3931 		bp->b_flags &= ~B_HASBOGUS;
3932 		vm_object_drop(obj);
3933 	}
3934 
3935 	/*
3936 	 * Finish up by releasing the buffer.  There are no more synchronous
3937 	 * or asynchronous completions, those were handled by bio_done
3938 	 * callbacks.
3939 	 */
3940 	if (elseit) {
3941 		if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3942 			brelse(bp);
3943 		else
3944 			bqrelse(bp);
3945 	}
3946 }
3947 
3948 /*
3949  * Normal biodone.
3950  */
3951 void
3952 biodone(struct bio *bio)
3953 {
3954 	struct buf *bp = bio->bio_buf;
3955 
3956 	runningbufwakeup(bp);
3957 
3958 	/*
3959 	 * Run up the chain of BIO's.   Leave b_cmd intact for the duration.
3960 	 */
3961 	while (bio) {
3962 		biodone_t *done_func;
3963 		struct bio_track *track;
3964 
3965 		/*
3966 		 * BIO tracking.  Most but not all BIOs are tracked.
3967 		 */
3968 		if ((track = bio->bio_track) != NULL) {
3969 			bio_track_rel(track);
3970 			bio->bio_track = NULL;
3971 		}
3972 
3973 		/*
3974 		 * A bio_done function terminates the loop.  The function
3975 		 * will be responsible for any further chaining and/or
3976 		 * buffer management.
3977 		 *
3978 		 * WARNING!  The done function can deallocate the buffer!
3979 		 */
3980 		if ((done_func = bio->bio_done) != NULL) {
3981 			bio->bio_done = NULL;
3982 			done_func(bio);
3983 			return;
3984 		}
3985 		bio = bio->bio_prev;
3986 	}
3987 
3988 	/*
3989 	 * If we've run out of bio's do normal [a]synchronous completion.
3990 	 */
3991 	bpdone(bp, 1);
3992 }
3993 
3994 /*
3995  * Synchronous biodone - this terminates a synchronous BIO.
3996  *
3997  * bpdone() is called with elseit=FALSE, leaving the buffer completed
3998  * but still locked.  The caller must brelse() the buffer after waiting
3999  * for completion.
4000  */
4001 void
4002 biodone_sync(struct bio *bio)
4003 {
4004 	struct buf *bp = bio->bio_buf;
4005 	int flags;
4006 	int nflags;
4007 
4008 	KKASSERT(bio == &bp->b_bio1);
4009 	bpdone(bp, 0);
4010 
4011 	for (;;) {
4012 		flags = bio->bio_flags;
4013 		nflags = (flags | BIO_DONE) & ~BIO_WANT;
4014 
4015 		if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
4016 			if (flags & BIO_WANT)
4017 				wakeup(bio);
4018 			break;
4019 		}
4020 	}
4021 }
4022 
4023 /*
4024  * vfs_unbusy_pages:
4025  *
4026  *	This routine is called in lieu of iodone in the case of
4027  *	incomplete I/O.  This keeps the busy status for pages
4028  *	consistant.
4029  */
4030 void
4031 vfs_unbusy_pages(struct buf *bp)
4032 {
4033 	int i;
4034 
4035 	runningbufwakeup(bp);
4036 
4037 	if (bp->b_flags & B_VMIO) {
4038 		struct vnode *vp = bp->b_vp;
4039 		vm_object_t obj;
4040 
4041 		obj = vp->v_object;
4042 		vm_object_hold(obj);
4043 
4044 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
4045 			vm_page_t m = bp->b_xio.xio_pages[i];
4046 
4047 			/*
4048 			 * When restoring bogus changes the original pages
4049 			 * should still be wired, so we are in no danger of
4050 			 * losing the object association and do not need
4051 			 * critical section protection particularly.
4052 			 */
4053 			if (m == bogus_page) {
4054 				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
4055 				if (!m) {
4056 					panic("vfs_unbusy_pages: page missing");
4057 				}
4058 				bp->b_xio.xio_pages[i] = m;
4059 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4060 					bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4061 			}
4062 			vm_page_busy_wait(m, FALSE, "bpdpgw");
4063 			vm_page_flag_clear(m, PG_ZERO);
4064 			vm_page_io_finish(m);
4065 			vm_page_wakeup(m);
4066 			vm_object_pip_wakeup(obj);
4067 		}
4068 		bp->b_flags &= ~B_HASBOGUS;
4069 		vm_object_drop(obj);
4070 	}
4071 }
4072 
4073 /*
4074  * vfs_busy_pages:
4075  *
4076  *	This routine is called before a device strategy routine.
4077  *	It is used to tell the VM system that paging I/O is in
4078  *	progress, and treat the pages associated with the buffer
4079  *	almost as being PG_BUSY.  Also the object 'paging_in_progress'
4080  *	flag is handled to make sure that the object doesn't become
4081  *	inconsistant.
4082  *
4083  *	Since I/O has not been initiated yet, certain buffer flags
4084  *	such as B_ERROR or B_INVAL may be in an inconsistant state
4085  *	and should be ignored.
4086  *
4087  * MPSAFE
4088  */
4089 void
4090 vfs_busy_pages(struct vnode *vp, struct buf *bp)
4091 {
4092 	int i, bogus;
4093 	struct lwp *lp = curthread->td_lwp;
4094 
4095 	/*
4096 	 * The buffer's I/O command must already be set.  If reading,
4097 	 * B_CACHE must be 0 (double check against callers only doing
4098 	 * I/O when B_CACHE is 0).
4099 	 */
4100 	KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4101 	KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
4102 
4103 	if (bp->b_flags & B_VMIO) {
4104 		vm_object_t obj;
4105 
4106 		obj = vp->v_object;
4107 		KASSERT(bp->b_loffset != NOOFFSET,
4108 			("vfs_busy_pages: no buffer offset"));
4109 
4110 		/*
4111 		 * Busy all the pages.  We have to busy them all at once
4112 		 * to avoid deadlocks.
4113 		 */
4114 retry:
4115 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
4116 			vm_page_t m = bp->b_xio.xio_pages[i];
4117 
4118 			if (vm_page_busy_try(m, FALSE)) {
4119 				vm_page_sleep_busy(m, FALSE, "vbpage");
4120 				while (--i >= 0)
4121 					vm_page_wakeup(bp->b_xio.xio_pages[i]);
4122 				goto retry;
4123 			}
4124 		}
4125 
4126 		/*
4127 		 * Setup for I/O, soft-busy the page right now because
4128 		 * the next loop may block.
4129 		 */
4130 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
4131 			vm_page_t m = bp->b_xio.xio_pages[i];
4132 
4133 			vm_page_flag_clear(m, PG_ZERO);
4134 			if ((bp->b_flags & B_CLUSTER) == 0) {
4135 				vm_object_pip_add(obj, 1);
4136 				vm_page_io_start(m);
4137 			}
4138 		}
4139 
4140 		/*
4141 		 * Adjust protections for I/O and do bogus-page mapping.
4142 		 * Assume that vm_page_protect() can block (it can block
4143 		 * if VM_PROT_NONE, don't take any chances regardless).
4144 		 *
4145 		 * In particular note that for writes we must incorporate
4146 		 * page dirtyness from the VM system into the buffer's
4147 		 * dirty range.
4148 		 *
4149 		 * For reads we theoretically must incorporate page dirtyness
4150 		 * from the VM system to determine if the page needs bogus
4151 		 * replacement, but we shortcut the test by simply checking
4152 		 * that all m->valid bits are set, indicating that the page
4153 		 * is fully valid and does not need to be re-read.  For any
4154 		 * VM system dirtyness the page will also be fully valid
4155 		 * since it was mapped at one point.
4156 		 */
4157 		bogus = 0;
4158 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
4159 			vm_page_t m = bp->b_xio.xio_pages[i];
4160 
4161 			vm_page_flag_clear(m, PG_ZERO);	/* XXX */
4162 			if (bp->b_cmd == BUF_CMD_WRITE) {
4163 				/*
4164 				 * When readying a vnode-backed buffer for
4165 				 * a write we must zero-fill any invalid
4166 				 * portions of the backing VM pages, mark
4167 				 * it valid and clear related dirty bits.
4168 				 *
4169 				 * vfs_clean_one_page() incorporates any
4170 				 * VM dirtyness and updates the b_dirtyoff
4171 				 * range (after we've made the page RO).
4172 				 *
4173 				 * It is also expected that the pmap modified
4174 				 * bit has already been cleared by the
4175 				 * vm_page_protect().  We may not be able
4176 				 * to clear all dirty bits for a page if it
4177 				 * was also memory mapped (NFS).
4178 				 *
4179 				 * Finally be sure to unassign any swap-cache
4180 				 * backing store as it is now stale.
4181 				 */
4182 				vm_page_protect(m, VM_PROT_READ);
4183 				vfs_clean_one_page(bp, i, m);
4184 				swap_pager_unswapped(m);
4185 			} else if (m->valid == VM_PAGE_BITS_ALL) {
4186 				/*
4187 				 * When readying a vnode-backed buffer for
4188 				 * read we must replace any dirty pages with
4189 				 * a bogus page so dirty data is not destroyed
4190 				 * when filling gaps.
4191 				 *
4192 				 * To avoid testing whether the page is
4193 				 * dirty we instead test that the page was
4194 				 * at some point mapped (m->valid fully
4195 				 * valid) with the understanding that
4196 				 * this also covers the dirty case.
4197 				 */
4198 				bp->b_xio.xio_pages[i] = bogus_page;
4199 				bp->b_flags |= B_HASBOGUS;
4200 				bogus++;
4201 			} else if (m->valid & m->dirty) {
4202 				/*
4203 				 * This case should not occur as partial
4204 				 * dirtyment can only happen if the buffer
4205 				 * is B_CACHE, and this code is not entered
4206 				 * if the buffer is B_CACHE.
4207 				 */
4208 				kprintf("Warning: vfs_busy_pages - page not "
4209 					"fully valid! loff=%jx bpf=%08x "
4210 					"idx=%d val=%02x dir=%02x\n",
4211 					(intmax_t)bp->b_loffset, bp->b_flags,
4212 					i, m->valid, m->dirty);
4213 				vm_page_protect(m, VM_PROT_NONE);
4214 			} else {
4215 				/*
4216 				 * The page is not valid and can be made
4217 				 * part of the read.
4218 				 */
4219 				vm_page_protect(m, VM_PROT_NONE);
4220 			}
4221 			vm_page_wakeup(m);
4222 		}
4223 		if (bogus) {
4224 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4225 				bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4226 		}
4227 	}
4228 
4229 	/*
4230 	 * This is the easiest place to put the process accounting for the I/O
4231 	 * for now.
4232 	 */
4233 	if (lp != NULL) {
4234 		if (bp->b_cmd == BUF_CMD_READ)
4235 			lp->lwp_ru.ru_inblock++;
4236 		else
4237 			lp->lwp_ru.ru_oublock++;
4238 	}
4239 }
4240 
4241 /*
4242  * Tell the VM system that the pages associated with this buffer
4243  * are clean.  This is used for delayed writes where the data is
4244  * going to go to disk eventually without additional VM intevention.
4245  *
4246  * NOTE: While we only really need to clean through to b_bcount, we
4247  *	 just go ahead and clean through to b_bufsize.
4248  */
4249 static void
4250 vfs_clean_pages(struct buf *bp)
4251 {
4252 	vm_page_t m;
4253 	int i;
4254 
4255 	if ((bp->b_flags & B_VMIO) == 0)
4256 		return;
4257 
4258 	KASSERT(bp->b_loffset != NOOFFSET,
4259 		("vfs_clean_pages: no buffer offset"));
4260 
4261 	for (i = 0; i < bp->b_xio.xio_npages; i++) {
4262 		m = bp->b_xio.xio_pages[i];
4263 		vfs_clean_one_page(bp, i, m);
4264 	}
4265 }
4266 
4267 /*
4268  * vfs_clean_one_page:
4269  *
4270  *	Set the valid bits and clear the dirty bits in a page within a
4271  *	buffer.  The range is restricted to the buffer's size and the
4272  *	buffer's logical offset might index into the first page.
4273  *
4274  *	The caller has busied or soft-busied the page and it is not mapped,
4275  *	test and incorporate the dirty bits into b_dirtyoff/end before
4276  *	clearing them.  Note that we need to clear the pmap modified bits
4277  *	after determining the the page was dirty, vm_page_set_validclean()
4278  *	does not do it for us.
4279  *
4280  *	This routine is typically called after a read completes (dirty should
4281  *	be zero in that case as we are not called on bogus-replace pages),
4282  *	or before a write is initiated.
4283  */
4284 static void
4285 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
4286 {
4287 	int bcount;
4288 	int xoff;
4289 	int soff;
4290 	int eoff;
4291 
4292 	/*
4293 	 * Calculate offset range within the page but relative to buffer's
4294 	 * loffset.  loffset might be offset into the first page.
4295 	 */
4296 	xoff = (int)bp->b_loffset & PAGE_MASK;	/* loffset offset into pg 0 */
4297 	bcount = bp->b_bcount + xoff;		/* offset adjusted */
4298 
4299 	if (pageno == 0) {
4300 		soff = xoff;
4301 		eoff = PAGE_SIZE;
4302 	} else {
4303 		soff = (pageno << PAGE_SHIFT);
4304 		eoff = soff + PAGE_SIZE;
4305 	}
4306 	if (eoff > bcount)
4307 		eoff = bcount;
4308 	if (soff >= eoff)
4309 		return;
4310 
4311 	/*
4312 	 * Test dirty bits and adjust b_dirtyoff/end.
4313 	 *
4314 	 * If dirty pages are incorporated into the bp any prior
4315 	 * B_NEEDCOMMIT state (NFS) must be cleared because the
4316 	 * caller has not taken into account the new dirty data.
4317 	 *
4318 	 * If the page was memory mapped the dirty bits might go beyond the
4319 	 * end of the buffer, but we can't really make the assumption that
4320 	 * a file EOF straddles the buffer (even though this is the case for
4321 	 * NFS if B_NEEDCOMMIT is also set).  So for the purposes of clearing
4322 	 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4323 	 * This also saves some console spam.
4324 	 *
4325 	 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4326 	 * NFS can handle huge commits but not huge writes.
4327 	 */
4328 	vm_page_test_dirty(m);
4329 	if (m->dirty) {
4330 		if ((bp->b_flags & B_NEEDCOMMIT) &&
4331 		    (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
4332 			if (debug_commit)
4333 			kprintf("Warning: vfs_clean_one_page: bp %p "
4334 				"loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4335 				" cmd %d vd %02x/%02x x/s/e %d %d %d "
4336 				"doff/end %d %d\n",
4337 				bp, (intmax_t)bp->b_loffset, bp->b_bcount,
4338 				bp->b_flags, bp->b_cmd,
4339 				m->valid, m->dirty, xoff, soff, eoff,
4340 				bp->b_dirtyoff, bp->b_dirtyend);
4341 			bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
4342 			if (debug_commit)
4343 				print_backtrace(-1);
4344 		}
4345 		/*
4346 		 * Only clear the pmap modified bits if ALL the dirty bits
4347 		 * are set, otherwise the system might mis-clear portions
4348 		 * of a page.
4349 		 */
4350 		if (m->dirty == VM_PAGE_BITS_ALL &&
4351 		    (bp->b_flags & B_NEEDCOMMIT) == 0) {
4352 			pmap_clear_modify(m);
4353 		}
4354 		if (bp->b_dirtyoff > soff - xoff)
4355 			bp->b_dirtyoff = soff - xoff;
4356 		if (bp->b_dirtyend < eoff - xoff)
4357 			bp->b_dirtyend = eoff - xoff;
4358 	}
4359 
4360 	/*
4361 	 * Set related valid bits, clear related dirty bits.
4362 	 * Does not mess with the pmap modified bit.
4363 	 *
4364 	 * WARNING!  We cannot just clear all of m->dirty here as the
4365 	 *	     buffer cache buffers may use a DEV_BSIZE'd aligned
4366 	 *	     block size, or have an odd size (e.g. NFS at file EOF).
4367 	 *	     The putpages code can clear m->dirty to 0.
4368 	 *
4369 	 *	     If a VOP_WRITE generates a buffer cache buffer which
4370 	 *	     covers the same space as mapped writable pages the
4371 	 *	     buffer flush might not be able to clear all the dirty
4372 	 *	     bits and still require a putpages from the VM system
4373 	 *	     to finish it off.
4374 	 *
4375 	 * WARNING!  vm_page_set_validclean() currently assumes vm_token
4376 	 *	     is held.  The page might not be busied (bdwrite() case).
4377 	 *	     XXX remove this comment once we've validated that this
4378 	 *	     is no longer an issue.
4379 	 */
4380 	vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
4381 }
4382 
4383 /*
4384  * Similar to vfs_clean_one_page() but sets the bits to valid and dirty.
4385  * The page data is assumed to be valid (there is no zeroing here).
4386  */
4387 static void
4388 vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m)
4389 {
4390 	int bcount;
4391 	int xoff;
4392 	int soff;
4393 	int eoff;
4394 
4395 	/*
4396 	 * Calculate offset range within the page but relative to buffer's
4397 	 * loffset.  loffset might be offset into the first page.
4398 	 */
4399 	xoff = (int)bp->b_loffset & PAGE_MASK;	/* loffset offset into pg 0 */
4400 	bcount = bp->b_bcount + xoff;		/* offset adjusted */
4401 
4402 	if (pageno == 0) {
4403 		soff = xoff;
4404 		eoff = PAGE_SIZE;
4405 	} else {
4406 		soff = (pageno << PAGE_SHIFT);
4407 		eoff = soff + PAGE_SIZE;
4408 	}
4409 	if (eoff > bcount)
4410 		eoff = bcount;
4411 	if (soff >= eoff)
4412 		return;
4413 	vm_page_set_validdirty(m, soff & PAGE_MASK, eoff - soff);
4414 }
4415 
4416 /*
4417  * vfs_bio_clrbuf:
4418  *
4419  *	Clear a buffer.  This routine essentially fakes an I/O, so we need
4420  *	to clear B_ERROR and B_INVAL.
4421  *
4422  *	Note that while we only theoretically need to clear through b_bcount,
4423  *	we go ahead and clear through b_bufsize.
4424  */
4425 
4426 void
4427 vfs_bio_clrbuf(struct buf *bp)
4428 {
4429 	int i, mask = 0;
4430 	caddr_t sa, ea;
4431 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
4432 		bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4433 		if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4434 		    (bp->b_loffset & PAGE_MASK) == 0) {
4435 			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4436 			if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4437 				bp->b_resid = 0;
4438 				return;
4439 			}
4440 			if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
4441 			    ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
4442 				bzero(bp->b_data, bp->b_bufsize);
4443 				bp->b_xio.xio_pages[0]->valid |= mask;
4444 				bp->b_resid = 0;
4445 				return;
4446 			}
4447 		}
4448 		sa = bp->b_data;
4449 		for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4450 			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4451 			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4452 			ea = (caddr_t)(vm_offset_t)ulmin(
4453 			    (u_long)(vm_offset_t)ea,
4454 			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4455 			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4456 			if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4457 				continue;
4458 			if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4459 				if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4460 					bzero(sa, ea - sa);
4461 				}
4462 			} else {
4463 				for (; sa < ea; sa += DEV_BSIZE, j++) {
4464 					if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4465 						(bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4466 						bzero(sa, DEV_BSIZE);
4467 				}
4468 			}
4469 			bp->b_xio.xio_pages[i]->valid |= mask;
4470 			vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4471 		}
4472 		bp->b_resid = 0;
4473 	} else {
4474 		clrbuf(bp);
4475 	}
4476 }
4477 
4478 /*
4479  * vm_hold_load_pages:
4480  *
4481  *	Load pages into the buffer's address space.  The pages are
4482  *	allocated from the kernel object in order to reduce interference
4483  *	with the any VM paging I/O activity.  The range of loaded
4484  *	pages will be wired.
4485  *
4486  *	If a page cannot be allocated, the 'pagedaemon' is woken up to
4487  *	retrieve the full range (to - from) of pages.
4488  *
4489  * MPSAFE
4490  */
4491 void
4492 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4493 {
4494 	vm_offset_t pg;
4495 	vm_page_t p;
4496 	int index;
4497 
4498 	to = round_page(to);
4499 	from = round_page(from);
4500 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4501 
4502 	pg = from;
4503 	while (pg < to) {
4504 		/*
4505 		 * Note: must allocate system pages since blocking here
4506 		 * could intefere with paging I/O, no matter which
4507 		 * process we are.
4508 		 */
4509 		vm_object_hold(&kernel_object);
4510 		p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
4511 				   (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4512 		vm_object_drop(&kernel_object);
4513 		if (p) {
4514 			vm_page_wire(p);
4515 			p->valid = VM_PAGE_BITS_ALL;
4516 			vm_page_flag_clear(p, PG_ZERO);
4517 			pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
4518 			bp->b_xio.xio_pages[index] = p;
4519 			vm_page_wakeup(p);
4520 
4521 			pg += PAGE_SIZE;
4522 			++index;
4523 		}
4524 	}
4525 	bp->b_xio.xio_npages = index;
4526 }
4527 
4528 /*
4529  * Allocate pages for a buffer cache buffer.
4530  *
4531  * Under extremely severe memory conditions even allocating out of the
4532  * system reserve can fail.  If this occurs we must allocate out of the
4533  * interrupt reserve to avoid a deadlock with the pageout daemon.
4534  *
4535  * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
4536  * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
4537  * against the pageout daemon if pages are not freed from other sources.
4538  *
4539  * If NULL is returned the caller is expected to retry (typically check if
4540  * the page already exists on retry before trying to allocate one).
4541  */
4542 static
4543 vm_page_t
4544 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
4545 {
4546 	vm_page_t p;
4547 
4548 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj));
4549 
4550 	/*
4551 	 * Try a normal allocation, allow use of system reserve.
4552 	 */
4553 	p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
4554 				   VM_ALLOC_NULL_OK);
4555 	if (p)
4556 		return(p);
4557 
4558 	/*
4559 	 * The normal allocation failed and we clearly have a page
4560 	 * deficit.  Try to reclaim some clean VM pages directly
4561 	 * from the buffer cache.
4562 	 */
4563 	vm_pageout_deficit += deficit;
4564 	recoverbufpages();
4565 
4566 	/*
4567 	 * We may have blocked, the caller will know what to do if the
4568 	 * page now exists.
4569 	 */
4570 	if (vm_page_lookup(obj, pg)) {
4571 		return(NULL);
4572 	}
4573 
4574 	/*
4575 	 * Only system threads can use the interrupt reserve
4576 	 */
4577 	if ((curthread->td_flags & TDF_SYSTHREAD) == 0) {
4578 		vm_wait(hz);
4579 		return(NULL);
4580 	}
4581 
4582 
4583 	/*
4584 	 * Allocate and allow use of the interrupt reserve.
4585 	 *
4586 	 * If after all that we still can't allocate a VM page we are
4587 	 * in real trouble, but we slog on anyway hoping that the system
4588 	 * won't deadlock.
4589 	 */
4590 	p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
4591 				   VM_ALLOC_INTERRUPT | VM_ALLOC_NULL_OK);
4592 	if (p) {
4593 		if (vm_page_count_severe()) {
4594 			++lowmempgallocs;
4595 			vm_wait(hz / 20 + 1);
4596 		}
4597 	} else if (vm_page_lookup(obj, pg) == NULL) {
4598 		kprintf("bio_page_alloc: Memory exhausted during bufcache "
4599 			"page allocation\n");
4600 		++lowmempgfails;
4601 		vm_wait(hz);
4602 	}
4603 	return(p);
4604 }
4605 
4606 /*
4607  * vm_hold_free_pages:
4608  *
4609  *	Return pages associated with the buffer back to the VM system.
4610  *
4611  *	The range of pages underlying the buffer's address space will
4612  *	be unmapped and un-wired.
4613  *
4614  * MPSAFE
4615  */
4616 void
4617 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4618 {
4619 	vm_offset_t pg;
4620 	vm_page_t p;
4621 	int index, newnpages;
4622 
4623 	from = round_page(from);
4624 	to = round_page(to);
4625 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4626 	newnpages = index;
4627 
4628 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4629 		p = bp->b_xio.xio_pages[index];
4630 		if (p && (index < bp->b_xio.xio_npages)) {
4631 			if (p->busy) {
4632 				kprintf("vm_hold_free_pages: doffset: %lld, "
4633 					"loffset: %lld\n",
4634 					(long long)bp->b_bio2.bio_offset,
4635 					(long long)bp->b_loffset);
4636 			}
4637 			bp->b_xio.xio_pages[index] = NULL;
4638 			pmap_kremove(pg);
4639 			vm_page_busy_wait(p, FALSE, "vmhldpg");
4640 			vm_page_unwire(p, 0);
4641 			vm_page_free(p);
4642 		}
4643 	}
4644 	bp->b_xio.xio_npages = newnpages;
4645 }
4646 
4647 /*
4648  * vmapbuf:
4649  *
4650  *	Map a user buffer into KVM via a pbuf.  On return the buffer's
4651  *	b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4652  *	initialized.
4653  */
4654 int
4655 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4656 {
4657 	caddr_t addr;
4658 	vm_offset_t va;
4659 	vm_page_t m;
4660 	int vmprot;
4661 	int error;
4662 	int pidx;
4663 	int i;
4664 
4665 	/*
4666 	 * bp had better have a command and it better be a pbuf.
4667 	 */
4668 	KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4669 	KKASSERT(bp->b_flags & B_PAGING);
4670 	KKASSERT(bp->b_kvabase);
4671 
4672 	if (bytes < 0)
4673 		return (-1);
4674 
4675 	/*
4676 	 * Map the user data into KVM.  Mappings have to be page-aligned.
4677 	 */
4678 	addr = (caddr_t)trunc_page((vm_offset_t)udata);
4679 	pidx = 0;
4680 
4681 	vmprot = VM_PROT_READ;
4682 	if (bp->b_cmd == BUF_CMD_READ)
4683 		vmprot |= VM_PROT_WRITE;
4684 
4685 	while (addr < udata + bytes) {
4686 		/*
4687 		 * Do the vm_fault if needed; do the copy-on-write thing
4688 		 * when reading stuff off device into memory.
4689 		 *
4690 		 * vm_fault_page*() returns a held VM page.
4691 		 */
4692 		va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4693 		va = trunc_page(va);
4694 
4695 		m = vm_fault_page_quick(va, vmprot, &error);
4696 		if (m == NULL) {
4697 			for (i = 0; i < pidx; ++i) {
4698 			    vm_page_unhold(bp->b_xio.xio_pages[i]);
4699 			    bp->b_xio.xio_pages[i] = NULL;
4700 			}
4701 			return(-1);
4702 		}
4703 		bp->b_xio.xio_pages[pidx] = m;
4704 		addr += PAGE_SIZE;
4705 		++pidx;
4706 	}
4707 
4708 	/*
4709 	 * Map the page array and set the buffer fields to point to
4710 	 * the mapped data buffer.
4711 	 */
4712 	if (pidx > btoc(MAXPHYS))
4713 		panic("vmapbuf: mapped more than MAXPHYS");
4714 	pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4715 
4716 	bp->b_xio.xio_npages = pidx;
4717 	bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4718 	bp->b_bcount = bytes;
4719 	bp->b_bufsize = bytes;
4720 	return(0);
4721 }
4722 
4723 /*
4724  * vunmapbuf:
4725  *
4726  *	Free the io map PTEs associated with this IO operation.
4727  *	We also invalidate the TLB entries and restore the original b_addr.
4728  */
4729 void
4730 vunmapbuf(struct buf *bp)
4731 {
4732 	int pidx;
4733 	int npages;
4734 
4735 	KKASSERT(bp->b_flags & B_PAGING);
4736 
4737 	npages = bp->b_xio.xio_npages;
4738 	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4739 	for (pidx = 0; pidx < npages; ++pidx) {
4740 		vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4741 		bp->b_xio.xio_pages[pidx] = NULL;
4742 	}
4743 	bp->b_xio.xio_npages = 0;
4744 	bp->b_data = bp->b_kvabase;
4745 }
4746 
4747 /*
4748  * Scan all buffers in the system and issue the callback.
4749  */
4750 int
4751 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4752 {
4753 	int count = 0;
4754 	int error;
4755 	int n;
4756 
4757 	for (n = 0; n < nbuf; ++n) {
4758 		if ((error = callback(&buf[n], info)) < 0) {
4759 			count = error;
4760 			break;
4761 		}
4762 		count += error;
4763 	}
4764 	return (count);
4765 }
4766 
4767 /*
4768  * nestiobuf_iodone: biodone callback for nested buffers and propagate
4769  * completion to the master buffer.
4770  */
4771 static void
4772 nestiobuf_iodone(struct bio *bio)
4773 {
4774 	struct bio *mbio;
4775 	struct buf *mbp, *bp;
4776 	struct devstat *stats;
4777 	int error;
4778 	int donebytes;
4779 
4780 	bp = bio->bio_buf;
4781 	mbio = bio->bio_caller_info1.ptr;
4782 	stats = bio->bio_caller_info2.ptr;
4783 	mbp = mbio->bio_buf;
4784 
4785 	KKASSERT(bp->b_bcount <= bp->b_bufsize);
4786 	KKASSERT(mbp != bp);
4787 
4788 	error = bp->b_error;
4789 	if (bp->b_error == 0 &&
4790 	    (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
4791 		/*
4792 		 * Not all got transfered, raise an error. We have no way to
4793 		 * propagate these conditions to mbp.
4794 		 */
4795 		error = EIO;
4796 	}
4797 
4798 	donebytes = bp->b_bufsize;
4799 
4800 	relpbuf(bp, NULL);
4801 
4802 	nestiobuf_done(mbio, donebytes, error, stats);
4803 }
4804 
4805 void
4806 nestiobuf_done(struct bio *mbio, int donebytes, int error, struct devstat *stats)
4807 {
4808 	struct buf *mbp;
4809 
4810 	mbp = mbio->bio_buf;
4811 
4812 	KKASSERT((int)(intptr_t)mbio->bio_driver_info > 0);
4813 
4814 	/*
4815 	 * If an error occured, propagate it to the master buffer.
4816 	 *
4817 	 * Several biodone()s may wind up running concurrently so
4818 	 * use an atomic op to adjust b_flags.
4819 	 */
4820 	if (error) {
4821 		mbp->b_error = error;
4822 		atomic_set_int(&mbp->b_flags, B_ERROR);
4823 	}
4824 
4825 	/*
4826 	 * Decrement the operations in progress counter and terminate the
4827 	 * I/O if this was the last bit.
4828 	 */
4829 	if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4830 		mbp->b_resid = 0;
4831 		if (stats)
4832 			devstat_end_transaction_buf(stats, mbp);
4833 		biodone(mbio);
4834 	}
4835 }
4836 
4837 /*
4838  * Initialize a nestiobuf for use.  Set an initial count of 1 to prevent
4839  * the mbio from being biodone()'d while we are still adding sub-bios to
4840  * it.
4841  */
4842 void
4843 nestiobuf_init(struct bio *bio)
4844 {
4845 	bio->bio_driver_info = (void *)1;
4846 }
4847 
4848 /*
4849  * The BIOs added to the nestedio have already been started, remove the
4850  * count that placeheld our mbio and biodone() it if the count would
4851  * transition to 0.
4852  */
4853 void
4854 nestiobuf_start(struct bio *mbio)
4855 {
4856 	struct buf *mbp = mbio->bio_buf;
4857 
4858 	/*
4859 	 * Decrement the operations in progress counter and terminate the
4860 	 * I/O if this was the last bit.
4861 	 */
4862 	if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4863 		if (mbp->b_flags & B_ERROR)
4864 			mbp->b_resid = mbp->b_bcount;
4865 		else
4866 			mbp->b_resid = 0;
4867 		biodone(mbio);
4868 	}
4869 }
4870 
4871 /*
4872  * Set an intermediate error prior to calling nestiobuf_start()
4873  */
4874 void
4875 nestiobuf_error(struct bio *mbio, int error)
4876 {
4877 	struct buf *mbp = mbio->bio_buf;
4878 
4879 	if (error) {
4880 		mbp->b_error = error;
4881 		atomic_set_int(&mbp->b_flags, B_ERROR);
4882 	}
4883 }
4884 
4885 /*
4886  * nestiobuf_add: setup a "nested" buffer.
4887  *
4888  * => 'mbp' is a "master" buffer which is being divided into sub pieces.
4889  * => 'bp' should be a buffer allocated by getiobuf.
4890  * => 'offset' is a byte offset in the master buffer.
4891  * => 'size' is a size in bytes of this nested buffer.
4892  */
4893 void
4894 nestiobuf_add(struct bio *mbio, struct buf *bp, int offset, size_t size, struct devstat *stats)
4895 {
4896 	struct buf *mbp = mbio->bio_buf;
4897 	struct vnode *vp = mbp->b_vp;
4898 
4899 	KKASSERT(mbp->b_bcount >= offset + size);
4900 
4901 	atomic_add_int((int *)&mbio->bio_driver_info, 1);
4902 
4903 	/* kernel needs to own the lock for it to be released in biodone */
4904 	BUF_KERNPROC(bp);
4905 	bp->b_vp = vp;
4906 	bp->b_cmd = mbp->b_cmd;
4907 	bp->b_bio1.bio_done = nestiobuf_iodone;
4908 	bp->b_data = (char *)mbp->b_data + offset;
4909 	bp->b_resid = bp->b_bcount = size;
4910 	bp->b_bufsize = bp->b_bcount;
4911 
4912 	bp->b_bio1.bio_track = NULL;
4913 	bp->b_bio1.bio_caller_info1.ptr = mbio;
4914 	bp->b_bio1.bio_caller_info2.ptr = stats;
4915 }
4916 
4917 /*
4918  * print out statistics from the current status of the buffer pool
4919  * this can be toggeled by the system control option debug.syncprt
4920  */
4921 #ifdef DEBUG
4922 void
4923 vfs_bufstats(void)
4924 {
4925         int i, j, count;
4926         struct buf *bp;
4927         struct bqueues *dp;
4928         int counts[(MAXBSIZE / PAGE_SIZE) + 1];
4929         static char *bname[3] = { "LOCKED", "LRU", "AGE" };
4930 
4931         for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
4932                 count = 0;
4933                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4934                         counts[j] = 0;
4935 
4936 		spin_lock(&bufqspin);
4937                 TAILQ_FOREACH(bp, dp, b_freelist) {
4938                         counts[bp->b_bufsize/PAGE_SIZE]++;
4939                         count++;
4940                 }
4941 		spin_unlock(&bufqspin);
4942 
4943                 kprintf("%s: total-%d", bname[i], count);
4944                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4945                         if (counts[j] != 0)
4946                                 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
4947                 kprintf("\n");
4948         }
4949 }
4950 #endif
4951 
4952 #ifdef DDB
4953 
4954 DB_SHOW_COMMAND(buffer, db_show_buffer)
4955 {
4956 	/* get args */
4957 	struct buf *bp = (struct buf *)addr;
4958 
4959 	if (!have_addr) {
4960 		db_printf("usage: show buffer <addr>\n");
4961 		return;
4962 	}
4963 
4964 	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4965 	db_printf("b_cmd = %d\n", bp->b_cmd);
4966 	db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4967 		  "b_resid = %d\n, b_data = %p, "
4968 		  "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4969 		  bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4970 		  bp->b_data,
4971 		  (long long)bp->b_bio2.bio_offset,
4972 		  (long long)(bp->b_bio2.bio_next ?
4973 				bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4974 	if (bp->b_xio.xio_npages) {
4975 		int i;
4976 		db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4977 			bp->b_xio.xio_npages);
4978 		for (i = 0; i < bp->b_xio.xio_npages; i++) {
4979 			vm_page_t m;
4980 			m = bp->b_xio.xio_pages[i];
4981 			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4982 			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4983 			if ((i + 1) < bp->b_xio.xio_npages)
4984 				db_printf(",");
4985 		}
4986 		db_printf("\n");
4987 	}
4988 }
4989 #endif /* DDB */
4990