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