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