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