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