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