xref: /freebsd/sys/kern/vfs_bio.c (revision 0efd6615cd5f39b67cec82a7034e655f3b5801e3)
1 /*-
2  * Copyright (c) 2004 Poul-Henning Kamp
3  * Copyright (c) 1994,1997 John S. Dyson
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * this file contains a new buffer I/O scheme implementing a coherent
30  * VM object and buffer cache scheme.  Pains have been taken to make
31  * sure that the performance degradation associated with schemes such
32  * as this is not realized.
33  *
34  * Author:  John S. Dyson
35  * Significant help during the development and debugging phases
36  * had been provided by David Greenman, also of the FreeBSD core team.
37  *
38  * see man buf(9) for more info.
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/bio.h>
47 #include <sys/conf.h>
48 #include <sys/buf.h>
49 #include <sys/devicestat.h>
50 #include <sys/eventhandler.h>
51 #include <sys/lock.h>
52 #include <sys/malloc.h>
53 #include <sys/mount.h>
54 #include <sys/mutex.h>
55 #include <sys/kernel.h>
56 #include <sys/kthread.h>
57 #include <sys/proc.h>
58 #include <sys/resourcevar.h>
59 #include <sys/sysctl.h>
60 #include <sys/vmmeter.h>
61 #include <sys/vnode.h>
62 #include <geom/geom.h>
63 #include <vm/vm.h>
64 #include <vm/vm_param.h>
65 #include <vm/vm_kern.h>
66 #include <vm/vm_pageout.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_object.h>
69 #include <vm/vm_extern.h>
70 #include <vm/vm_map.h>
71 #include "opt_directio.h"
72 #include "opt_swap.h"
73 
74 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
75 
76 struct	bio_ops bioops;		/* I/O operation notification */
77 
78 struct	buf_ops buf_ops_bio = {
79 	.bop_name	=	"buf_ops_bio",
80 	.bop_write	=	bufwrite,
81 	.bop_strategy	=	bufstrategy,
82 	.bop_sync	=	bufsync,
83 };
84 
85 /*
86  * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
87  * carnal knowledge of buffers.  This knowledge should be moved to vfs_bio.c.
88  */
89 struct buf *buf;		/* buffer header pool */
90 
91 static struct proc *bufdaemonproc;
92 
93 static int inmem(struct vnode *vp, daddr_t blkno);
94 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
95 		vm_offset_t to);
96 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
97 		vm_offset_t to);
98 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
99 			       int pageno, vm_page_t m);
100 static void vfs_clean_pages(struct buf *bp);
101 static void vfs_setdirty(struct buf *bp);
102 static void vfs_setdirty_locked_object(struct buf *bp);
103 static void vfs_vmio_release(struct buf *bp);
104 static int vfs_bio_clcheck(struct vnode *vp, int size,
105 		daddr_t lblkno, daddr_t blkno);
106 static int flushbufqueues(int, int);
107 static void buf_daemon(void);
108 static void bremfreel(struct buf *bp);
109 
110 int vmiodirenable = TRUE;
111 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
112     "Use the VM system for directory writes");
113 int runningbufspace;
114 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
115     "Amount of presently outstanding async buffer io");
116 static int bufspace;
117 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
118     "KVA memory used for bufs");
119 static int maxbufspace;
120 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
121     "Maximum allowed value of bufspace (including buf_daemon)");
122 static int bufmallocspace;
123 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
124     "Amount of malloced memory for buffers");
125 static int maxbufmallocspace;
126 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
127     "Maximum amount of malloced memory for buffers");
128 static int lobufspace;
129 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
130     "Minimum amount of buffers we want to have");
131 int hibufspace;
132 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
133     "Maximum allowed value of bufspace (excluding buf_daemon)");
134 static int bufreusecnt;
135 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
136     "Number of times we have reused a buffer");
137 static int buffreekvacnt;
138 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
139     "Number of times we have freed the KVA space from some buffer");
140 static int bufdefragcnt;
141 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
142     "Number of times we have had to repeat buffer allocation to defragment");
143 static int lorunningspace;
144 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
145     "Minimum preferred space used for in-progress I/O");
146 static int hirunningspace;
147 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
148     "Maximum amount of space to use for in-progress I/O");
149 static int dirtybufferflushes;
150 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
151     0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
152 static int altbufferflushes;
153 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
154     0, "Number of fsync flushes to limit dirty buffers");
155 static int recursiveflushes;
156 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
157     0, "Number of flushes skipped due to being recursive");
158 static int numdirtybuffers;
159 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
160     "Number of buffers that are dirty (has unwritten changes) at the moment");
161 static int lodirtybuffers;
162 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
163     "How many buffers we want to have free before bufdaemon can sleep");
164 static int hidirtybuffers;
165 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
166     "When the number of dirty buffers is considered severe");
167 static int dirtybufthresh;
168 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
169     0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
170 static int numfreebuffers;
171 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
172     "Number of free buffers");
173 static int lofreebuffers;
174 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
175    "XXX Unused");
176 static int hifreebuffers;
177 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
178    "XXX Complicatedly unused");
179 static int getnewbufcalls;
180 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
181    "Number of calls to getnewbuf");
182 static int getnewbufrestarts;
183 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
184     "Number of times getnewbuf has had to restart a buffer aquisition");
185 
186 /*
187  * Wakeup point for bufdaemon, as well as indicator of whether it is already
188  * active.  Set to 1 when the bufdaemon is already "on" the queue, 0 when it
189  * is idling.
190  */
191 static int bd_request;
192 
193 /*
194  * This lock synchronizes access to bd_request.
195  */
196 static struct mtx bdlock;
197 
198 /*
199  * bogus page -- for I/O to/from partially complete buffers
200  * this is a temporary solution to the problem, but it is not
201  * really that bad.  it would be better to split the buffer
202  * for input in the case of buffers partially already in memory,
203  * but the code is intricate enough already.
204  */
205 vm_page_t bogus_page;
206 
207 /*
208  * Synchronization (sleep/wakeup) variable for active buffer space requests.
209  * Set when wait starts, cleared prior to wakeup().
210  * Used in runningbufwakeup() and waitrunningbufspace().
211  */
212 static int runningbufreq;
213 
214 /*
215  * This lock protects the runningbufreq and synchronizes runningbufwakeup and
216  * waitrunningbufspace().
217  */
218 static struct mtx rbreqlock;
219 
220 /*
221  * Synchronization (sleep/wakeup) variable for buffer requests.
222  * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
223  * by and/or.
224  * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(),
225  * getnewbuf(), and getblk().
226  */
227 static int needsbuffer;
228 
229 /*
230  * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
231  */
232 static struct mtx nblock;
233 
234 /*
235  * Lock that protects against bwait()/bdone()/B_DONE races.
236  */
237 
238 static struct mtx bdonelock;
239 
240 /*
241  * Lock that protects against bwait()/bdone()/B_DONE races.
242  */
243 static struct mtx bpinlock;
244 
245 /*
246  * Definitions for the buffer free lists.
247  */
248 #define BUFFER_QUEUES	6	/* number of free buffer queues */
249 
250 #define QUEUE_NONE	0	/* on no queue */
251 #define QUEUE_CLEAN	1	/* non-B_DELWRI buffers */
252 #define QUEUE_DIRTY	2	/* B_DELWRI buffers */
253 #define QUEUE_DIRTY_GIANT 3	/* B_DELWRI buffers that need giant */
254 #define QUEUE_EMPTYKVA	4	/* empty buffer headers w/KVA assignment */
255 #define QUEUE_EMPTY	5	/* empty buffer headers */
256 
257 /* Queues for free buffers with various properties */
258 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
259 
260 /* Lock for the bufqueues */
261 static struct mtx bqlock;
262 
263 /*
264  * Single global constant for BUF_WMESG, to avoid getting multiple references.
265  * buf_wmesg is referred from macros.
266  */
267 const char *buf_wmesg = BUF_WMESG;
268 
269 #define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
270 #define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
271 #define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
272 #define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
273 
274 #ifdef DIRECTIO
275 extern void ffs_rawread_setup(void);
276 #endif /* DIRECTIO */
277 /*
278  *	numdirtywakeup:
279  *
280  *	If someone is blocked due to there being too many dirty buffers,
281  *	and numdirtybuffers is now reasonable, wake them up.
282  */
283 
284 static __inline void
285 numdirtywakeup(int level)
286 {
287 
288 	if (numdirtybuffers <= level) {
289 		mtx_lock(&nblock);
290 		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
291 			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
292 			wakeup(&needsbuffer);
293 		}
294 		mtx_unlock(&nblock);
295 	}
296 }
297 
298 /*
299  *	bufspacewakeup:
300  *
301  *	Called when buffer space is potentially available for recovery.
302  *	getnewbuf() will block on this flag when it is unable to free
303  *	sufficient buffer space.  Buffer space becomes recoverable when
304  *	bp's get placed back in the queues.
305  */
306 
307 static __inline void
308 bufspacewakeup(void)
309 {
310 
311 	/*
312 	 * If someone is waiting for BUF space, wake them up.  Even
313 	 * though we haven't freed the kva space yet, the waiting
314 	 * process will be able to now.
315 	 */
316 	mtx_lock(&nblock);
317 	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
318 		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
319 		wakeup(&needsbuffer);
320 	}
321 	mtx_unlock(&nblock);
322 }
323 
324 /*
325  * runningbufwakeup() - in-progress I/O accounting.
326  *
327  */
328 void
329 runningbufwakeup(struct buf *bp)
330 {
331 
332 	if (bp->b_runningbufspace) {
333 		atomic_subtract_int(&runningbufspace, bp->b_runningbufspace);
334 		bp->b_runningbufspace = 0;
335 		mtx_lock(&rbreqlock);
336 		if (runningbufreq && runningbufspace <= lorunningspace) {
337 			runningbufreq = 0;
338 			wakeup(&runningbufreq);
339 		}
340 		mtx_unlock(&rbreqlock);
341 	}
342 }
343 
344 /*
345  *	bufcountwakeup:
346  *
347  *	Called when a buffer has been added to one of the free queues to
348  *	account for the buffer and to wakeup anyone waiting for free buffers.
349  *	This typically occurs when large amounts of metadata are being handled
350  *	by the buffer cache ( else buffer space runs out first, usually ).
351  */
352 
353 static __inline void
354 bufcountwakeup(void)
355 {
356 
357 	atomic_add_int(&numfreebuffers, 1);
358 	mtx_lock(&nblock);
359 	if (needsbuffer) {
360 		needsbuffer &= ~VFS_BIO_NEED_ANY;
361 		if (numfreebuffers >= hifreebuffers)
362 			needsbuffer &= ~VFS_BIO_NEED_FREE;
363 		wakeup(&needsbuffer);
364 	}
365 	mtx_unlock(&nblock);
366 }
367 
368 /*
369  *	waitrunningbufspace()
370  *
371  *	runningbufspace is a measure of the amount of I/O currently
372  *	running.  This routine is used in async-write situations to
373  *	prevent creating huge backups of pending writes to a device.
374  *	Only asynchronous writes are governed by this function.
375  *
376  *	Reads will adjust runningbufspace, but will not block based on it.
377  *	The read load has a side effect of reducing the allowed write load.
378  *
379  *	This does NOT turn an async write into a sync write.  It waits
380  *	for earlier writes to complete and generally returns before the
381  *	caller's write has reached the device.
382  */
383 void
384 waitrunningbufspace(void)
385 {
386 
387 	mtx_lock(&rbreqlock);
388 	while (runningbufspace > hirunningspace) {
389 		++runningbufreq;
390 		msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
391 	}
392 	mtx_unlock(&rbreqlock);
393 }
394 
395 
396 /*
397  *	vfs_buf_test_cache:
398  *
399  *	Called when a buffer is extended.  This function clears the B_CACHE
400  *	bit if the newly extended portion of the buffer does not contain
401  *	valid data.
402  */
403 static __inline
404 void
405 vfs_buf_test_cache(struct buf *bp,
406 		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
407 		  vm_page_t m)
408 {
409 
410 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
411 	if (bp->b_flags & B_CACHE) {
412 		int base = (foff + off) & PAGE_MASK;
413 		if (vm_page_is_valid(m, base, size) == 0)
414 			bp->b_flags &= ~B_CACHE;
415 	}
416 }
417 
418 /* Wake up the buffer deamon if necessary */
419 static __inline
420 void
421 bd_wakeup(int dirtybuflevel)
422 {
423 
424 	mtx_lock(&bdlock);
425 	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
426 		bd_request = 1;
427 		wakeup(&bd_request);
428 	}
429 	mtx_unlock(&bdlock);
430 }
431 
432 /*
433  * bd_speedup - speedup the buffer cache flushing code
434  */
435 
436 static __inline
437 void
438 bd_speedup(void)
439 {
440 
441 	bd_wakeup(1);
442 }
443 
444 /*
445  * Calculating buffer cache scaling values and reserve space for buffer
446  * headers.  This is called during low level kernel initialization and
447  * may be called more then once.  We CANNOT write to the memory area
448  * being reserved at this time.
449  */
450 caddr_t
451 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
452 {
453 
454 	/*
455 	 * physmem_est is in pages.  Convert it to kilobytes (assumes
456 	 * PAGE_SIZE is >= 1K)
457 	 */
458 	physmem_est = physmem_est * (PAGE_SIZE / 1024);
459 
460 	/*
461 	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
462 	 * For the first 64MB of ram nominally allocate sufficient buffers to
463 	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
464 	 * buffers to cover 1/20 of our ram over 64MB.  When auto-sizing
465 	 * the buffer cache we limit the eventual kva reservation to
466 	 * maxbcache bytes.
467 	 *
468 	 * factor represents the 1/4 x ram conversion.
469 	 */
470 	if (nbuf == 0) {
471 		int factor = 4 * BKVASIZE / 1024;
472 
473 		nbuf = 50;
474 		if (physmem_est > 4096)
475 			nbuf += min((physmem_est - 4096) / factor,
476 			    65536 / factor);
477 		if (physmem_est > 65536)
478 			nbuf += (physmem_est - 65536) * 2 / (factor * 5);
479 
480 		if (maxbcache && nbuf > maxbcache / BKVASIZE)
481 			nbuf = maxbcache / BKVASIZE;
482 	}
483 
484 #if 0
485 	/*
486 	 * Do not allow the buffer_map to be more then 1/2 the size of the
487 	 * kernel_map.
488 	 */
489 	if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
490 	    (BKVASIZE * 2)) {
491 		nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
492 		    (BKVASIZE * 2);
493 		printf("Warning: nbufs capped at %d\n", nbuf);
494 	}
495 #endif
496 
497 	/*
498 	 * swbufs are used as temporary holders for I/O, such as paging I/O.
499 	 * We have no less then 16 and no more then 256.
500 	 */
501 	nswbuf = max(min(nbuf/4, 256), 16);
502 #ifdef NSWBUF_MIN
503 	if (nswbuf < NSWBUF_MIN)
504 		nswbuf = NSWBUF_MIN;
505 #endif
506 #ifdef DIRECTIO
507 	ffs_rawread_setup();
508 #endif
509 
510 	/*
511 	 * Reserve space for the buffer cache buffers
512 	 */
513 	swbuf = (void *)v;
514 	v = (caddr_t)(swbuf + nswbuf);
515 	buf = (void *)v;
516 	v = (caddr_t)(buf + nbuf);
517 
518 	return(v);
519 }
520 
521 /* Initialize the buffer subsystem.  Called before use of any buffers. */
522 void
523 bufinit(void)
524 {
525 	struct buf *bp;
526 	int i;
527 
528 	mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF);
529 	mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
530 	mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
531 	mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
532 	mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF);
533 	mtx_init(&bpinlock, "bpin lock", NULL, MTX_DEF);
534 
535 	/* next, make a null set of free lists */
536 	for (i = 0; i < BUFFER_QUEUES; i++)
537 		TAILQ_INIT(&bufqueues[i]);
538 
539 	/* finally, initialize each buffer header and stick on empty q */
540 	for (i = 0; i < nbuf; i++) {
541 		bp = &buf[i];
542 		bzero(bp, sizeof *bp);
543 		bp->b_flags = B_INVAL;	/* we're just an empty header */
544 		bp->b_rcred = NOCRED;
545 		bp->b_wcred = NOCRED;
546 		bp->b_qindex = QUEUE_EMPTY;
547 		bp->b_vflags = 0;
548 		bp->b_xflags = 0;
549 		LIST_INIT(&bp->b_dep);
550 		BUF_LOCKINIT(bp);
551 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
552 	}
553 
554 	/*
555 	 * maxbufspace is the absolute maximum amount of buffer space we are
556 	 * allowed to reserve in KVM and in real terms.  The absolute maximum
557 	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
558 	 * used by most other processes.  The differential is required to
559 	 * ensure that buf_daemon is able to run when other processes might
560 	 * be blocked waiting for buffer space.
561 	 *
562 	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
563 	 * this may result in KVM fragmentation which is not handled optimally
564 	 * by the system.
565 	 */
566 	maxbufspace = nbuf * BKVASIZE;
567 	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
568 	lobufspace = hibufspace - MAXBSIZE;
569 
570 	lorunningspace = 512 * 1024;
571 	hirunningspace = 1024 * 1024;
572 
573 /*
574  * Limit the amount of malloc memory since it is wired permanently into
575  * the kernel space.  Even though this is accounted for in the buffer
576  * allocation, we don't want the malloced region to grow uncontrolled.
577  * The malloc scheme improves memory utilization significantly on average
578  * (small) directories.
579  */
580 	maxbufmallocspace = hibufspace / 20;
581 
582 /*
583  * Reduce the chance of a deadlock occuring by limiting the number
584  * of delayed-write dirty buffers we allow to stack up.
585  */
586 	hidirtybuffers = nbuf / 4 + 20;
587 	dirtybufthresh = hidirtybuffers * 9 / 10;
588 	numdirtybuffers = 0;
589 /*
590  * To support extreme low-memory systems, make sure hidirtybuffers cannot
591  * eat up all available buffer space.  This occurs when our minimum cannot
592  * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
593  * BKVASIZE'd (8K) buffers.
594  */
595 	while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
596 		hidirtybuffers >>= 1;
597 	}
598 	lodirtybuffers = hidirtybuffers / 2;
599 
600 /*
601  * Try to keep the number of free buffers in the specified range,
602  * and give special processes (e.g. like buf_daemon) access to an
603  * emergency reserve.
604  */
605 	lofreebuffers = nbuf / 18 + 5;
606 	hifreebuffers = 2 * lofreebuffers;
607 	numfreebuffers = nbuf;
608 
609 /*
610  * Maximum number of async ops initiated per buf_daemon loop.  This is
611  * somewhat of a hack at the moment, we really need to limit ourselves
612  * based on the number of bytes of I/O in-transit that were initiated
613  * from buf_daemon.
614  */
615 
616 	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
617 	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
618 }
619 
620 /*
621  * bfreekva() - free the kva allocation for a buffer.
622  *
623  *	Since this call frees up buffer space, we call bufspacewakeup().
624  */
625 static void
626 bfreekva(struct buf *bp)
627 {
628 
629 	if (bp->b_kvasize) {
630 		atomic_add_int(&buffreekvacnt, 1);
631 		atomic_subtract_int(&bufspace, bp->b_kvasize);
632 		vm_map_lock(buffer_map);
633 		vm_map_delete(buffer_map,
634 		    (vm_offset_t) bp->b_kvabase,
635 		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize
636 		);
637 		vm_map_unlock(buffer_map);
638 		bp->b_kvasize = 0;
639 		bufspacewakeup();
640 	}
641 }
642 
643 /*
644  *	bremfree:
645  *
646  *	Mark the buffer for removal from the appropriate free list in brelse.
647  *
648  */
649 void
650 bremfree(struct buf *bp)
651 {
652 
653 	CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
654 	KASSERT(BUF_REFCNT(bp), ("bremfree: buf must be locked."));
655 	KASSERT((bp->b_flags & B_REMFREE) == 0,
656 	    ("bremfree: buffer %p already marked for delayed removal.", bp));
657 	KASSERT(bp->b_qindex != QUEUE_NONE,
658 	    ("bremfree: buffer %p not on a queue.", bp));
659 
660 	bp->b_flags |= B_REMFREE;
661 	/* Fixup numfreebuffers count.  */
662 	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
663 		atomic_subtract_int(&numfreebuffers, 1);
664 }
665 
666 /*
667  *	bremfreef:
668  *
669  *	Force an immediate removal from a free list.  Used only in nfs when
670  *	it abuses the b_freelist pointer.
671  */
672 void
673 bremfreef(struct buf *bp)
674 {
675 	mtx_lock(&bqlock);
676 	bremfreel(bp);
677 	mtx_unlock(&bqlock);
678 }
679 
680 /*
681  *	bremfreel:
682  *
683  *	Removes a buffer from the free list, must be called with the
684  *	bqlock held.
685  */
686 static void
687 bremfreel(struct buf *bp)
688 {
689 	CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
690 	    bp, bp->b_vp, bp->b_flags);
691 	KASSERT(BUF_REFCNT(bp), ("bremfreel: buffer %p not locked.", bp));
692 	KASSERT(bp->b_qindex != QUEUE_NONE,
693 	    ("bremfreel: buffer %p not on a queue.", bp));
694 	mtx_assert(&bqlock, MA_OWNED);
695 
696 	TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
697 	bp->b_qindex = QUEUE_NONE;
698 	/*
699 	 * If this was a delayed bremfree() we only need to remove the buffer
700 	 * from the queue and return the stats are already done.
701 	 */
702 	if (bp->b_flags & B_REMFREE) {
703 		bp->b_flags &= ~B_REMFREE;
704 		return;
705 	}
706 	/*
707 	 * Fixup numfreebuffers count.  If the buffer is invalid or not
708 	 * delayed-write, the buffer was free and we must decrement
709 	 * numfreebuffers.
710 	 */
711 	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)
712 		atomic_subtract_int(&numfreebuffers, 1);
713 }
714 
715 
716 /*
717  * Get a buffer with the specified data.  Look in the cache first.  We
718  * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
719  * is set, the buffer is valid and we do not have to do anything ( see
720  * getblk() ).  This is really just a special case of breadn().
721  */
722 int
723 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
724     struct buf **bpp)
725 {
726 
727 	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
728 }
729 
730 /*
731  * Attempt to initiate asynchronous I/O on read-ahead blocks.  We must
732  * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
733  * the buffer is valid and we do not have to do anything.
734  */
735 void
736 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
737     int cnt, struct ucred * cred)
738 {
739 	struct buf *rabp;
740 	int i;
741 
742 	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
743 		if (inmem(vp, *rablkno))
744 			continue;
745 		rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
746 
747 		if ((rabp->b_flags & B_CACHE) == 0) {
748 			if (curthread != PCPU_GET(idlethread))
749 				curthread->td_proc->p_stats->p_ru.ru_inblock++;
750 			rabp->b_flags |= B_ASYNC;
751 			rabp->b_flags &= ~B_INVAL;
752 			rabp->b_ioflags &= ~BIO_ERROR;
753 			rabp->b_iocmd = BIO_READ;
754 			if (rabp->b_rcred == NOCRED && cred != NOCRED)
755 				rabp->b_rcred = crhold(cred);
756 			vfs_busy_pages(rabp, 0);
757 			BUF_KERNPROC(rabp);
758 			rabp->b_iooffset = dbtob(rabp->b_blkno);
759 			bstrategy(rabp);
760 		} else {
761 			brelse(rabp);
762 		}
763 	}
764 }
765 
766 /*
767  * Operates like bread, but also starts asynchronous I/O on
768  * read-ahead blocks.
769  */
770 int
771 breadn(struct vnode * vp, daddr_t blkno, int size,
772     daddr_t * rablkno, int *rabsize,
773     int cnt, struct ucred * cred, struct buf **bpp)
774 {
775 	struct buf *bp;
776 	int rv = 0, readwait = 0;
777 
778 	CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
779 	*bpp = bp = getblk(vp, blkno, size, 0, 0, 0);
780 
781 	/* if not found in cache, do some I/O */
782 	if ((bp->b_flags & B_CACHE) == 0) {
783 		if (curthread != PCPU_GET(idlethread))
784 			curthread->td_proc->p_stats->p_ru.ru_inblock++;
785 		bp->b_iocmd = BIO_READ;
786 		bp->b_flags &= ~B_INVAL;
787 		bp->b_ioflags &= ~BIO_ERROR;
788 		if (bp->b_rcred == NOCRED && cred != NOCRED)
789 			bp->b_rcred = crhold(cred);
790 		vfs_busy_pages(bp, 0);
791 		bp->b_iooffset = dbtob(bp->b_blkno);
792 		bstrategy(bp);
793 		++readwait;
794 	}
795 
796 	breada(vp, rablkno, rabsize, cnt, cred);
797 
798 	if (readwait) {
799 		rv = bufwait(bp);
800 	}
801 	return (rv);
802 }
803 
804 /*
805  * Write, release buffer on completion.  (Done by iodone
806  * if async).  Do not bother writing anything if the buffer
807  * is invalid.
808  *
809  * Note that we set B_CACHE here, indicating that buffer is
810  * fully valid and thus cacheable.  This is true even of NFS
811  * now so we set it generally.  This could be set either here
812  * or in biodone() since the I/O is synchronous.  We put it
813  * here.
814  */
815 int
816 bufwrite(struct buf *bp)
817 {
818 	int oldflags;
819 	struct vnode *vp;
820 	int vp_md;
821 
822 	CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
823 	if (bp->b_flags & B_INVAL) {
824 		brelse(bp);
825 		return (0);
826 	}
827 
828 	oldflags = bp->b_flags;
829 
830 	if (BUF_REFCNT(bp) == 0)
831 		panic("bufwrite: buffer is not busy???");
832 
833 	if (bp->b_pin_count > 0)
834 		bunpin_wait(bp);
835 
836 	KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
837 	    ("FFS background buffer should not get here %p", bp));
838 
839 	vp = bp->b_vp;
840 	if (vp)
841 		vp_md = vp->v_vflag & VV_MD;
842 	else
843 		vp_md = 0;
844 
845 	/* Mark the buffer clean */
846 	bundirty(bp);
847 
848 	bp->b_flags &= ~B_DONE;
849 	bp->b_ioflags &= ~BIO_ERROR;
850 	bp->b_flags |= B_CACHE;
851 	bp->b_iocmd = BIO_WRITE;
852 
853 	bufobj_wref(bp->b_bufobj);
854 	vfs_busy_pages(bp, 1);
855 
856 	/*
857 	 * Normal bwrites pipeline writes
858 	 */
859 	bp->b_runningbufspace = bp->b_bufsize;
860 	atomic_add_int(&runningbufspace, bp->b_runningbufspace);
861 
862 	if (curthread != PCPU_GET(idlethread))
863 		curthread->td_proc->p_stats->p_ru.ru_oublock++;
864 	if (oldflags & B_ASYNC)
865 		BUF_KERNPROC(bp);
866 	bp->b_iooffset = dbtob(bp->b_blkno);
867 	bstrategy(bp);
868 
869 	if ((oldflags & B_ASYNC) == 0) {
870 		int rtval = bufwait(bp);
871 		brelse(bp);
872 		return (rtval);
873 	} else {
874 		/*
875 		 * don't allow the async write to saturate the I/O
876 		 * system.  We will not deadlock here because
877 		 * we are blocking waiting for I/O that is already in-progress
878 		 * to complete. We do not block here if it is the update
879 		 * or syncer daemon trying to clean up as that can lead
880 		 * to deadlock.
881 		 */
882 		if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
883 			waitrunningbufspace();
884 	}
885 
886 	return (0);
887 }
888 
889 /*
890  * Delayed write. (Buffer is marked dirty).  Do not bother writing
891  * anything if the buffer is marked invalid.
892  *
893  * Note that since the buffer must be completely valid, we can safely
894  * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
895  * biodone() in order to prevent getblk from writing the buffer
896  * out synchronously.
897  */
898 void
899 bdwrite(struct buf *bp)
900 {
901 	struct thread *td = curthread;
902 	struct vnode *vp;
903 	struct buf *nbp;
904 	struct bufobj *bo;
905 
906 	CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
907 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
908 	KASSERT(BUF_REFCNT(bp) != 0, ("bdwrite: buffer is not busy"));
909 
910 	if (bp->b_flags & B_INVAL) {
911 		brelse(bp);
912 		return;
913 	}
914 
915 	/*
916 	 * If we have too many dirty buffers, don't create any more.
917 	 * If we are wildly over our limit, then force a complete
918 	 * cleanup. Otherwise, just keep the situation from getting
919 	 * out of control. Note that we have to avoid a recursive
920 	 * disaster and not try to clean up after our own cleanup!
921 	 */
922 	vp = bp->b_vp;
923 	bo = bp->b_bufobj;
924 	if ((td->td_pflags & TDP_COWINPROGRESS) == 0) {
925 		BO_LOCK(bo);
926 		if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
927 			BO_UNLOCK(bo);
928 			(void) VOP_FSYNC(vp, MNT_NOWAIT, td);
929 			altbufferflushes++;
930 		} else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
931 			/*
932 			 * Try to find a buffer to flush.
933 			 */
934 			TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
935 				if ((nbp->b_vflags & BV_BKGRDINPROG) ||
936 				    BUF_LOCK(nbp,
937 				    LK_EXCLUSIVE | LK_NOWAIT, NULL))
938 					continue;
939 				if (bp == nbp)
940 					panic("bdwrite: found ourselves");
941 				BO_UNLOCK(bo);
942 				/* Don't countdeps with the bo lock held. */
943 				if (buf_countdeps(nbp, 0)) {
944 					BO_LOCK(bo);
945 					BUF_UNLOCK(nbp);
946 					continue;
947 				}
948 				if (nbp->b_flags & B_CLUSTEROK) {
949 					vfs_bio_awrite(nbp);
950 				} else {
951 					bremfree(nbp);
952 					bawrite(nbp);
953 				}
954 				dirtybufferflushes++;
955 				break;
956 			}
957 			if (nbp == NULL)
958 				BO_UNLOCK(bo);
959 		} else
960 			BO_UNLOCK(bo);
961 	} else
962 		recursiveflushes++;
963 
964 	bdirty(bp);
965 	/*
966 	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
967 	 * true even of NFS now.
968 	 */
969 	bp->b_flags |= B_CACHE;
970 
971 	/*
972 	 * This bmap keeps the system from needing to do the bmap later,
973 	 * perhaps when the system is attempting to do a sync.  Since it
974 	 * is likely that the indirect block -- or whatever other datastructure
975 	 * that the filesystem needs is still in memory now, it is a good
976 	 * thing to do this.  Note also, that if the pageout daemon is
977 	 * requesting a sync -- there might not be enough memory to do
978 	 * the bmap then...  So, this is important to do.
979 	 */
980 	if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
981 		VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
982 	}
983 
984 	/*
985 	 * Set the *dirty* buffer range based upon the VM system dirty pages.
986 	 */
987 	vfs_setdirty(bp);
988 
989 	/*
990 	 * We need to do this here to satisfy the vnode_pager and the
991 	 * pageout daemon, so that it thinks that the pages have been
992 	 * "cleaned".  Note that since the pages are in a delayed write
993 	 * buffer -- the VFS layer "will" see that the pages get written
994 	 * out on the next sync, or perhaps the cluster will be completed.
995 	 */
996 	vfs_clean_pages(bp);
997 	bqrelse(bp);
998 
999 	/*
1000 	 * Wakeup the buffer flushing daemon if we have a lot of dirty
1001 	 * buffers (midpoint between our recovery point and our stall
1002 	 * point).
1003 	 */
1004 	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1005 
1006 	/*
1007 	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1008 	 * due to the softdep code.
1009 	 */
1010 }
1011 
1012 /*
1013  *	bdirty:
1014  *
1015  *	Turn buffer into delayed write request.  We must clear BIO_READ and
1016  *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
1017  *	itself to properly update it in the dirty/clean lists.  We mark it
1018  *	B_DONE to ensure that any asynchronization of the buffer properly
1019  *	clears B_DONE ( else a panic will occur later ).
1020  *
1021  *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1022  *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
1023  *	should only be called if the buffer is known-good.
1024  *
1025  *	Since the buffer is not on a queue, we do not update the numfreebuffers
1026  *	count.
1027  *
1028  *	The buffer must be on QUEUE_NONE.
1029  */
1030 void
1031 bdirty(struct buf *bp)
1032 {
1033 
1034 	CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1035 	    bp, bp->b_vp, bp->b_flags);
1036 	KASSERT(BUF_REFCNT(bp) == 1, ("bdirty: bp %p not locked",bp));
1037 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1038 	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1039 	    ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1040 	bp->b_flags &= ~(B_RELBUF);
1041 	bp->b_iocmd = BIO_WRITE;
1042 
1043 	if ((bp->b_flags & B_DELWRI) == 0) {
1044 		bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1045 		reassignbuf(bp);
1046 		atomic_add_int(&numdirtybuffers, 1);
1047 		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
1048 	}
1049 }
1050 
1051 /*
1052  *	bundirty:
1053  *
1054  *	Clear B_DELWRI for buffer.
1055  *
1056  *	Since the buffer is not on a queue, we do not update the numfreebuffers
1057  *	count.
1058  *
1059  *	The buffer must be on QUEUE_NONE.
1060  */
1061 
1062 void
1063 bundirty(struct buf *bp)
1064 {
1065 
1066 	CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1067 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1068 	KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1069 	    ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1070 	KASSERT(BUF_REFCNT(bp) == 1, ("bundirty: bp %p not locked",bp));
1071 
1072 	if (bp->b_flags & B_DELWRI) {
1073 		bp->b_flags &= ~B_DELWRI;
1074 		reassignbuf(bp);
1075 		atomic_subtract_int(&numdirtybuffers, 1);
1076 		numdirtywakeup(lodirtybuffers);
1077 	}
1078 	/*
1079 	 * Since it is now being written, we can clear its deferred write flag.
1080 	 */
1081 	bp->b_flags &= ~B_DEFERRED;
1082 }
1083 
1084 /*
1085  *	bawrite:
1086  *
1087  *	Asynchronous write.  Start output on a buffer, but do not wait for
1088  *	it to complete.  The buffer is released when the output completes.
1089  *
1090  *	bwrite() ( or the VOP routine anyway ) is responsible for handling
1091  *	B_INVAL buffers.  Not us.
1092  */
1093 void
1094 bawrite(struct buf *bp)
1095 {
1096 
1097 	bp->b_flags |= B_ASYNC;
1098 	(void) bwrite(bp);
1099 }
1100 
1101 /*
1102  *	bwillwrite:
1103  *
1104  *	Called prior to the locking of any vnodes when we are expecting to
1105  *	write.  We do not want to starve the buffer cache with too many
1106  *	dirty buffers so we block here.  By blocking prior to the locking
1107  *	of any vnodes we attempt to avoid the situation where a locked vnode
1108  *	prevents the various system daemons from flushing related buffers.
1109  */
1110 
1111 void
1112 bwillwrite(void)
1113 {
1114 
1115 	if (numdirtybuffers >= hidirtybuffers) {
1116 		mtx_lock(&nblock);
1117 		while (numdirtybuffers >= hidirtybuffers) {
1118 			bd_wakeup(1);
1119 			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1120 			msleep(&needsbuffer, &nblock,
1121 			    (PRIBIO + 4), "flswai", 0);
1122 		}
1123 		mtx_unlock(&nblock);
1124 	}
1125 }
1126 
1127 /*
1128  * Return true if we have too many dirty buffers.
1129  */
1130 int
1131 buf_dirty_count_severe(void)
1132 {
1133 
1134 	return(numdirtybuffers >= hidirtybuffers);
1135 }
1136 
1137 /*
1138  *	brelse:
1139  *
1140  *	Release a busy buffer and, if requested, free its resources.  The
1141  *	buffer will be stashed in the appropriate bufqueue[] allowing it
1142  *	to be accessed later as a cache entity or reused for other purposes.
1143  */
1144 void
1145 brelse(struct buf *bp)
1146 {
1147 	CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1148 	    bp, bp->b_vp, bp->b_flags);
1149 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1150 	    ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1151 
1152 	if (bp->b_flags & B_MANAGED) {
1153 		bqrelse(bp);
1154 		return;
1155 	}
1156 
1157 	if (bp->b_iocmd == BIO_WRITE &&
1158 	    (bp->b_ioflags & BIO_ERROR) &&
1159 	    !(bp->b_flags & B_INVAL)) {
1160 		/*
1161 		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1162 		 * pages from being scrapped.  If B_INVAL is set then
1163 		 * this case is not run and the next case is run to
1164 		 * destroy the buffer.  B_INVAL can occur if the buffer
1165 		 * is outside the range supported by the underlying device.
1166 		 */
1167 		bp->b_ioflags &= ~BIO_ERROR;
1168 		bdirty(bp);
1169 	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1170 	    (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1171 		/*
1172 		 * Either a failed I/O or we were asked to free or not
1173 		 * cache the buffer.
1174 		 */
1175 		bp->b_flags |= B_INVAL;
1176 		if (LIST_FIRST(&bp->b_dep) != NULL)
1177 			buf_deallocate(bp);
1178 		if (bp->b_flags & B_DELWRI) {
1179 			atomic_subtract_int(&numdirtybuffers, 1);
1180 			numdirtywakeup(lodirtybuffers);
1181 		}
1182 		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1183 		if ((bp->b_flags & B_VMIO) == 0) {
1184 			if (bp->b_bufsize)
1185 				allocbuf(bp, 0);
1186 			if (bp->b_vp)
1187 				brelvp(bp);
1188 		}
1189 	}
1190 
1191 	/*
1192 	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1193 	 * is called with B_DELWRI set, the underlying pages may wind up
1194 	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1195 	 * because pages associated with a B_DELWRI bp are marked clean.
1196 	 *
1197 	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1198 	 * if B_DELWRI is set.
1199 	 *
1200 	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1201 	 * on pages to return pages to the VM page queues.
1202 	 */
1203 	if (bp->b_flags & B_DELWRI)
1204 		bp->b_flags &= ~B_RELBUF;
1205 	else if (vm_page_count_severe()) {
1206 		/*
1207 		 * XXX This lock may not be necessary since BKGRDINPROG
1208 		 * cannot be set while we hold the buf lock, it can only be
1209 		 * cleared if it is already pending.
1210 		 */
1211 		if (bp->b_vp) {
1212 			BO_LOCK(bp->b_bufobj);
1213 			if (!(bp->b_vflags & BV_BKGRDINPROG))
1214 				bp->b_flags |= B_RELBUF;
1215 			BO_UNLOCK(bp->b_bufobj);
1216 		} else
1217 			bp->b_flags |= B_RELBUF;
1218 	}
1219 
1220 	/*
1221 	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1222 	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1223 	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1224 	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1225 	 *
1226 	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1227 	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1228 	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1229 	 *
1230 	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1231 	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1232 	 * the commit state and we cannot afford to lose the buffer. If the
1233 	 * buffer has a background write in progress, we need to keep it
1234 	 * around to prevent it from being reconstituted and starting a second
1235 	 * background write.
1236 	 */
1237 	if ((bp->b_flags & B_VMIO)
1238 	    && !(bp->b_vp->v_mount != NULL &&
1239 		 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1240 		 !vn_isdisk(bp->b_vp, NULL) &&
1241 		 (bp->b_flags & B_DELWRI))
1242 	    ) {
1243 
1244 		int i, j, resid;
1245 		vm_page_t m;
1246 		off_t foff;
1247 		vm_pindex_t poff;
1248 		vm_object_t obj;
1249 
1250 		obj = bp->b_bufobj->bo_object;
1251 
1252 		/*
1253 		 * Get the base offset and length of the buffer.  Note that
1254 		 * in the VMIO case if the buffer block size is not
1255 		 * page-aligned then b_data pointer may not be page-aligned.
1256 		 * But our b_pages[] array *IS* page aligned.
1257 		 *
1258 		 * block sizes less then DEV_BSIZE (usually 512) are not
1259 		 * supported due to the page granularity bits (m->valid,
1260 		 * m->dirty, etc...).
1261 		 *
1262 		 * See man buf(9) for more information
1263 		 */
1264 		resid = bp->b_bufsize;
1265 		foff = bp->b_offset;
1266 		VM_OBJECT_LOCK(obj);
1267 		for (i = 0; i < bp->b_npages; i++) {
1268 			int had_bogus = 0;
1269 
1270 			m = bp->b_pages[i];
1271 
1272 			/*
1273 			 * If we hit a bogus page, fixup *all* the bogus pages
1274 			 * now.
1275 			 */
1276 			if (m == bogus_page) {
1277 				poff = OFF_TO_IDX(bp->b_offset);
1278 				had_bogus = 1;
1279 
1280 				for (j = i; j < bp->b_npages; j++) {
1281 					vm_page_t mtmp;
1282 					mtmp = bp->b_pages[j];
1283 					if (mtmp == bogus_page) {
1284 						mtmp = vm_page_lookup(obj, poff + j);
1285 						if (!mtmp) {
1286 							panic("brelse: page missing\n");
1287 						}
1288 						bp->b_pages[j] = mtmp;
1289 					}
1290 				}
1291 
1292 				if ((bp->b_flags & B_INVAL) == 0) {
1293 					pmap_qenter(
1294 					    trunc_page((vm_offset_t)bp->b_data),
1295 					    bp->b_pages, bp->b_npages);
1296 				}
1297 				m = bp->b_pages[i];
1298 			}
1299 			if ((bp->b_flags & B_NOCACHE) ||
1300 			    (bp->b_ioflags & BIO_ERROR)) {
1301 				int poffset = foff & PAGE_MASK;
1302 				int presid = resid > (PAGE_SIZE - poffset) ?
1303 					(PAGE_SIZE - poffset) : resid;
1304 
1305 				KASSERT(presid >= 0, ("brelse: extra page"));
1306 				vm_page_lock_queues();
1307 				vm_page_set_invalid(m, poffset, presid);
1308 				vm_page_unlock_queues();
1309 				if (had_bogus)
1310 					printf("avoided corruption bug in bogus_page/brelse code\n");
1311 			}
1312 			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1313 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1314 		}
1315 		VM_OBJECT_UNLOCK(obj);
1316 		if (bp->b_flags & (B_INVAL | B_RELBUF))
1317 			vfs_vmio_release(bp);
1318 
1319 	} else if (bp->b_flags & B_VMIO) {
1320 
1321 		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1322 			vfs_vmio_release(bp);
1323 		}
1324 
1325 	} else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1326 		if (bp->b_bufsize != 0)
1327 			allocbuf(bp, 0);
1328 		if (bp->b_vp != NULL)
1329 			brelvp(bp);
1330 	}
1331 
1332 	if (BUF_REFCNT(bp) > 1) {
1333 		/* do not release to free list */
1334 		BUF_UNLOCK(bp);
1335 		return;
1336 	}
1337 
1338 	/* enqueue */
1339 	mtx_lock(&bqlock);
1340 	/* Handle delayed bremfree() processing. */
1341 	if (bp->b_flags & B_REMFREE)
1342 		bremfreel(bp);
1343 	if (bp->b_qindex != QUEUE_NONE)
1344 		panic("brelse: free buffer onto another queue???");
1345 
1346 	/* buffers with no memory */
1347 	if (bp->b_bufsize == 0) {
1348 		bp->b_flags |= B_INVAL;
1349 		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1350 		if (bp->b_vflags & BV_BKGRDINPROG)
1351 			panic("losing buffer 1");
1352 		if (bp->b_kvasize) {
1353 			bp->b_qindex = QUEUE_EMPTYKVA;
1354 		} else {
1355 			bp->b_qindex = QUEUE_EMPTY;
1356 		}
1357 		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1358 	/* buffers with junk contents */
1359 	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1360 	    (bp->b_ioflags & BIO_ERROR)) {
1361 		bp->b_flags |= B_INVAL;
1362 		bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1363 		if (bp->b_vflags & BV_BKGRDINPROG)
1364 			panic("losing buffer 2");
1365 		bp->b_qindex = QUEUE_CLEAN;
1366 		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1367 	/* remaining buffers */
1368 	} else {
1369 		if ((bp->b_flags & (B_DELWRI|B_NEEDSGIANT)) ==
1370 		    (B_DELWRI|B_NEEDSGIANT))
1371 			bp->b_qindex = QUEUE_DIRTY_GIANT;
1372 		if (bp->b_flags & B_DELWRI)
1373 			bp->b_qindex = QUEUE_DIRTY;
1374 		else
1375 			bp->b_qindex = QUEUE_CLEAN;
1376 		if (bp->b_flags & B_AGE)
1377 			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1378 		else
1379 			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1380 	}
1381 	mtx_unlock(&bqlock);
1382 
1383 	/*
1384 	 * If B_INVAL and B_DELWRI is set, clear B_DELWRI.  We have already
1385 	 * placed the buffer on the correct queue.  We must also disassociate
1386 	 * the device and vnode for a B_INVAL buffer so gbincore() doesn't
1387 	 * find it.
1388 	 */
1389 	if (bp->b_flags & B_INVAL) {
1390 		if (bp->b_flags & B_DELWRI)
1391 			bundirty(bp);
1392 		if (bp->b_vp)
1393 			brelvp(bp);
1394 	}
1395 
1396 	/*
1397 	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1398 	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1399 	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1400 	 * if B_INVAL is set ).
1401 	 */
1402 
1403 	if (!(bp->b_flags & B_DELWRI))
1404 		bufcountwakeup();
1405 
1406 	/*
1407 	 * Something we can maybe free or reuse
1408 	 */
1409 	if (bp->b_bufsize || bp->b_kvasize)
1410 		bufspacewakeup();
1411 
1412 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1413 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1414 		panic("brelse: not dirty");
1415 	/* unlock */
1416 	BUF_UNLOCK(bp);
1417 }
1418 
1419 /*
1420  * Release a buffer back to the appropriate queue but do not try to free
1421  * it.  The buffer is expected to be used again soon.
1422  *
1423  * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1424  * biodone() to requeue an async I/O on completion.  It is also used when
1425  * known good buffers need to be requeued but we think we may need the data
1426  * again soon.
1427  *
1428  * XXX we should be able to leave the B_RELBUF hint set on completion.
1429  */
1430 void
1431 bqrelse(struct buf *bp)
1432 {
1433 	CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1434 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1435 	    ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1436 
1437 	if (BUF_REFCNT(bp) > 1) {
1438 		/* do not release to free list */
1439 		BUF_UNLOCK(bp);
1440 		return;
1441 	}
1442 
1443 	if (bp->b_flags & B_MANAGED) {
1444 		if (bp->b_flags & B_REMFREE) {
1445 			mtx_lock(&bqlock);
1446 			bremfreel(bp);
1447 			mtx_unlock(&bqlock);
1448 		}
1449 		bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1450 		BUF_UNLOCK(bp);
1451 		return;
1452 	}
1453 
1454 	mtx_lock(&bqlock);
1455 	/* Handle delayed bremfree() processing. */
1456 	if (bp->b_flags & B_REMFREE)
1457 		bremfreel(bp);
1458 	if (bp->b_qindex != QUEUE_NONE)
1459 		panic("bqrelse: free buffer onto another queue???");
1460 	/* buffers with stale but valid contents */
1461 	if (bp->b_flags & B_DELWRI) {
1462 		if (bp->b_flags & B_NEEDSGIANT)
1463 			bp->b_qindex = QUEUE_DIRTY_GIANT;
1464 		else
1465 			bp->b_qindex = QUEUE_DIRTY;
1466 		TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1467 	} else {
1468 		/*
1469 		 * XXX This lock may not be necessary since BKGRDINPROG
1470 		 * cannot be set while we hold the buf lock, it can only be
1471 		 * cleared if it is already pending.
1472 		 */
1473 		BO_LOCK(bp->b_bufobj);
1474 		if (!vm_page_count_severe() || bp->b_vflags & BV_BKGRDINPROG) {
1475 			BO_UNLOCK(bp->b_bufobj);
1476 			bp->b_qindex = QUEUE_CLEAN;
1477 			TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp,
1478 			    b_freelist);
1479 		} else {
1480 			/*
1481 			 * We are too low on memory, we have to try to free
1482 			 * the buffer (most importantly: the wired pages
1483 			 * making up its backing store) *now*.
1484 			 */
1485 			BO_UNLOCK(bp->b_bufobj);
1486 			mtx_unlock(&bqlock);
1487 			brelse(bp);
1488 			return;
1489 		}
1490 	}
1491 	mtx_unlock(&bqlock);
1492 
1493 	if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1494 		bufcountwakeup();
1495 
1496 	/*
1497 	 * Something we can maybe free or reuse.
1498 	 */
1499 	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1500 		bufspacewakeup();
1501 
1502 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1503 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1504 		panic("bqrelse: not dirty");
1505 	/* unlock */
1506 	BUF_UNLOCK(bp);
1507 }
1508 
1509 /* Give pages used by the bp back to the VM system (where possible) */
1510 static void
1511 vfs_vmio_release(struct buf *bp)
1512 {
1513 	int i;
1514 	vm_page_t m;
1515 
1516 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
1517 	vm_page_lock_queues();
1518 	for (i = 0; i < bp->b_npages; i++) {
1519 		m = bp->b_pages[i];
1520 		bp->b_pages[i] = NULL;
1521 		/*
1522 		 * In order to keep page LRU ordering consistent, put
1523 		 * everything on the inactive queue.
1524 		 */
1525 		vm_page_unwire(m, 0);
1526 		/*
1527 		 * We don't mess with busy pages, it is
1528 		 * the responsibility of the process that
1529 		 * busied the pages to deal with them.
1530 		 */
1531 		if ((m->oflags & VPO_BUSY) || (m->busy != 0))
1532 			continue;
1533 
1534 		if (m->wire_count == 0) {
1535 			/*
1536 			 * Might as well free the page if we can and it has
1537 			 * no valid data.  We also free the page if the
1538 			 * buffer was used for direct I/O
1539 			 */
1540 			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1541 			    m->hold_count == 0) {
1542 				vm_page_free(m);
1543 			} else if (bp->b_flags & B_DIRECT) {
1544 				vm_page_try_to_free(m);
1545 			} else if (vm_page_count_severe()) {
1546 				vm_page_try_to_cache(m);
1547 			}
1548 		}
1549 	}
1550 	vm_page_unlock_queues();
1551 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
1552 	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1553 
1554 	if (bp->b_bufsize) {
1555 		bufspacewakeup();
1556 		bp->b_bufsize = 0;
1557 	}
1558 	bp->b_npages = 0;
1559 	bp->b_flags &= ~B_VMIO;
1560 	if (bp->b_vp)
1561 		brelvp(bp);
1562 }
1563 
1564 /*
1565  * Check to see if a block at a particular lbn is available for a clustered
1566  * write.
1567  */
1568 static int
1569 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1570 {
1571 	struct buf *bpa;
1572 	int match;
1573 
1574 	match = 0;
1575 
1576 	/* If the buf isn't in core skip it */
1577 	if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1578 		return (0);
1579 
1580 	/* If the buf is busy we don't want to wait for it */
1581 	if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1582 		return (0);
1583 
1584 	/* Only cluster with valid clusterable delayed write buffers */
1585 	if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1586 	    (B_DELWRI | B_CLUSTEROK))
1587 		goto done;
1588 
1589 	if (bpa->b_bufsize != size)
1590 		goto done;
1591 
1592 	/*
1593 	 * Check to see if it is in the expected place on disk and that the
1594 	 * block has been mapped.
1595 	 */
1596 	if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1597 		match = 1;
1598 done:
1599 	BUF_UNLOCK(bpa);
1600 	return (match);
1601 }
1602 
1603 /*
1604  *	vfs_bio_awrite:
1605  *
1606  *	Implement clustered async writes for clearing out B_DELWRI buffers.
1607  *	This is much better then the old way of writing only one buffer at
1608  *	a time.  Note that we may not be presented with the buffers in the
1609  *	correct order, so we search for the cluster in both directions.
1610  */
1611 int
1612 vfs_bio_awrite(struct buf *bp)
1613 {
1614 	int i;
1615 	int j;
1616 	daddr_t lblkno = bp->b_lblkno;
1617 	struct vnode *vp = bp->b_vp;
1618 	int ncl;
1619 	int nwritten;
1620 	int size;
1621 	int maxcl;
1622 
1623 	/*
1624 	 * right now we support clustered writing only to regular files.  If
1625 	 * we find a clusterable block we could be in the middle of a cluster
1626 	 * rather then at the beginning.
1627 	 */
1628 	if ((vp->v_type == VREG) &&
1629 	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1630 	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1631 
1632 		size = vp->v_mount->mnt_stat.f_iosize;
1633 		maxcl = MAXPHYS / size;
1634 
1635 		VI_LOCK(vp);
1636 		for (i = 1; i < maxcl; i++)
1637 			if (vfs_bio_clcheck(vp, size, lblkno + i,
1638 			    bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1639 				break;
1640 
1641 		for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1642 			if (vfs_bio_clcheck(vp, size, lblkno - j,
1643 			    bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1644 				break;
1645 
1646 		VI_UNLOCK(vp);
1647 		--j;
1648 		ncl = i + j;
1649 		/*
1650 		 * this is a possible cluster write
1651 		 */
1652 		if (ncl != 1) {
1653 			BUF_UNLOCK(bp);
1654 			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1655 			return nwritten;
1656 		}
1657 	}
1658 	bremfree(bp);
1659 	bp->b_flags |= B_ASYNC;
1660 	/*
1661 	 * default (old) behavior, writing out only one block
1662 	 *
1663 	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1664 	 */
1665 	nwritten = bp->b_bufsize;
1666 	(void) bwrite(bp);
1667 
1668 	return nwritten;
1669 }
1670 
1671 /*
1672  *	getnewbuf:
1673  *
1674  *	Find and initialize a new buffer header, freeing up existing buffers
1675  *	in the bufqueues as necessary.  The new buffer is returned locked.
1676  *
1677  *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1678  *	buffer away, the caller must set B_INVAL prior to calling brelse().
1679  *
1680  *	We block if:
1681  *		We have insufficient buffer headers
1682  *		We have insufficient buffer space
1683  *		buffer_map is too fragmented ( space reservation fails )
1684  *		If we have to flush dirty buffers ( but we try to avoid this )
1685  *
1686  *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1687  *	Instead we ask the buf daemon to do it for us.  We attempt to
1688  *	avoid piecemeal wakeups of the pageout daemon.
1689  */
1690 
1691 static struct buf *
1692 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1693 {
1694 	struct buf *bp;
1695 	struct buf *nbp;
1696 	int defrag = 0;
1697 	int nqindex;
1698 	static int flushingbufs;
1699 
1700 	/*
1701 	 * We can't afford to block since we might be holding a vnode lock,
1702 	 * which may prevent system daemons from running.  We deal with
1703 	 * low-memory situations by proactively returning memory and running
1704 	 * async I/O rather then sync I/O.
1705 	 */
1706 
1707 	atomic_add_int(&getnewbufcalls, 1);
1708 	atomic_subtract_int(&getnewbufrestarts, 1);
1709 restart:
1710 	atomic_add_int(&getnewbufrestarts, 1);
1711 
1712 	/*
1713 	 * Setup for scan.  If we do not have enough free buffers,
1714 	 * we setup a degenerate case that immediately fails.  Note
1715 	 * that if we are specially marked process, we are allowed to
1716 	 * dip into our reserves.
1717 	 *
1718 	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1719 	 *
1720 	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1721 	 * However, there are a number of cases (defragging, reusing, ...)
1722 	 * where we cannot backup.
1723 	 */
1724 	mtx_lock(&bqlock);
1725 	nqindex = QUEUE_EMPTYKVA;
1726 	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1727 
1728 	if (nbp == NULL) {
1729 		/*
1730 		 * If no EMPTYKVA buffers and we are either
1731 		 * defragging or reusing, locate a CLEAN buffer
1732 		 * to free or reuse.  If bufspace useage is low
1733 		 * skip this step so we can allocate a new buffer.
1734 		 */
1735 		if (defrag || bufspace >= lobufspace) {
1736 			nqindex = QUEUE_CLEAN;
1737 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1738 		}
1739 
1740 		/*
1741 		 * If we could not find or were not allowed to reuse a
1742 		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1743 		 * buffer.  We can only use an EMPTY buffer if allocating
1744 		 * its KVA would not otherwise run us out of buffer space.
1745 		 */
1746 		if (nbp == NULL && defrag == 0 &&
1747 		    bufspace + maxsize < hibufspace) {
1748 			nqindex = QUEUE_EMPTY;
1749 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1750 		}
1751 	}
1752 
1753 	/*
1754 	 * Run scan, possibly freeing data and/or kva mappings on the fly
1755 	 * depending.
1756 	 */
1757 
1758 	while ((bp = nbp) != NULL) {
1759 		int qindex = nqindex;
1760 
1761 		/*
1762 		 * Calculate next bp ( we can only use it if we do not block
1763 		 * or do other fancy things ).
1764 		 */
1765 		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1766 			switch(qindex) {
1767 			case QUEUE_EMPTY:
1768 				nqindex = QUEUE_EMPTYKVA;
1769 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1770 					break;
1771 				/* FALLTHROUGH */
1772 			case QUEUE_EMPTYKVA:
1773 				nqindex = QUEUE_CLEAN;
1774 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1775 					break;
1776 				/* FALLTHROUGH */
1777 			case QUEUE_CLEAN:
1778 				/*
1779 				 * nbp is NULL.
1780 				 */
1781 				break;
1782 			}
1783 		}
1784 		/*
1785 		 * If we are defragging then we need a buffer with
1786 		 * b_kvasize != 0.  XXX this situation should no longer
1787 		 * occur, if defrag is non-zero the buffer's b_kvasize
1788 		 * should also be non-zero at this point.  XXX
1789 		 */
1790 		if (defrag && bp->b_kvasize == 0) {
1791 			printf("Warning: defrag empty buffer %p\n", bp);
1792 			continue;
1793 		}
1794 
1795 		/*
1796 		 * Start freeing the bp.  This is somewhat involved.  nbp
1797 		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1798 		 */
1799 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1800 			continue;
1801 		if (bp->b_vp) {
1802 			BO_LOCK(bp->b_bufobj);
1803 			if (bp->b_vflags & BV_BKGRDINPROG) {
1804 				BO_UNLOCK(bp->b_bufobj);
1805 				BUF_UNLOCK(bp);
1806 				continue;
1807 			}
1808 			BO_UNLOCK(bp->b_bufobj);
1809 		}
1810 		CTR6(KTR_BUF,
1811 		    "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
1812 		    "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
1813 		    bp->b_kvasize, bp->b_bufsize, qindex);
1814 
1815 		/*
1816 		 * Sanity Checks
1817 		 */
1818 		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1819 
1820 		/*
1821 		 * Note: we no longer distinguish between VMIO and non-VMIO
1822 		 * buffers.
1823 		 */
1824 
1825 		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1826 
1827 		bremfreel(bp);
1828 		mtx_unlock(&bqlock);
1829 
1830 		if (qindex == QUEUE_CLEAN) {
1831 			if (bp->b_flags & B_VMIO) {
1832 				bp->b_flags &= ~B_ASYNC;
1833 				vfs_vmio_release(bp);
1834 			}
1835 			if (bp->b_vp)
1836 				brelvp(bp);
1837 		}
1838 
1839 		/*
1840 		 * NOTE:  nbp is now entirely invalid.  We can only restart
1841 		 * the scan from this point on.
1842 		 *
1843 		 * Get the rest of the buffer freed up.  b_kva* is still
1844 		 * valid after this operation.
1845 		 */
1846 
1847 		if (bp->b_rcred != NOCRED) {
1848 			crfree(bp->b_rcred);
1849 			bp->b_rcred = NOCRED;
1850 		}
1851 		if (bp->b_wcred != NOCRED) {
1852 			crfree(bp->b_wcred);
1853 			bp->b_wcred = NOCRED;
1854 		}
1855 		if (LIST_FIRST(&bp->b_dep) != NULL)
1856 			buf_deallocate(bp);
1857 		if (bp->b_vflags & BV_BKGRDINPROG)
1858 			panic("losing buffer 3");
1859 		KASSERT(bp->b_vp == NULL,
1860 		    ("bp: %p still has vnode %p.  qindex: %d",
1861 		    bp, bp->b_vp, qindex));
1862 		KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1863 		   ("bp: %p still on a buffer list. xflags %X",
1864 		    bp, bp->b_xflags));
1865 
1866 		if (bp->b_bufsize)
1867 			allocbuf(bp, 0);
1868 
1869 		bp->b_flags = 0;
1870 		bp->b_ioflags = 0;
1871 		bp->b_xflags = 0;
1872 		bp->b_vflags = 0;
1873 		bp->b_vp = NULL;
1874 		bp->b_blkno = bp->b_lblkno = 0;
1875 		bp->b_offset = NOOFFSET;
1876 		bp->b_iodone = 0;
1877 		bp->b_error = 0;
1878 		bp->b_resid = 0;
1879 		bp->b_bcount = 0;
1880 		bp->b_npages = 0;
1881 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1882 		bp->b_bufobj = NULL;
1883 		bp->b_pin_count = 0;
1884 		bp->b_fsprivate1 = NULL;
1885 		bp->b_fsprivate2 = NULL;
1886 		bp->b_fsprivate3 = NULL;
1887 
1888 		LIST_INIT(&bp->b_dep);
1889 
1890 		/*
1891 		 * If we are defragging then free the buffer.
1892 		 */
1893 		if (defrag) {
1894 			bp->b_flags |= B_INVAL;
1895 			bfreekva(bp);
1896 			brelse(bp);
1897 			defrag = 0;
1898 			goto restart;
1899 		}
1900 
1901 		/*
1902 		 * Notify any waiters for the buffer lock about
1903 		 * identity change by freeing the buffer.
1904 		 */
1905 		if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp) > 0) {
1906 			bp->b_flags |= B_INVAL;
1907 			bfreekva(bp);
1908 			brelse(bp);
1909 			goto restart;
1910 		}
1911 
1912 		/*
1913 		 * If we are overcomitted then recover the buffer and its
1914 		 * KVM space.  This occurs in rare situations when multiple
1915 		 * processes are blocked in getnewbuf() or allocbuf().
1916 		 */
1917 		if (bufspace >= hibufspace)
1918 			flushingbufs = 1;
1919 		if (flushingbufs && bp->b_kvasize != 0) {
1920 			bp->b_flags |= B_INVAL;
1921 			bfreekva(bp);
1922 			brelse(bp);
1923 			goto restart;
1924 		}
1925 		if (bufspace < lobufspace)
1926 			flushingbufs = 0;
1927 		break;
1928 	}
1929 
1930 	/*
1931 	 * If we exhausted our list, sleep as appropriate.  We may have to
1932 	 * wakeup various daemons and write out some dirty buffers.
1933 	 *
1934 	 * Generally we are sleeping due to insufficient buffer space.
1935 	 */
1936 
1937 	if (bp == NULL) {
1938 		int flags;
1939 		char *waitmsg;
1940 
1941 		if (defrag) {
1942 			flags = VFS_BIO_NEED_BUFSPACE;
1943 			waitmsg = "nbufkv";
1944 		} else if (bufspace >= hibufspace) {
1945 			waitmsg = "nbufbs";
1946 			flags = VFS_BIO_NEED_BUFSPACE;
1947 		} else {
1948 			waitmsg = "newbuf";
1949 			flags = VFS_BIO_NEED_ANY;
1950 		}
1951 		mtx_lock(&nblock);
1952 		needsbuffer |= flags;
1953 		mtx_unlock(&nblock);
1954 		mtx_unlock(&bqlock);
1955 
1956 		bd_speedup();	/* heeeelp */
1957 
1958 		mtx_lock(&nblock);
1959 		while (needsbuffer & flags) {
1960 			if (msleep(&needsbuffer, &nblock,
1961 			    (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) {
1962 				mtx_unlock(&nblock);
1963 				return (NULL);
1964 			}
1965 		}
1966 		mtx_unlock(&nblock);
1967 	} else {
1968 		/*
1969 		 * We finally have a valid bp.  We aren't quite out of the
1970 		 * woods, we still have to reserve kva space.  In order
1971 		 * to keep fragmentation sane we only allocate kva in
1972 		 * BKVASIZE chunks.
1973 		 */
1974 		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1975 
1976 		if (maxsize != bp->b_kvasize) {
1977 			vm_offset_t addr = 0;
1978 
1979 			bfreekva(bp);
1980 
1981 			vm_map_lock(buffer_map);
1982 			if (vm_map_findspace(buffer_map,
1983 				vm_map_min(buffer_map), maxsize, &addr)) {
1984 				/*
1985 				 * Uh oh.  Buffer map is to fragmented.  We
1986 				 * must defragment the map.
1987 				 */
1988 				atomic_add_int(&bufdefragcnt, 1);
1989 				vm_map_unlock(buffer_map);
1990 				defrag = 1;
1991 				bp->b_flags |= B_INVAL;
1992 				brelse(bp);
1993 				goto restart;
1994 			}
1995 			if (addr) {
1996 				vm_map_insert(buffer_map, NULL, 0,
1997 					addr, addr + maxsize,
1998 					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1999 
2000 				bp->b_kvabase = (caddr_t) addr;
2001 				bp->b_kvasize = maxsize;
2002 				atomic_add_int(&bufspace, bp->b_kvasize);
2003 				atomic_add_int(&bufreusecnt, 1);
2004 			}
2005 			vm_map_unlock(buffer_map);
2006 		}
2007 		bp->b_saveaddr = bp->b_kvabase;
2008 		bp->b_data = bp->b_saveaddr;
2009 	}
2010 	return(bp);
2011 }
2012 
2013 /*
2014  *	buf_daemon:
2015  *
2016  *	buffer flushing daemon.  Buffers are normally flushed by the
2017  *	update daemon but if it cannot keep up this process starts to
2018  *	take the load in an attempt to prevent getnewbuf() from blocking.
2019  */
2020 
2021 static struct kproc_desc buf_kp = {
2022 	"bufdaemon",
2023 	buf_daemon,
2024 	&bufdaemonproc
2025 };
2026 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
2027 
2028 static void
2029 buf_daemon()
2030 {
2031 
2032 	/*
2033 	 * This process needs to be suspended prior to shutdown sync.
2034 	 */
2035 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2036 	    SHUTDOWN_PRI_LAST);
2037 
2038 	/*
2039 	 * This process is allowed to take the buffer cache to the limit
2040 	 */
2041 	curthread->td_pflags |= TDP_NORUNNINGBUF;
2042 	mtx_lock(&bdlock);
2043 	for (;;) {
2044 		bd_request = 0;
2045 		mtx_unlock(&bdlock);
2046 
2047 		kthread_suspend_check(bufdaemonproc);
2048 
2049 		/*
2050 		 * Do the flush.  Limit the amount of in-transit I/O we
2051 		 * allow to build up, otherwise we would completely saturate
2052 		 * the I/O system.  Wakeup any waiting processes before we
2053 		 * normally would so they can run in parallel with our drain.
2054 		 */
2055 		while (numdirtybuffers > lodirtybuffers) {
2056 			int flushed;
2057 
2058 			flushed = flushbufqueues(QUEUE_DIRTY, 0);
2059 			/* The list empty check here is slightly racy */
2060 			if (!TAILQ_EMPTY(&bufqueues[QUEUE_DIRTY_GIANT])) {
2061 				mtx_lock(&Giant);
2062 				flushed += flushbufqueues(QUEUE_DIRTY_GIANT, 0);
2063 				mtx_unlock(&Giant);
2064 			}
2065 			if (flushed == 0) {
2066 				/*
2067 				 * Could not find any buffers without rollback
2068 				 * dependencies, so just write the first one
2069 				 * in the hopes of eventually making progress.
2070 				 */
2071 				flushbufqueues(QUEUE_DIRTY, 1);
2072 				if (!TAILQ_EMPTY(
2073 				    &bufqueues[QUEUE_DIRTY_GIANT])) {
2074 					mtx_lock(&Giant);
2075 					flushbufqueues(QUEUE_DIRTY_GIANT, 1);
2076 					mtx_unlock(&Giant);
2077 				}
2078 				break;
2079 			}
2080 			uio_yield();
2081 		}
2082 
2083 		/*
2084 		 * Only clear bd_request if we have reached our low water
2085 		 * mark.  The buf_daemon normally waits 1 second and
2086 		 * then incrementally flushes any dirty buffers that have
2087 		 * built up, within reason.
2088 		 *
2089 		 * If we were unable to hit our low water mark and couldn't
2090 		 * find any flushable buffers, we sleep half a second.
2091 		 * Otherwise we loop immediately.
2092 		 */
2093 		mtx_lock(&bdlock);
2094 		if (numdirtybuffers <= lodirtybuffers) {
2095 			/*
2096 			 * We reached our low water mark, reset the
2097 			 * request and sleep until we are needed again.
2098 			 * The sleep is just so the suspend code works.
2099 			 */
2100 			bd_request = 0;
2101 			msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2102 		} else {
2103 			/*
2104 			 * We couldn't find any flushable dirty buffers but
2105 			 * still have too many dirty buffers, we
2106 			 * have to sleep and try again.  (rare)
2107 			 */
2108 			msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2109 		}
2110 	}
2111 }
2112 
2113 /*
2114  *	flushbufqueues:
2115  *
2116  *	Try to flush a buffer in the dirty queue.  We must be careful to
2117  *	free up B_INVAL buffers instead of write them, which NFS is
2118  *	particularly sensitive to.
2119  */
2120 static int flushwithdeps = 0;
2121 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2122     0, "Number of buffers flushed with dependecies that require rollbacks");
2123 
2124 static int
2125 flushbufqueues(int queue, int flushdeps)
2126 {
2127 	struct thread *td = curthread;
2128 	struct buf sentinel;
2129 	struct vnode *vp;
2130 	struct mount *mp;
2131 	struct buf *bp;
2132 	int hasdeps;
2133 	int flushed;
2134 	int target;
2135 
2136 	target = numdirtybuffers - lodirtybuffers;
2137 	if (flushdeps && target > 2)
2138 		target /= 2;
2139 	flushed = 0;
2140 	bp = NULL;
2141 	mtx_lock(&bqlock);
2142 	TAILQ_INSERT_TAIL(&bufqueues[queue], &sentinel, b_freelist);
2143 	while (flushed != target) {
2144 		bp = TAILQ_FIRST(&bufqueues[queue]);
2145 		if (bp == &sentinel)
2146 			break;
2147 		TAILQ_REMOVE(&bufqueues[queue], bp, b_freelist);
2148 		TAILQ_INSERT_TAIL(&bufqueues[queue], bp, b_freelist);
2149 
2150 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2151 			continue;
2152 		if (bp->b_pin_count > 0) {
2153 			BUF_UNLOCK(bp);
2154 			continue;
2155 		}
2156 		BO_LOCK(bp->b_bufobj);
2157 		if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2158 		    (bp->b_flags & B_DELWRI) == 0) {
2159 			BO_UNLOCK(bp->b_bufobj);
2160 			BUF_UNLOCK(bp);
2161 			continue;
2162 		}
2163 		BO_UNLOCK(bp->b_bufobj);
2164 		if (bp->b_flags & B_INVAL) {
2165 			bremfreel(bp);
2166 			mtx_unlock(&bqlock);
2167 			brelse(bp);
2168 			flushed++;
2169 			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2170 			mtx_lock(&bqlock);
2171 			continue;
2172 		}
2173 
2174 		if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) {
2175 			if (flushdeps == 0) {
2176 				BUF_UNLOCK(bp);
2177 				continue;
2178 			}
2179 			hasdeps = 1;
2180 		} else
2181 			hasdeps = 0;
2182 		/*
2183 		 * We must hold the lock on a vnode before writing
2184 		 * one of its buffers. Otherwise we may confuse, or
2185 		 * in the case of a snapshot vnode, deadlock the
2186 		 * system.
2187 		 *
2188 		 * The lock order here is the reverse of the normal
2189 		 * of vnode followed by buf lock.  This is ok because
2190 		 * the NOWAIT will prevent deadlock.
2191 		 */
2192 		vp = bp->b_vp;
2193 		if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2194 			BUF_UNLOCK(bp);
2195 			continue;
2196 		}
2197 		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) {
2198 			mtx_unlock(&bqlock);
2199 			CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2200 			    bp, bp->b_vp, bp->b_flags);
2201 			vfs_bio_awrite(bp);
2202 			vn_finished_write(mp);
2203 			VOP_UNLOCK(vp, 0, td);
2204 			flushwithdeps += hasdeps;
2205 			flushed++;
2206 			waitrunningbufspace();
2207 			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2208 			mtx_lock(&bqlock);
2209 			continue;
2210 		}
2211 		vn_finished_write(mp);
2212 		BUF_UNLOCK(bp);
2213 	}
2214 	TAILQ_REMOVE(&bufqueues[queue], &sentinel, b_freelist);
2215 	mtx_unlock(&bqlock);
2216 	return (flushed);
2217 }
2218 
2219 /*
2220  * Check to see if a block is currently memory resident.
2221  */
2222 struct buf *
2223 incore(struct bufobj *bo, daddr_t blkno)
2224 {
2225 	struct buf *bp;
2226 
2227 	BO_LOCK(bo);
2228 	bp = gbincore(bo, blkno);
2229 	BO_UNLOCK(bo);
2230 	return (bp);
2231 }
2232 
2233 /*
2234  * Returns true if no I/O is needed to access the
2235  * associated VM object.  This is like incore except
2236  * it also hunts around in the VM system for the data.
2237  */
2238 
2239 static int
2240 inmem(struct vnode * vp, daddr_t blkno)
2241 {
2242 	vm_object_t obj;
2243 	vm_offset_t toff, tinc, size;
2244 	vm_page_t m;
2245 	vm_ooffset_t off;
2246 
2247 	ASSERT_VOP_LOCKED(vp, "inmem");
2248 
2249 	if (incore(&vp->v_bufobj, blkno))
2250 		return 1;
2251 	if (vp->v_mount == NULL)
2252 		return 0;
2253 	obj = vp->v_object;
2254 	if (obj == NULL)
2255 		return (0);
2256 
2257 	size = PAGE_SIZE;
2258 	if (size > vp->v_mount->mnt_stat.f_iosize)
2259 		size = vp->v_mount->mnt_stat.f_iosize;
2260 	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2261 
2262 	VM_OBJECT_LOCK(obj);
2263 	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2264 		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2265 		if (!m)
2266 			goto notinmem;
2267 		tinc = size;
2268 		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2269 			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2270 		if (vm_page_is_valid(m,
2271 		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2272 			goto notinmem;
2273 	}
2274 	VM_OBJECT_UNLOCK(obj);
2275 	return 1;
2276 
2277 notinmem:
2278 	VM_OBJECT_UNLOCK(obj);
2279 	return (0);
2280 }
2281 
2282 /*
2283  *	vfs_setdirty:
2284  *
2285  *	Sets the dirty range for a buffer based on the status of the dirty
2286  *	bits in the pages comprising the buffer.
2287  *
2288  *	The range is limited to the size of the buffer.
2289  *
2290  *	This routine is primarily used by NFS, but is generalized for the
2291  *	B_VMIO case.
2292  */
2293 static void
2294 vfs_setdirty(struct buf *bp)
2295 {
2296 
2297 	/*
2298 	 * Degenerate case - empty buffer
2299 	 */
2300 
2301 	if (bp->b_bufsize == 0)
2302 		return;
2303 
2304 	/*
2305 	 * We qualify the scan for modified pages on whether the
2306 	 * object has been flushed yet.
2307 	 */
2308 
2309 	if ((bp->b_flags & B_VMIO) == 0)
2310 		return;
2311 
2312 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2313 	vfs_setdirty_locked_object(bp);
2314 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2315 }
2316 
2317 static void
2318 vfs_setdirty_locked_object(struct buf *bp)
2319 {
2320 	vm_object_t object;
2321 	int i;
2322 
2323 	object = bp->b_bufobj->bo_object;
2324 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2325 	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2326 		vm_offset_t boffset;
2327 		vm_offset_t eoffset;
2328 
2329 		vm_page_lock_queues();
2330 		/*
2331 		 * test the pages to see if they have been modified directly
2332 		 * by users through the VM system.
2333 		 */
2334 		for (i = 0; i < bp->b_npages; i++)
2335 			vm_page_test_dirty(bp->b_pages[i]);
2336 
2337 		/*
2338 		 * Calculate the encompassing dirty range, boffset and eoffset,
2339 		 * (eoffset - boffset) bytes.
2340 		 */
2341 
2342 		for (i = 0; i < bp->b_npages; i++) {
2343 			if (bp->b_pages[i]->dirty)
2344 				break;
2345 		}
2346 		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2347 
2348 		for (i = bp->b_npages - 1; i >= 0; --i) {
2349 			if (bp->b_pages[i]->dirty) {
2350 				break;
2351 			}
2352 		}
2353 		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2354 
2355 		vm_page_unlock_queues();
2356 		/*
2357 		 * Fit it to the buffer.
2358 		 */
2359 
2360 		if (eoffset > bp->b_bcount)
2361 			eoffset = bp->b_bcount;
2362 
2363 		/*
2364 		 * If we have a good dirty range, merge with the existing
2365 		 * dirty range.
2366 		 */
2367 
2368 		if (boffset < eoffset) {
2369 			if (bp->b_dirtyoff > boffset)
2370 				bp->b_dirtyoff = boffset;
2371 			if (bp->b_dirtyend < eoffset)
2372 				bp->b_dirtyend = eoffset;
2373 		}
2374 	}
2375 }
2376 
2377 /*
2378  *	getblk:
2379  *
2380  *	Get a block given a specified block and offset into a file/device.
2381  *	The buffers B_DONE bit will be cleared on return, making it almost
2382  * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2383  *	return.  The caller should clear B_INVAL prior to initiating a
2384  *	READ.
2385  *
2386  *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2387  *	an existing buffer.
2388  *
2389  *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2390  *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2391  *	and then cleared based on the backing VM.  If the previous buffer is
2392  *	non-0-sized but invalid, B_CACHE will be cleared.
2393  *
2394  *	If getblk() must create a new buffer, the new buffer is returned with
2395  *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2396  *	case it is returned with B_INVAL clear and B_CACHE set based on the
2397  *	backing VM.
2398  *
2399  *	getblk() also forces a bwrite() for any B_DELWRI buffer whos
2400  *	B_CACHE bit is clear.
2401  *
2402  *	What this means, basically, is that the caller should use B_CACHE to
2403  *	determine whether the buffer is fully valid or not and should clear
2404  *	B_INVAL prior to issuing a read.  If the caller intends to validate
2405  *	the buffer by loading its data area with something, the caller needs
2406  *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2407  *	the caller should set B_CACHE ( as an optimization ), else the caller
2408  *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2409  *	a write attempt or if it was a successfull read.  If the caller
2410  *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2411  *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2412  */
2413 struct buf *
2414 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo,
2415     int flags)
2416 {
2417 	struct buf *bp;
2418 	struct bufobj *bo;
2419 	int error;
2420 
2421 	CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
2422 	ASSERT_VOP_LOCKED(vp, "getblk");
2423 	if (size > MAXBSIZE)
2424 		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2425 
2426 	bo = &vp->v_bufobj;
2427 loop:
2428 	/*
2429 	 * Block if we are low on buffers.   Certain processes are allowed
2430 	 * to completely exhaust the buffer cache.
2431          *
2432          * If this check ever becomes a bottleneck it may be better to
2433          * move it into the else, when gbincore() fails.  At the moment
2434          * it isn't a problem.
2435 	 *
2436 	 * XXX remove if 0 sections (clean this up after its proven)
2437          */
2438 	if (numfreebuffers == 0) {
2439 		if (curthread == PCPU_GET(idlethread))
2440 			return NULL;
2441 		mtx_lock(&nblock);
2442 		needsbuffer |= VFS_BIO_NEED_ANY;
2443 		mtx_unlock(&nblock);
2444 	}
2445 
2446 	VI_LOCK(vp);
2447 	bp = gbincore(bo, blkno);
2448 	if (bp != NULL) {
2449 		int lockflags;
2450 		/*
2451 		 * Buffer is in-core.  If the buffer is not busy, it must
2452 		 * be on a queue.
2453 		 */
2454 		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2455 
2456 		if (flags & GB_LOCK_NOWAIT)
2457 			lockflags |= LK_NOWAIT;
2458 
2459 		error = BUF_TIMELOCK(bp, lockflags,
2460 		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2461 
2462 		/*
2463 		 * If we slept and got the lock we have to restart in case
2464 		 * the buffer changed identities.
2465 		 */
2466 		if (error == ENOLCK)
2467 			goto loop;
2468 		/* We timed out or were interrupted. */
2469 		else if (error)
2470 			return (NULL);
2471 
2472 		/*
2473 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2474 		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2475 		 * and for a VMIO buffer B_CACHE is adjusted according to the
2476 		 * backing VM cache.
2477 		 */
2478 		if (bp->b_flags & B_INVAL)
2479 			bp->b_flags &= ~B_CACHE;
2480 		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2481 			bp->b_flags |= B_CACHE;
2482 		bremfree(bp);
2483 
2484 		/*
2485 		 * check for size inconsistancies for non-VMIO case.
2486 		 */
2487 
2488 		if (bp->b_bcount != size) {
2489 			if ((bp->b_flags & B_VMIO) == 0 ||
2490 			    (size > bp->b_kvasize)) {
2491 				if (bp->b_flags & B_DELWRI) {
2492 					/*
2493 					 * If buffer is pinned and caller does
2494 					 * not want sleep  waiting for it to be
2495 					 * unpinned, bail out
2496 					 * */
2497 					if (bp->b_pin_count > 0) {
2498 						if (flags & GB_LOCK_NOWAIT) {
2499 							bqrelse(bp);
2500 							return (NULL);
2501 						} else {
2502 							bunpin_wait(bp);
2503 						}
2504 					}
2505 					bp->b_flags |= B_NOCACHE;
2506 					bwrite(bp);
2507 				} else {
2508 					if (LIST_FIRST(&bp->b_dep) == NULL) {
2509 						bp->b_flags |= B_RELBUF;
2510 						brelse(bp);
2511 					} else {
2512 						bp->b_flags |= B_NOCACHE;
2513 						bwrite(bp);
2514 					}
2515 				}
2516 				goto loop;
2517 			}
2518 		}
2519 
2520 		/*
2521 		 * If the size is inconsistant in the VMIO case, we can resize
2522 		 * the buffer.  This might lead to B_CACHE getting set or
2523 		 * cleared.  If the size has not changed, B_CACHE remains
2524 		 * unchanged from its previous state.
2525 		 */
2526 
2527 		if (bp->b_bcount != size)
2528 			allocbuf(bp, size);
2529 
2530 		KASSERT(bp->b_offset != NOOFFSET,
2531 		    ("getblk: no buffer offset"));
2532 
2533 		/*
2534 		 * A buffer with B_DELWRI set and B_CACHE clear must
2535 		 * be committed before we can return the buffer in
2536 		 * order to prevent the caller from issuing a read
2537 		 * ( due to B_CACHE not being set ) and overwriting
2538 		 * it.
2539 		 *
2540 		 * Most callers, including NFS and FFS, need this to
2541 		 * operate properly either because they assume they
2542 		 * can issue a read if B_CACHE is not set, or because
2543 		 * ( for example ) an uncached B_DELWRI might loop due
2544 		 * to softupdates re-dirtying the buffer.  In the latter
2545 		 * case, B_CACHE is set after the first write completes,
2546 		 * preventing further loops.
2547 		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2548 		 * above while extending the buffer, we cannot allow the
2549 		 * buffer to remain with B_CACHE set after the write
2550 		 * completes or it will represent a corrupt state.  To
2551 		 * deal with this we set B_NOCACHE to scrap the buffer
2552 		 * after the write.
2553 		 *
2554 		 * We might be able to do something fancy, like setting
2555 		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2556 		 * so the below call doesn't set B_CACHE, but that gets real
2557 		 * confusing.  This is much easier.
2558 		 */
2559 
2560 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2561 			bp->b_flags |= B_NOCACHE;
2562 			bwrite(bp);
2563 			goto loop;
2564 		}
2565 		bp->b_flags &= ~B_DONE;
2566 	} else {
2567 		int bsize, maxsize, vmio;
2568 		off_t offset;
2569 
2570 		/*
2571 		 * Buffer is not in-core, create new buffer.  The buffer
2572 		 * returned by getnewbuf() is locked.  Note that the returned
2573 		 * buffer is also considered valid (not marked B_INVAL).
2574 		 */
2575 		VI_UNLOCK(vp);
2576 		/*
2577 		 * If the user does not want us to create the buffer, bail out
2578 		 * here.
2579 		 */
2580 		if (flags & GB_NOCREAT)
2581 			return NULL;
2582 		bsize = bo->bo_bsize;
2583 		offset = blkno * bsize;
2584 		vmio = vp->v_object != NULL;
2585 		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2586 		maxsize = imax(maxsize, bsize);
2587 
2588 		bp = getnewbuf(slpflag, slptimeo, size, maxsize);
2589 		if (bp == NULL) {
2590 			if (slpflag || slptimeo)
2591 				return NULL;
2592 			goto loop;
2593 		}
2594 
2595 		/*
2596 		 * This code is used to make sure that a buffer is not
2597 		 * created while the getnewbuf routine is blocked.
2598 		 * This can be a problem whether the vnode is locked or not.
2599 		 * If the buffer is created out from under us, we have to
2600 		 * throw away the one we just created.
2601 		 *
2602 		 * Note: this must occur before we associate the buffer
2603 		 * with the vp especially considering limitations in
2604 		 * the splay tree implementation when dealing with duplicate
2605 		 * lblkno's.
2606 		 */
2607 		BO_LOCK(bo);
2608 		if (gbincore(bo, blkno)) {
2609 			BO_UNLOCK(bo);
2610 			bp->b_flags |= B_INVAL;
2611 			brelse(bp);
2612 			goto loop;
2613 		}
2614 
2615 		/*
2616 		 * Insert the buffer into the hash, so that it can
2617 		 * be found by incore.
2618 		 */
2619 		bp->b_blkno = bp->b_lblkno = blkno;
2620 		bp->b_offset = offset;
2621 		bgetvp(vp, bp);
2622 		BO_UNLOCK(bo);
2623 
2624 		/*
2625 		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2626 		 * buffer size starts out as 0, B_CACHE will be set by
2627 		 * allocbuf() for the VMIO case prior to it testing the
2628 		 * backing store for validity.
2629 		 */
2630 
2631 		if (vmio) {
2632 			bp->b_flags |= B_VMIO;
2633 #if defined(VFS_BIO_DEBUG)
2634 			if (vn_canvmio(vp) != TRUE)
2635 				printf("getblk: VMIO on vnode type %d\n",
2636 					vp->v_type);
2637 #endif
2638 			KASSERT(vp->v_object == bp->b_bufobj->bo_object,
2639 			    ("ARGH! different b_bufobj->bo_object %p %p %p\n",
2640 			    bp, vp->v_object, bp->b_bufobj->bo_object));
2641 		} else {
2642 			bp->b_flags &= ~B_VMIO;
2643 			KASSERT(bp->b_bufobj->bo_object == NULL,
2644 			    ("ARGH! has b_bufobj->bo_object %p %p\n",
2645 			    bp, bp->b_bufobj->bo_object));
2646 		}
2647 
2648 		allocbuf(bp, size);
2649 		bp->b_flags &= ~B_DONE;
2650 	}
2651 	CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
2652 	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2653 	KASSERT(bp->b_bufobj == bo,
2654 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2655 	return (bp);
2656 }
2657 
2658 /*
2659  * Get an empty, disassociated buffer of given size.  The buffer is initially
2660  * set to B_INVAL.
2661  */
2662 struct buf *
2663 geteblk(int size)
2664 {
2665 	struct buf *bp;
2666 	int maxsize;
2667 
2668 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2669 	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2670 		continue;
2671 	allocbuf(bp, size);
2672 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2673 	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2674 	return (bp);
2675 }
2676 
2677 
2678 /*
2679  * This code constitutes the buffer memory from either anonymous system
2680  * memory (in the case of non-VMIO operations) or from an associated
2681  * VM object (in the case of VMIO operations).  This code is able to
2682  * resize a buffer up or down.
2683  *
2684  * Note that this code is tricky, and has many complications to resolve
2685  * deadlock or inconsistant data situations.  Tread lightly!!!
2686  * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2687  * the caller.  Calling this code willy nilly can result in the loss of data.
2688  *
2689  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2690  * B_CACHE for the non-VMIO case.
2691  */
2692 
2693 int
2694 allocbuf(struct buf *bp, int size)
2695 {
2696 	int newbsize, mbsize;
2697 	int i;
2698 
2699 	if (BUF_REFCNT(bp) == 0)
2700 		panic("allocbuf: buffer not busy");
2701 
2702 	if (bp->b_kvasize < size)
2703 		panic("allocbuf: buffer too small");
2704 
2705 	if ((bp->b_flags & B_VMIO) == 0) {
2706 		caddr_t origbuf;
2707 		int origbufsize;
2708 		/*
2709 		 * Just get anonymous memory from the kernel.  Don't
2710 		 * mess with B_CACHE.
2711 		 */
2712 		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2713 		if (bp->b_flags & B_MALLOC)
2714 			newbsize = mbsize;
2715 		else
2716 			newbsize = round_page(size);
2717 
2718 		if (newbsize < bp->b_bufsize) {
2719 			/*
2720 			 * malloced buffers are not shrunk
2721 			 */
2722 			if (bp->b_flags & B_MALLOC) {
2723 				if (newbsize) {
2724 					bp->b_bcount = size;
2725 				} else {
2726 					free(bp->b_data, M_BIOBUF);
2727 					if (bp->b_bufsize) {
2728 						atomic_subtract_int(
2729 						    &bufmallocspace,
2730 						    bp->b_bufsize);
2731 						bufspacewakeup();
2732 						bp->b_bufsize = 0;
2733 					}
2734 					bp->b_saveaddr = bp->b_kvabase;
2735 					bp->b_data = bp->b_saveaddr;
2736 					bp->b_bcount = 0;
2737 					bp->b_flags &= ~B_MALLOC;
2738 				}
2739 				return 1;
2740 			}
2741 			vm_hold_free_pages(
2742 			    bp,
2743 			    (vm_offset_t) bp->b_data + newbsize,
2744 			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2745 		} else if (newbsize > bp->b_bufsize) {
2746 			/*
2747 			 * We only use malloced memory on the first allocation.
2748 			 * and revert to page-allocated memory when the buffer
2749 			 * grows.
2750 			 */
2751 			/*
2752 			 * There is a potential smp race here that could lead
2753 			 * to bufmallocspace slightly passing the max.  It
2754 			 * is probably extremely rare and not worth worrying
2755 			 * over.
2756 			 */
2757 			if ( (bufmallocspace < maxbufmallocspace) &&
2758 				(bp->b_bufsize == 0) &&
2759 				(mbsize <= PAGE_SIZE/2)) {
2760 
2761 				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2762 				bp->b_bufsize = mbsize;
2763 				bp->b_bcount = size;
2764 				bp->b_flags |= B_MALLOC;
2765 				atomic_add_int(&bufmallocspace, mbsize);
2766 				return 1;
2767 			}
2768 			origbuf = NULL;
2769 			origbufsize = 0;
2770 			/*
2771 			 * If the buffer is growing on its other-than-first allocation,
2772 			 * then we revert to the page-allocation scheme.
2773 			 */
2774 			if (bp->b_flags & B_MALLOC) {
2775 				origbuf = bp->b_data;
2776 				origbufsize = bp->b_bufsize;
2777 				bp->b_data = bp->b_kvabase;
2778 				if (bp->b_bufsize) {
2779 					atomic_subtract_int(&bufmallocspace,
2780 					    bp->b_bufsize);
2781 					bufspacewakeup();
2782 					bp->b_bufsize = 0;
2783 				}
2784 				bp->b_flags &= ~B_MALLOC;
2785 				newbsize = round_page(newbsize);
2786 			}
2787 			vm_hold_load_pages(
2788 			    bp,
2789 			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2790 			    (vm_offset_t) bp->b_data + newbsize);
2791 			if (origbuf) {
2792 				bcopy(origbuf, bp->b_data, origbufsize);
2793 				free(origbuf, M_BIOBUF);
2794 			}
2795 		}
2796 	} else {
2797 		int desiredpages;
2798 
2799 		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2800 		desiredpages = (size == 0) ? 0 :
2801 			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2802 
2803 		if (bp->b_flags & B_MALLOC)
2804 			panic("allocbuf: VMIO buffer can't be malloced");
2805 		/*
2806 		 * Set B_CACHE initially if buffer is 0 length or will become
2807 		 * 0-length.
2808 		 */
2809 		if (size == 0 || bp->b_bufsize == 0)
2810 			bp->b_flags |= B_CACHE;
2811 
2812 		if (newbsize < bp->b_bufsize) {
2813 			/*
2814 			 * DEV_BSIZE aligned new buffer size is less then the
2815 			 * DEV_BSIZE aligned existing buffer size.  Figure out
2816 			 * if we have to remove any pages.
2817 			 */
2818 			if (desiredpages < bp->b_npages) {
2819 				vm_page_t m;
2820 
2821 				VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
2822 				vm_page_lock_queues();
2823 				for (i = desiredpages; i < bp->b_npages; i++) {
2824 					/*
2825 					 * the page is not freed here -- it
2826 					 * is the responsibility of
2827 					 * vnode_pager_setsize
2828 					 */
2829 					m = bp->b_pages[i];
2830 					KASSERT(m != bogus_page,
2831 					    ("allocbuf: bogus page found"));
2832 					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2833 						vm_page_lock_queues();
2834 
2835 					bp->b_pages[i] = NULL;
2836 					vm_page_unwire(m, 0);
2837 				}
2838 				vm_page_unlock_queues();
2839 				VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
2840 				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2841 				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2842 				bp->b_npages = desiredpages;
2843 			}
2844 		} else if (size > bp->b_bcount) {
2845 			/*
2846 			 * We are growing the buffer, possibly in a
2847 			 * byte-granular fashion.
2848 			 */
2849 			struct vnode *vp;
2850 			vm_object_t obj;
2851 			vm_offset_t toff;
2852 			vm_offset_t tinc;
2853 
2854 			/*
2855 			 * Step 1, bring in the VM pages from the object,
2856 			 * allocating them if necessary.  We must clear
2857 			 * B_CACHE if these pages are not valid for the
2858 			 * range covered by the buffer.
2859 			 */
2860 
2861 			vp = bp->b_vp;
2862 			obj = bp->b_bufobj->bo_object;
2863 
2864 			VM_OBJECT_LOCK(obj);
2865 			while (bp->b_npages < desiredpages) {
2866 				vm_page_t m;
2867 				vm_pindex_t pi;
2868 
2869 				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2870 				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2871 					/*
2872 					 * note: must allocate system pages
2873 					 * since blocking here could intefere
2874 					 * with paging I/O, no matter which
2875 					 * process we are.
2876 					 */
2877 					m = vm_page_alloc(obj, pi,
2878 					    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2879 					    VM_ALLOC_WIRED);
2880 					if (m == NULL) {
2881 						atomic_add_int(&vm_pageout_deficit,
2882 						    desiredpages - bp->b_npages);
2883 						VM_OBJECT_UNLOCK(obj);
2884 						VM_WAIT;
2885 						VM_OBJECT_LOCK(obj);
2886 					} else {
2887 						bp->b_flags &= ~B_CACHE;
2888 						bp->b_pages[bp->b_npages] = m;
2889 						++bp->b_npages;
2890 					}
2891 					continue;
2892 				}
2893 
2894 				/*
2895 				 * We found a page.  If we have to sleep on it,
2896 				 * retry because it might have gotten freed out
2897 				 * from under us.
2898 				 *
2899 				 * We can only test VPO_BUSY here.  Blocking on
2900 				 * m->busy might lead to a deadlock:
2901 				 *
2902 				 *  vm_fault->getpages->cluster_read->allocbuf
2903 				 *
2904 				 */
2905 				vm_page_lock_queues();
2906 				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2907 					continue;
2908 
2909 				/*
2910 				 * We have a good page.  Should we wakeup the
2911 				 * page daemon?
2912 				 */
2913 				if ((curproc != pageproc) &&
2914 				    (VM_PAGE_INQUEUE1(m, PQ_CACHE)) &&
2915 				    ((cnt.v_free_count + cnt.v_cache_count) <
2916 			 		(cnt.v_free_min + cnt.v_cache_min))) {
2917 					pagedaemon_wakeup();
2918 				}
2919 				vm_page_wire(m);
2920 				vm_page_unlock_queues();
2921 				bp->b_pages[bp->b_npages] = m;
2922 				++bp->b_npages;
2923 			}
2924 
2925 			/*
2926 			 * Step 2.  We've loaded the pages into the buffer,
2927 			 * we have to figure out if we can still have B_CACHE
2928 			 * set.  Note that B_CACHE is set according to the
2929 			 * byte-granular range ( bcount and size ), new the
2930 			 * aligned range ( newbsize ).
2931 			 *
2932 			 * The VM test is against m->valid, which is DEV_BSIZE
2933 			 * aligned.  Needless to say, the validity of the data
2934 			 * needs to also be DEV_BSIZE aligned.  Note that this
2935 			 * fails with NFS if the server or some other client
2936 			 * extends the file's EOF.  If our buffer is resized,
2937 			 * B_CACHE may remain set! XXX
2938 			 */
2939 
2940 			toff = bp->b_bcount;
2941 			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2942 
2943 			while ((bp->b_flags & B_CACHE) && toff < size) {
2944 				vm_pindex_t pi;
2945 
2946 				if (tinc > (size - toff))
2947 					tinc = size - toff;
2948 
2949 				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2950 				    PAGE_SHIFT;
2951 
2952 				vfs_buf_test_cache(
2953 				    bp,
2954 				    bp->b_offset,
2955 				    toff,
2956 				    tinc,
2957 				    bp->b_pages[pi]
2958 				);
2959 				toff += tinc;
2960 				tinc = PAGE_SIZE;
2961 			}
2962 			VM_OBJECT_UNLOCK(obj);
2963 
2964 			/*
2965 			 * Step 3, fixup the KVM pmap.  Remember that
2966 			 * bp->b_data is relative to bp->b_offset, but
2967 			 * bp->b_offset may be offset into the first page.
2968 			 */
2969 
2970 			bp->b_data = (caddr_t)
2971 			    trunc_page((vm_offset_t)bp->b_data);
2972 			pmap_qenter(
2973 			    (vm_offset_t)bp->b_data,
2974 			    bp->b_pages,
2975 			    bp->b_npages
2976 			);
2977 
2978 			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2979 			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2980 		}
2981 	}
2982 	if (newbsize < bp->b_bufsize)
2983 		bufspacewakeup();
2984 	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2985 	bp->b_bcount = size;		/* requested buffer size	*/
2986 	return 1;
2987 }
2988 
2989 void
2990 biodone(struct bio *bp)
2991 {
2992 	void (*done)(struct bio *);
2993 
2994 	mtx_lock(&bdonelock);
2995 	bp->bio_flags |= BIO_DONE;
2996 	done = bp->bio_done;
2997 	if (done == NULL)
2998 		wakeup(bp);
2999 	mtx_unlock(&bdonelock);
3000 	if (done != NULL)
3001 		done(bp);
3002 }
3003 
3004 /*
3005  * Wait for a BIO to finish.
3006  *
3007  * XXX: resort to a timeout for now.  The optimal locking (if any) for this
3008  * case is not yet clear.
3009  */
3010 int
3011 biowait(struct bio *bp, const char *wchan)
3012 {
3013 
3014 	mtx_lock(&bdonelock);
3015 	while ((bp->bio_flags & BIO_DONE) == 0)
3016 		msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10);
3017 	mtx_unlock(&bdonelock);
3018 	if (bp->bio_error != 0)
3019 		return (bp->bio_error);
3020 	if (!(bp->bio_flags & BIO_ERROR))
3021 		return (0);
3022 	return (EIO);
3023 }
3024 
3025 void
3026 biofinish(struct bio *bp, struct devstat *stat, int error)
3027 {
3028 
3029 	if (error) {
3030 		bp->bio_error = error;
3031 		bp->bio_flags |= BIO_ERROR;
3032 	}
3033 	if (stat != NULL)
3034 		devstat_end_transaction_bio(stat, bp);
3035 	biodone(bp);
3036 }
3037 
3038 /*
3039  *	bufwait:
3040  *
3041  *	Wait for buffer I/O completion, returning error status.  The buffer
3042  *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3043  *	error and cleared.
3044  */
3045 int
3046 bufwait(struct buf *bp)
3047 {
3048 	if (bp->b_iocmd == BIO_READ)
3049 		bwait(bp, PRIBIO, "biord");
3050 	else
3051 		bwait(bp, PRIBIO, "biowr");
3052 	if (bp->b_flags & B_EINTR) {
3053 		bp->b_flags &= ~B_EINTR;
3054 		return (EINTR);
3055 	}
3056 	if (bp->b_ioflags & BIO_ERROR) {
3057 		return (bp->b_error ? bp->b_error : EIO);
3058 	} else {
3059 		return (0);
3060 	}
3061 }
3062 
3063  /*
3064   * Call back function from struct bio back up to struct buf.
3065   */
3066 static void
3067 bufdonebio(struct bio *bip)
3068 {
3069 	struct buf *bp;
3070 
3071 	bp = bip->bio_caller2;
3072 	bp->b_resid = bp->b_bcount - bip->bio_completed;
3073 	bp->b_resid = bip->bio_resid;	/* XXX: remove */
3074 	bp->b_ioflags = bip->bio_flags;
3075 	bp->b_error = bip->bio_error;
3076 	if (bp->b_error)
3077 		bp->b_ioflags |= BIO_ERROR;
3078 	bufdone(bp);
3079 	g_destroy_bio(bip);
3080 }
3081 
3082 void
3083 dev_strategy(struct cdev *dev, struct buf *bp)
3084 {
3085 	struct cdevsw *csw;
3086 	struct bio *bip;
3087 
3088 	if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1)))
3089 		panic("b_iocmd botch");
3090 	for (;;) {
3091 		bip = g_new_bio();
3092 		if (bip != NULL)
3093 			break;
3094 		/* Try again later */
3095 		tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3096 	}
3097 	bip->bio_cmd = bp->b_iocmd;
3098 	bip->bio_offset = bp->b_iooffset;
3099 	bip->bio_length = bp->b_bcount;
3100 	bip->bio_bcount = bp->b_bcount;	/* XXX: remove */
3101 	bip->bio_data = bp->b_data;
3102 	bip->bio_done = bufdonebio;
3103 	bip->bio_caller2 = bp;
3104 	bip->bio_dev = dev;
3105 	KASSERT(dev->si_refcount > 0,
3106 	    ("dev_strategy on un-referenced struct cdev *(%s)",
3107 	    devtoname(dev)));
3108 	csw = dev_refthread(dev);
3109 	if (csw == NULL) {
3110 		g_destroy_bio(bip);
3111 		bp->b_error = ENXIO;
3112 		bp->b_ioflags = BIO_ERROR;
3113 		bufdone(bp);
3114 		return;
3115 	}
3116 	(*csw->d_strategy)(bip);
3117 	dev_relthread(dev);
3118 }
3119 
3120 /*
3121  *	bufdone:
3122  *
3123  *	Finish I/O on a buffer, optionally calling a completion function.
3124  *	This is usually called from an interrupt so process blocking is
3125  *	not allowed.
3126  *
3127  *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3128  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3129  *	assuming B_INVAL is clear.
3130  *
3131  *	For the VMIO case, we set B_CACHE if the op was a read and no
3132  *	read error occured, or if the op was a write.  B_CACHE is never
3133  *	set if the buffer is invalid or otherwise uncacheable.
3134  *
3135  *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3136  *	initiator to leave B_INVAL set to brelse the buffer out of existance
3137  *	in the biodone routine.
3138  */
3139 void
3140 bufdone(struct buf *bp)
3141 {
3142 	struct bufobj *dropobj;
3143 	void    (*biodone)(struct buf *);
3144 
3145 	CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3146 	dropobj = NULL;
3147 
3148 	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3149 	    BUF_REFCNT(bp)));
3150 	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3151 
3152 	runningbufwakeup(bp);
3153 	if (bp->b_iocmd == BIO_WRITE)
3154 		dropobj = bp->b_bufobj;
3155 	/* call optional completion function if requested */
3156 	if (bp->b_iodone != NULL) {
3157 		biodone = bp->b_iodone;
3158 		bp->b_iodone = NULL;
3159 		(*biodone) (bp);
3160 		if (dropobj)
3161 			bufobj_wdrop(dropobj);
3162 		return;
3163 	}
3164 
3165 	bufdone_finish(bp);
3166 
3167 	if (dropobj)
3168 		bufobj_wdrop(dropobj);
3169 }
3170 
3171 void
3172 bufdone_finish(struct buf *bp)
3173 {
3174 	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp,
3175 	    BUF_REFCNT(bp)));
3176 
3177 	if (LIST_FIRST(&bp->b_dep) != NULL)
3178 		buf_complete(bp);
3179 
3180 	if (bp->b_flags & B_VMIO) {
3181 		int i;
3182 		vm_ooffset_t foff;
3183 		vm_page_t m;
3184 		vm_object_t obj;
3185 		int iosize;
3186 		struct vnode *vp = bp->b_vp;
3187 		boolean_t are_queues_locked;
3188 
3189 		obj = bp->b_bufobj->bo_object;
3190 
3191 #if defined(VFS_BIO_DEBUG)
3192 		mp_fixme("usecount and vflag accessed without locks.");
3193 		if (vp->v_usecount == 0) {
3194 			panic("biodone: zero vnode ref count");
3195 		}
3196 
3197 		KASSERT(vp->v_object != NULL,
3198 			("biodone: vnode %p has no vm_object", vp));
3199 #endif
3200 
3201 		foff = bp->b_offset;
3202 		KASSERT(bp->b_offset != NOOFFSET,
3203 		    ("biodone: no buffer offset"));
3204 
3205 		VM_OBJECT_LOCK(obj);
3206 #if defined(VFS_BIO_DEBUG)
3207 		if (obj->paging_in_progress < bp->b_npages) {
3208 			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3209 			    obj->paging_in_progress, bp->b_npages);
3210 		}
3211 #endif
3212 
3213 		/*
3214 		 * Set B_CACHE if the op was a normal read and no error
3215 		 * occured.  B_CACHE is set for writes in the b*write()
3216 		 * routines.
3217 		 */
3218 		iosize = bp->b_bcount - bp->b_resid;
3219 		if (bp->b_iocmd == BIO_READ &&
3220 		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3221 		    !(bp->b_ioflags & BIO_ERROR)) {
3222 			bp->b_flags |= B_CACHE;
3223 		}
3224 		if (bp->b_iocmd == BIO_READ) {
3225 			vm_page_lock_queues();
3226 			are_queues_locked = TRUE;
3227 		} else
3228 			are_queues_locked = FALSE;
3229 		for (i = 0; i < bp->b_npages; i++) {
3230 			int bogusflag = 0;
3231 			int resid;
3232 
3233 			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3234 			if (resid > iosize)
3235 				resid = iosize;
3236 
3237 			/*
3238 			 * cleanup bogus pages, restoring the originals
3239 			 */
3240 			m = bp->b_pages[i];
3241 			if (m == bogus_page) {
3242 				bogusflag = 1;
3243 				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3244 				if (m == NULL)
3245 					panic("biodone: page disappeared!");
3246 				bp->b_pages[i] = m;
3247 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3248 				    bp->b_pages, bp->b_npages);
3249 			}
3250 #if defined(VFS_BIO_DEBUG)
3251 			if (OFF_TO_IDX(foff) != m->pindex) {
3252 				printf(
3253 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3254 				    (intmax_t)foff, (uintmax_t)m->pindex);
3255 			}
3256 #endif
3257 
3258 			/*
3259 			 * In the write case, the valid and clean bits are
3260 			 * already changed correctly ( see bdwrite() ), so we
3261 			 * only need to do this here in the read case.
3262 			 */
3263 			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3264 				vfs_page_set_valid(bp, foff, i, m);
3265 			}
3266 
3267 			/*
3268 			 * when debugging new filesystems or buffer I/O methods, this
3269 			 * is the most common error that pops up.  if you see this, you
3270 			 * have not set the page busy flag correctly!!!
3271 			 */
3272 			if (m->busy == 0) {
3273 				printf("biodone: page busy < 0, "
3274 				    "pindex: %d, foff: 0x(%x,%x), "
3275 				    "resid: %d, index: %d\n",
3276 				    (int) m->pindex, (int)(foff >> 32),
3277 						(int) foff & 0xffffffff, resid, i);
3278 				if (!vn_isdisk(vp, NULL))
3279 					printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n",
3280 					    (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize,
3281 					    (intmax_t) bp->b_lblkno,
3282 					    bp->b_flags, bp->b_npages);
3283 				else
3284 					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3285 					    (intmax_t) bp->b_lblkno,
3286 					    bp->b_flags, bp->b_npages);
3287 				printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n",
3288 				    (u_long)m->valid, (u_long)m->dirty,
3289 				    m->wire_count);
3290 				panic("biodone: page busy < 0\n");
3291 			}
3292 			vm_page_io_finish(m);
3293 			vm_object_pip_subtract(obj, 1);
3294 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3295 			iosize -= resid;
3296 		}
3297 		if (are_queues_locked)
3298 			vm_page_unlock_queues();
3299 		vm_object_pip_wakeupn(obj, 0);
3300 		VM_OBJECT_UNLOCK(obj);
3301 	}
3302 
3303 	/*
3304 	 * For asynchronous completions, release the buffer now. The brelse
3305 	 * will do a wakeup there if necessary - so no need to do a wakeup
3306 	 * here in the async case. The sync case always needs to do a wakeup.
3307 	 */
3308 
3309 	if (bp->b_flags & B_ASYNC) {
3310 		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3311 			brelse(bp);
3312 		else
3313 			bqrelse(bp);
3314 	} else
3315 		bdone(bp);
3316 }
3317 
3318 /*
3319  * This routine is called in lieu of iodone in the case of
3320  * incomplete I/O.  This keeps the busy status for pages
3321  * consistant.
3322  */
3323 void
3324 vfs_unbusy_pages(struct buf *bp)
3325 {
3326 	int i;
3327 	vm_object_t obj;
3328 	vm_page_t m;
3329 
3330 	runningbufwakeup(bp);
3331 	if (!(bp->b_flags & B_VMIO))
3332 		return;
3333 
3334 	obj = bp->b_bufobj->bo_object;
3335 	VM_OBJECT_LOCK(obj);
3336 	for (i = 0; i < bp->b_npages; i++) {
3337 		m = bp->b_pages[i];
3338 		if (m == bogus_page) {
3339 			m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3340 			if (!m)
3341 				panic("vfs_unbusy_pages: page missing\n");
3342 			bp->b_pages[i] = m;
3343 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3344 			    bp->b_pages, bp->b_npages);
3345 		}
3346 		vm_object_pip_subtract(obj, 1);
3347 		vm_page_io_finish(m);
3348 	}
3349 	vm_object_pip_wakeupn(obj, 0);
3350 	VM_OBJECT_UNLOCK(obj);
3351 }
3352 
3353 /*
3354  * vfs_page_set_valid:
3355  *
3356  *	Set the valid bits in a page based on the supplied offset.   The
3357  *	range is restricted to the buffer's size.
3358  *
3359  *	This routine is typically called after a read completes.
3360  */
3361 static void
3362 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3363 {
3364 	vm_ooffset_t soff, eoff;
3365 
3366 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3367 	/*
3368 	 * Start and end offsets in buffer.  eoff - soff may not cross a
3369 	 * page boundry or cross the end of the buffer.  The end of the
3370 	 * buffer, in this case, is our file EOF, not the allocation size
3371 	 * of the buffer.
3372 	 */
3373 	soff = off;
3374 	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3375 	if (eoff > bp->b_offset + bp->b_bcount)
3376 		eoff = bp->b_offset + bp->b_bcount;
3377 
3378 	/*
3379 	 * Set valid range.  This is typically the entire buffer and thus the
3380 	 * entire page.
3381 	 */
3382 	if (eoff > soff) {
3383 		vm_page_set_validclean(
3384 		    m,
3385 		   (vm_offset_t) (soff & PAGE_MASK),
3386 		   (vm_offset_t) (eoff - soff)
3387 		);
3388 	}
3389 }
3390 
3391 /*
3392  * This routine is called before a device strategy routine.
3393  * It is used to tell the VM system that paging I/O is in
3394  * progress, and treat the pages associated with the buffer
3395  * almost as being VPO_BUSY.  Also the object paging_in_progress
3396  * flag is handled to make sure that the object doesn't become
3397  * inconsistant.
3398  *
3399  * Since I/O has not been initiated yet, certain buffer flags
3400  * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3401  * and should be ignored.
3402  */
3403 void
3404 vfs_busy_pages(struct buf *bp, int clear_modify)
3405 {
3406 	int i, bogus;
3407 	vm_object_t obj;
3408 	vm_ooffset_t foff;
3409 	vm_page_t m;
3410 
3411 	if (!(bp->b_flags & B_VMIO))
3412 		return;
3413 
3414 	obj = bp->b_bufobj->bo_object;
3415 	foff = bp->b_offset;
3416 	KASSERT(bp->b_offset != NOOFFSET,
3417 	    ("vfs_busy_pages: no buffer offset"));
3418 	VM_OBJECT_LOCK(obj);
3419 	if (bp->b_bufsize != 0)
3420 		vfs_setdirty_locked_object(bp);
3421 retry:
3422 	for (i = 0; i < bp->b_npages; i++) {
3423 		m = bp->b_pages[i];
3424 
3425 		if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3426 			goto retry;
3427 	}
3428 	bogus = 0;
3429 	vm_page_lock_queues();
3430 	for (i = 0; i < bp->b_npages; i++) {
3431 		m = bp->b_pages[i];
3432 
3433 		if ((bp->b_flags & B_CLUSTER) == 0) {
3434 			vm_object_pip_add(obj, 1);
3435 			vm_page_io_start(m);
3436 		}
3437 		/*
3438 		 * When readying a buffer for a read ( i.e
3439 		 * clear_modify == 0 ), it is important to do
3440 		 * bogus_page replacement for valid pages in
3441 		 * partially instantiated buffers.  Partially
3442 		 * instantiated buffers can, in turn, occur when
3443 		 * reconstituting a buffer from its VM backing store
3444 		 * base.  We only have to do this if B_CACHE is
3445 		 * clear ( which causes the I/O to occur in the
3446 		 * first place ).  The replacement prevents the read
3447 		 * I/O from overwriting potentially dirty VM-backed
3448 		 * pages.  XXX bogus page replacement is, uh, bogus.
3449 		 * It may not work properly with small-block devices.
3450 		 * We need to find a better way.
3451 		 */
3452 		pmap_remove_all(m);
3453 		if (clear_modify)
3454 			vfs_page_set_valid(bp, foff, i, m);
3455 		else if (m->valid == VM_PAGE_BITS_ALL &&
3456 		    (bp->b_flags & B_CACHE) == 0) {
3457 			bp->b_pages[i] = bogus_page;
3458 			bogus++;
3459 		}
3460 		foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3461 	}
3462 	vm_page_unlock_queues();
3463 	VM_OBJECT_UNLOCK(obj);
3464 	if (bogus)
3465 		pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3466 		    bp->b_pages, bp->b_npages);
3467 }
3468 
3469 /*
3470  * Tell the VM system that the pages associated with this buffer
3471  * are clean.  This is used for delayed writes where the data is
3472  * going to go to disk eventually without additional VM intevention.
3473  *
3474  * Note that while we only really need to clean through to b_bcount, we
3475  * just go ahead and clean through to b_bufsize.
3476  */
3477 static void
3478 vfs_clean_pages(struct buf *bp)
3479 {
3480 	int i;
3481 	vm_ooffset_t foff, noff, eoff;
3482 	vm_page_t m;
3483 
3484 	if (!(bp->b_flags & B_VMIO))
3485 		return;
3486 
3487 	foff = bp->b_offset;
3488 	KASSERT(bp->b_offset != NOOFFSET,
3489 	    ("vfs_clean_pages: no buffer offset"));
3490 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3491 	vm_page_lock_queues();
3492 	for (i = 0; i < bp->b_npages; i++) {
3493 		m = bp->b_pages[i];
3494 		noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3495 		eoff = noff;
3496 
3497 		if (eoff > bp->b_offset + bp->b_bufsize)
3498 			eoff = bp->b_offset + bp->b_bufsize;
3499 		vfs_page_set_valid(bp, foff, i, m);
3500 		/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3501 		foff = noff;
3502 	}
3503 	vm_page_unlock_queues();
3504 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3505 }
3506 
3507 /*
3508  *	vfs_bio_set_validclean:
3509  *
3510  *	Set the range within the buffer to valid and clean.  The range is
3511  *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3512  *	itself may be offset from the beginning of the first page.
3513  *
3514  */
3515 
3516 void
3517 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3518 {
3519 	int i, n;
3520 	vm_page_t m;
3521 
3522 	if (!(bp->b_flags & B_VMIO))
3523 		return;
3524 	/*
3525 	 * Fixup base to be relative to beginning of first page.
3526 	 * Set initial n to be the maximum number of bytes in the
3527 	 * first page that can be validated.
3528 	 */
3529 
3530 	base += (bp->b_offset & PAGE_MASK);
3531 	n = PAGE_SIZE - (base & PAGE_MASK);
3532 
3533 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3534 	vm_page_lock_queues();
3535 	for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3536 		m = bp->b_pages[i];
3537 		if (n > size)
3538 			n = size;
3539 		vm_page_set_validclean(m, base & PAGE_MASK, n);
3540 		base += n;
3541 		size -= n;
3542 		n = PAGE_SIZE;
3543 	}
3544 	vm_page_unlock_queues();
3545 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3546 }
3547 
3548 /*
3549  *	vfs_bio_clrbuf:
3550  *
3551  *	clear a buffer.  This routine essentially fakes an I/O, so we need
3552  *	to clear BIO_ERROR and B_INVAL.
3553  *
3554  *	Note that while we only theoretically need to clear through b_bcount,
3555  *	we go ahead and clear through b_bufsize.
3556  */
3557 
3558 void
3559 vfs_bio_clrbuf(struct buf *bp)
3560 {
3561 	int i, j, mask = 0;
3562 	caddr_t sa, ea;
3563 
3564 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
3565 		clrbuf(bp);
3566 		return;
3567 	}
3568 
3569 	bp->b_flags &= ~B_INVAL;
3570 	bp->b_ioflags &= ~BIO_ERROR;
3571 	VM_OBJECT_LOCK(bp->b_bufobj->bo_object);
3572 	if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3573 	    (bp->b_offset & PAGE_MASK) == 0) {
3574 		if (bp->b_pages[0] == bogus_page)
3575 			goto unlock;
3576 		mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3577 		VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED);
3578 		if ((bp->b_pages[0]->valid & mask) == mask)
3579 			goto unlock;
3580 		if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3581 		    ((bp->b_pages[0]->valid & mask) == 0)) {
3582 			bzero(bp->b_data, bp->b_bufsize);
3583 			bp->b_pages[0]->valid |= mask;
3584 			goto unlock;
3585 		}
3586 	}
3587 	ea = sa = bp->b_data;
3588 	for(i = 0; i < bp->b_npages; i++, sa = ea) {
3589 		ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3590 		ea = (caddr_t)(vm_offset_t)ulmin(
3591 		    (u_long)(vm_offset_t)ea,
3592 		    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3593 		if (bp->b_pages[i] == bogus_page)
3594 			continue;
3595 		j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3596 		mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3597 		VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED);
3598 		if ((bp->b_pages[i]->valid & mask) == mask)
3599 			continue;
3600 		if ((bp->b_pages[i]->valid & mask) == 0) {
3601 			if ((bp->b_pages[i]->flags & PG_ZERO) == 0)
3602 				bzero(sa, ea - sa);
3603 		} else {
3604 			for (; sa < ea; sa += DEV_BSIZE, j++) {
3605 				if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3606 				    (bp->b_pages[i]->valid & (1 << j)) == 0)
3607 					bzero(sa, DEV_BSIZE);
3608 			}
3609 		}
3610 		bp->b_pages[i]->valid |= mask;
3611 	}
3612 unlock:
3613 	VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object);
3614 	bp->b_resid = 0;
3615 }
3616 
3617 /*
3618  * vm_hold_load_pages and vm_hold_free_pages get pages into
3619  * a buffers address space.  The pages are anonymous and are
3620  * not associated with a file object.
3621  */
3622 static void
3623 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3624 {
3625 	vm_offset_t pg;
3626 	vm_page_t p;
3627 	int index;
3628 
3629 	to = round_page(to);
3630 	from = round_page(from);
3631 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3632 
3633 	VM_OBJECT_LOCK(kernel_object);
3634 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3635 tryagain:
3636 		/*
3637 		 * note: must allocate system pages since blocking here
3638 		 * could intefere with paging I/O, no matter which
3639 		 * process we are.
3640 		 */
3641 		p = vm_page_alloc(kernel_object,
3642 			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3643 		    VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3644 		if (!p) {
3645 			atomic_add_int(&vm_pageout_deficit,
3646 			    (to - pg) >> PAGE_SHIFT);
3647 			VM_OBJECT_UNLOCK(kernel_object);
3648 			VM_WAIT;
3649 			VM_OBJECT_LOCK(kernel_object);
3650 			goto tryagain;
3651 		}
3652 		p->valid = VM_PAGE_BITS_ALL;
3653 		pmap_qenter(pg, &p, 1);
3654 		bp->b_pages[index] = p;
3655 	}
3656 	VM_OBJECT_UNLOCK(kernel_object);
3657 	bp->b_npages = index;
3658 }
3659 
3660 /* Return pages associated with this buf to the vm system */
3661 static void
3662 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3663 {
3664 	vm_offset_t pg;
3665 	vm_page_t p;
3666 	int index, newnpages;
3667 
3668 	from = round_page(from);
3669 	to = round_page(to);
3670 	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3671 
3672 	VM_OBJECT_LOCK(kernel_object);
3673 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3674 		p = bp->b_pages[index];
3675 		if (p && (index < bp->b_npages)) {
3676 			if (p->busy) {
3677 				printf(
3678 			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3679 				    (intmax_t)bp->b_blkno,
3680 				    (intmax_t)bp->b_lblkno);
3681 			}
3682 			bp->b_pages[index] = NULL;
3683 			pmap_qremove(pg, 1);
3684 			vm_page_lock_queues();
3685 			vm_page_unwire(p, 0);
3686 			vm_page_free(p);
3687 			vm_page_unlock_queues();
3688 		}
3689 	}
3690 	VM_OBJECT_UNLOCK(kernel_object);
3691 	bp->b_npages = newnpages;
3692 }
3693 
3694 /*
3695  * Map an IO request into kernel virtual address space.
3696  *
3697  * All requests are (re)mapped into kernel VA space.
3698  * Notice that we use b_bufsize for the size of the buffer
3699  * to be mapped.  b_bcount might be modified by the driver.
3700  *
3701  * Note that even if the caller determines that the address space should
3702  * be valid, a race or a smaller-file mapped into a larger space may
3703  * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3704  * check the return value.
3705  */
3706 int
3707 vmapbuf(struct buf *bp)
3708 {
3709 	caddr_t addr, kva;
3710 	vm_prot_t prot;
3711 	int pidx, i;
3712 	struct vm_page *m;
3713 	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3714 
3715 	if (bp->b_bufsize < 0)
3716 		return (-1);
3717 	prot = VM_PROT_READ;
3718 	if (bp->b_iocmd == BIO_READ)
3719 		prot |= VM_PROT_WRITE;	/* Less backwards than it looks */
3720 	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3721 	     addr < bp->b_data + bp->b_bufsize;
3722 	     addr += PAGE_SIZE, pidx++) {
3723 		/*
3724 		 * Do the vm_fault if needed; do the copy-on-write thing
3725 		 * when reading stuff off device into memory.
3726 		 *
3727 		 * NOTE! Must use pmap_extract() because addr may be in
3728 		 * the userland address space, and kextract is only guarenteed
3729 		 * to work for the kernland address space (see: sparc64 port).
3730 		 */
3731 retry:
3732 		if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data,
3733 		    prot) < 0) {
3734 			vm_page_lock_queues();
3735 			for (i = 0; i < pidx; ++i) {
3736 				vm_page_unhold(bp->b_pages[i]);
3737 				bp->b_pages[i] = NULL;
3738 			}
3739 			vm_page_unlock_queues();
3740 			return(-1);
3741 		}
3742 		m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot);
3743 		if (m == NULL)
3744 			goto retry;
3745 		bp->b_pages[pidx] = m;
3746 	}
3747 	if (pidx > btoc(MAXPHYS))
3748 		panic("vmapbuf: mapped more than MAXPHYS");
3749 	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3750 
3751 	kva = bp->b_saveaddr;
3752 	bp->b_npages = pidx;
3753 	bp->b_saveaddr = bp->b_data;
3754 	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3755 	return(0);
3756 }
3757 
3758 /*
3759  * Free the io map PTEs associated with this IO operation.
3760  * We also invalidate the TLB entries and restore the original b_addr.
3761  */
3762 void
3763 vunmapbuf(struct buf *bp)
3764 {
3765 	int pidx;
3766 	int npages;
3767 
3768 	npages = bp->b_npages;
3769 	pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3770 	vm_page_lock_queues();
3771 	for (pidx = 0; pidx < npages; pidx++)
3772 		vm_page_unhold(bp->b_pages[pidx]);
3773 	vm_page_unlock_queues();
3774 
3775 	bp->b_data = bp->b_saveaddr;
3776 }
3777 
3778 void
3779 bdone(struct buf *bp)
3780 {
3781 
3782 	mtx_lock(&bdonelock);
3783 	bp->b_flags |= B_DONE;
3784 	wakeup(bp);
3785 	mtx_unlock(&bdonelock);
3786 }
3787 
3788 void
3789 bwait(struct buf *bp, u_char pri, const char *wchan)
3790 {
3791 
3792 	mtx_lock(&bdonelock);
3793 	while ((bp->b_flags & B_DONE) == 0)
3794 		msleep(bp, &bdonelock, pri, wchan, 0);
3795 	mtx_unlock(&bdonelock);
3796 }
3797 
3798 int
3799 bufsync(struct bufobj *bo, int waitfor, struct thread *td)
3800 {
3801 
3802 	return (VOP_FSYNC(bo->__bo_vnode, waitfor, td));
3803 }
3804 
3805 void
3806 bufstrategy(struct bufobj *bo, struct buf *bp)
3807 {
3808 	int i = 0;
3809 	struct vnode *vp;
3810 
3811 	vp = bp->b_vp;
3812 	KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
3813 	KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
3814 	    ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
3815 	i = VOP_STRATEGY(vp, bp);
3816 	KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
3817 }
3818 
3819 void
3820 bufobj_wrefl(struct bufobj *bo)
3821 {
3822 
3823 	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3824 	ASSERT_BO_LOCKED(bo);
3825 	bo->bo_numoutput++;
3826 }
3827 
3828 void
3829 bufobj_wref(struct bufobj *bo)
3830 {
3831 
3832 	KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
3833 	BO_LOCK(bo);
3834 	bo->bo_numoutput++;
3835 	BO_UNLOCK(bo);
3836 }
3837 
3838 void
3839 bufobj_wdrop(struct bufobj *bo)
3840 {
3841 
3842 	KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
3843 	BO_LOCK(bo);
3844 	KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
3845 	if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
3846 		bo->bo_flag &= ~BO_WWAIT;
3847 		wakeup(&bo->bo_numoutput);
3848 	}
3849 	BO_UNLOCK(bo);
3850 }
3851 
3852 int
3853 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
3854 {
3855 	int error;
3856 
3857 	KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
3858 	ASSERT_BO_LOCKED(bo);
3859 	error = 0;
3860 	while (bo->bo_numoutput) {
3861 		bo->bo_flag |= BO_WWAIT;
3862 		error = msleep(&bo->bo_numoutput, BO_MTX(bo),
3863 		    slpflag | (PRIBIO + 1), "bo_wwait", timeo);
3864 		if (error)
3865 			break;
3866 	}
3867 	return (error);
3868 }
3869 
3870 void
3871 bpin(struct buf *bp)
3872 {
3873 	mtx_lock(&bpinlock);
3874 	bp->b_pin_count++;
3875 	mtx_unlock(&bpinlock);
3876 }
3877 
3878 void
3879 bunpin(struct buf *bp)
3880 {
3881 	mtx_lock(&bpinlock);
3882 	if (--bp->b_pin_count == 0)
3883 		wakeup(bp);
3884 	mtx_unlock(&bpinlock);
3885 }
3886 
3887 void
3888 bunpin_wait(struct buf *bp)
3889 {
3890 	mtx_lock(&bpinlock);
3891 	while (bp->b_pin_count > 0)
3892 		msleep(bp, &bpinlock, PRIBIO, "bwunpin", 0);
3893 	mtx_unlock(&bpinlock);
3894 }
3895 
3896 #include "opt_ddb.h"
3897 #ifdef DDB
3898 #include <ddb/ddb.h>
3899 
3900 /* DDB command to show buffer data */
3901 DB_SHOW_COMMAND(buffer, db_show_buffer)
3902 {
3903 	/* get args */
3904 	struct buf *bp = (struct buf *)addr;
3905 
3906 	if (!have_addr) {
3907 		db_printf("usage: show buffer <addr>\n");
3908 		return;
3909 	}
3910 
3911 	db_printf("buf at %p\n", bp);
3912 	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3913 	db_printf(
3914 	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3915 	    "b_bufobj = (%p), b_data = %p, b_blkno = %jd\n",
3916 	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3917 	    bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno);
3918 	if (bp->b_npages) {
3919 		int i;
3920 		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3921 		for (i = 0; i < bp->b_npages; i++) {
3922 			vm_page_t m;
3923 			m = bp->b_pages[i];
3924 			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3925 			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3926 			if ((i + 1) < bp->b_npages)
3927 				db_printf(",");
3928 		}
3929 		db_printf("\n");
3930 	}
3931 	lockmgr_printinfo(&bp->b_lock);
3932 }
3933 
3934 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
3935 {
3936 	struct buf *bp;
3937 	int i;
3938 
3939 	for (i = 0; i < nbuf; i++) {
3940 		bp = &buf[i];
3941 		if (lockcount(&bp->b_lock)) {
3942 			db_show_buffer((uintptr_t)bp, 1, 0, NULL);
3943 			db_printf("\n");
3944 		}
3945 	}
3946 }
3947 #endif /* DDB */
3948