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