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