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