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