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