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