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