xref: /freebsd/sys/kern/vfs_bio.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
1 /*
2  * Copyright (c) 1994,1997 John S. Dyson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. Absolutely no warranty of function or purpose is made by the author
12  *		John S. Dyson.
13  *
14  * $FreeBSD$
15  */
16 
17 /*
18  * this file contains a new buffer I/O scheme implementing a coherent
19  * VM object and buffer cache scheme.  Pains have been taken to make
20  * sure that the performance degradation associated with schemes such
21  * as this is not realized.
22  *
23  * Author:  John S. Dyson
24  * Significant help during the development and debugging phases
25  * had been provided by David Greenman, also of the FreeBSD core team.
26  *
27  * see man buf(9) for more info.
28  */
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/bio.h>
33 #include <sys/buf.h>
34 #include <sys/eventhandler.h>
35 #include <sys/lock.h>
36 #include <sys/malloc.h>
37 #include <sys/mount.h>
38 #include <sys/mutex.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/ktr.h>
42 #include <sys/proc.h>
43 #include <sys/reboot.h>
44 #include <sys/resourcevar.h>
45 #include <sys/sysctl.h>
46 #include <sys/vmmeter.h>
47 #include <sys/vnode.h>
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
56 
57 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
58 
59 struct	bio_ops bioops;		/* I/O operation notification */
60 
61 struct	buf_ops buf_ops_bio = {
62 	"buf_ops_bio",
63 	bwrite
64 };
65 
66 struct buf *buf;		/* buffer header pool */
67 struct swqueue bswlist;
68 struct mtx buftimelock;		/* Interlock on setting prio and timo */
69 
70 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
71 		vm_offset_t to);
72 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
73 		vm_offset_t to);
74 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
75 			       int pageno, vm_page_t m);
76 static void vfs_clean_pages(struct buf * bp);
77 static void vfs_setdirty(struct buf *bp);
78 static void vfs_vmio_release(struct buf *bp);
79 static void vfs_backgroundwritedone(struct buf *bp);
80 static int flushbufqueues(void);
81 
82 static int bd_request;
83 
84 static void buf_daemon __P((void));
85 /*
86  * bogus page -- for I/O to/from partially complete buffers
87  * this is a temporary solution to the problem, but it is not
88  * really that bad.  it would be better to split the buffer
89  * for input in the case of buffers partially already in memory,
90  * but the code is intricate enough already.
91  */
92 vm_page_t bogus_page;
93 int vmiodirenable = FALSE;
94 int runningbufspace;
95 static vm_offset_t bogus_offset;
96 
97 static int bufspace, maxbufspace,
98 	bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
99 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
100 static int needsbuffer;
101 static int lorunningspace, hirunningspace, runningbufreq;
102 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
103 static int numfreebuffers, lofreebuffers, hifreebuffers;
104 static int getnewbufcalls;
105 static int getnewbufrestarts;
106 
107 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
108 	&numdirtybuffers, 0, "");
109 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
110 	&lodirtybuffers, 0, "");
111 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
112 	&hidirtybuffers, 0, "");
113 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
114 	&numfreebuffers, 0, "");
115 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
116 	&lofreebuffers, 0, "");
117 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
118 	&hifreebuffers, 0, "");
119 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
120 	&runningbufspace, 0, "");
121 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW,
122 	&lorunningspace, 0, "");
123 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW,
124 	&hirunningspace, 0, "");
125 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD,
126 	&maxbufspace, 0, "");
127 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
128 	&hibufspace, 0, "");
129 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD,
130 	&lobufspace, 0, "");
131 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
132 	&bufspace, 0, "");
133 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
134 	&maxbufmallocspace, 0, "");
135 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
136 	&bufmallocspace, 0, "");
137 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW,
138 	&getnewbufcalls, 0, "");
139 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW,
140 	&getnewbufrestarts, 0, "");
141 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW,
142 	&vmiodirenable, 0, "");
143 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW,
144 	&bufdefragcnt, 0, "");
145 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW,
146 	&buffreekvacnt, 0, "");
147 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW,
148 	&bufreusecnt, 0, "");
149 
150 static int bufhashmask;
151 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
152 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
153 char *buf_wmesg = BUF_WMESG;
154 
155 extern int vm_swap_size;
156 
157 #define VFS_BIO_NEED_ANY	0x01	/* any freeable buffer */
158 #define VFS_BIO_NEED_DIRTYFLUSH	0x02	/* waiting for dirty buffer flush */
159 #define VFS_BIO_NEED_FREE	0x04	/* wait for free bufs, hi hysteresis */
160 #define VFS_BIO_NEED_BUFSPACE	0x08	/* wait for buf space, lo hysteresis */
161 
162 /*
163  * Buffer hash table code.  Note that the logical block scans linearly, which
164  * gives us some L1 cache locality.
165  */
166 
167 static __inline
168 struct bufhashhdr *
169 bufhash(struct vnode *vnp, daddr_t bn)
170 {
171 	return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
172 }
173 
174 /*
175  *	numdirtywakeup:
176  *
177  *	If someone is blocked due to there being too many dirty buffers,
178  *	and numdirtybuffers is now reasonable, wake them up.
179  */
180 
181 static __inline void
182 numdirtywakeup(int level)
183 {
184 	if (numdirtybuffers <= level) {
185 		if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
186 			needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
187 			wakeup(&needsbuffer);
188 		}
189 	}
190 }
191 
192 /*
193  *	bufspacewakeup:
194  *
195  *	Called when buffer space is potentially available for recovery.
196  *	getnewbuf() will block on this flag when it is unable to free
197  *	sufficient buffer space.  Buffer space becomes recoverable when
198  *	bp's get placed back in the queues.
199  */
200 
201 static __inline void
202 bufspacewakeup(void)
203 {
204 	/*
205 	 * If someone is waiting for BUF space, wake them up.  Even
206 	 * though we haven't freed the kva space yet, the waiting
207 	 * process will be able to now.
208 	 */
209 	if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
210 		needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
211 		wakeup(&needsbuffer);
212 	}
213 }
214 
215 /*
216  * runningbufwakeup() - in-progress I/O accounting.
217  *
218  */
219 static __inline void
220 runningbufwakeup(struct buf *bp)
221 {
222 	if (bp->b_runningbufspace) {
223 		runningbufspace -= bp->b_runningbufspace;
224 		bp->b_runningbufspace = 0;
225 		if (runningbufreq && runningbufspace <= lorunningspace) {
226 			runningbufreq = 0;
227 			wakeup(&runningbufreq);
228 		}
229 	}
230 }
231 
232 /*
233  *	bufcountwakeup:
234  *
235  *	Called when a buffer has been added to one of the free queues to
236  *	account for the buffer and to wakeup anyone waiting for free buffers.
237  *	This typically occurs when large amounts of metadata are being handled
238  *	by the buffer cache ( else buffer space runs out first, usually ).
239  */
240 
241 static __inline void
242 bufcountwakeup(void)
243 {
244 	++numfreebuffers;
245 	if (needsbuffer) {
246 		needsbuffer &= ~VFS_BIO_NEED_ANY;
247 		if (numfreebuffers >= hifreebuffers)
248 			needsbuffer &= ~VFS_BIO_NEED_FREE;
249 		wakeup(&needsbuffer);
250 	}
251 }
252 
253 /*
254  *	waitrunningbufspace()
255  *
256  *	runningbufspace is a measure of the amount of I/O currently
257  *	running.  This routine is used in async-write situations to
258  *	prevent creating huge backups of pending writes to a device.
259  *	Only asynchronous writes are governed by this function.
260  *
261  *	Reads will adjust runningbufspace, but will not block based on it.
262  *	The read load has a side effect of reducing the allowed write load.
263  *
264  *	This does NOT turn an async write into a sync write.  It waits
265  *	for earlier writes to complete and generally returns before the
266  *	caller's write has reached the device.
267  */
268 static __inline void
269 waitrunningbufspace(void)
270 {
271 	while (runningbufspace > hirunningspace) {
272 		++runningbufreq;
273 		tsleep(&runningbufreq, PVM, "wdrain", 0);
274 	}
275 }
276 
277 
278 /*
279  *	vfs_buf_test_cache:
280  *
281  *	Called when a buffer is extended.  This function clears the B_CACHE
282  *	bit if the newly extended portion of the buffer does not contain
283  *	valid data.
284  *
285  *	must be called with vm_mtx held
286  */
287 static __inline__
288 void
289 vfs_buf_test_cache(struct buf *bp,
290 		  vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
291 		  vm_page_t m)
292 {
293 	if (bp->b_flags & B_CACHE) {
294 		int base = (foff + off) & PAGE_MASK;
295 		if (vm_page_is_valid(m, base, size) == 0)
296 			bp->b_flags &= ~B_CACHE;
297 	}
298 }
299 
300 static __inline__
301 void
302 bd_wakeup(int dirtybuflevel)
303 {
304 	if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
305 		bd_request = 1;
306 		wakeup(&bd_request);
307 	}
308 }
309 
310 /*
311  * bd_speedup - speedup the buffer cache flushing code
312  */
313 
314 static __inline__
315 void
316 bd_speedup(void)
317 {
318 	bd_wakeup(1);
319 }
320 
321 /*
322  * Initialize buffer headers and related structures.
323  */
324 
325 caddr_t
326 bufhashinit(caddr_t vaddr)
327 {
328 	/* first, make a null hash table */
329 	for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
330 		;
331 	bufhashtbl = (void *)vaddr;
332 	vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
333 	--bufhashmask;
334 	return(vaddr);
335 }
336 
337 void
338 bufinit(void)
339 {
340 	struct buf *bp;
341 	int i;
342 
343 	TAILQ_INIT(&bswlist);
344 	LIST_INIT(&invalhash);
345 	mtx_init(&buftimelock, "buftime lock", MTX_DEF);
346 
347 	for (i = 0; i <= bufhashmask; i++)
348 		LIST_INIT(&bufhashtbl[i]);
349 
350 	/* next, make a null set of free lists */
351 	for (i = 0; i < BUFFER_QUEUES; i++)
352 		TAILQ_INIT(&bufqueues[i]);
353 
354 	/* finally, initialize each buffer header and stick on empty q */
355 	for (i = 0; i < nbuf; i++) {
356 		bp = &buf[i];
357 		bzero(bp, sizeof *bp);
358 		bp->b_flags = B_INVAL;	/* we're just an empty header */
359 		bp->b_dev = NODEV;
360 		bp->b_rcred = NOCRED;
361 		bp->b_wcred = NOCRED;
362 		bp->b_qindex = QUEUE_EMPTY;
363 		bp->b_xflags = 0;
364 		LIST_INIT(&bp->b_dep);
365 		BUF_LOCKINIT(bp);
366 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
367 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
368 	}
369 
370 	/*
371 	 * maxbufspace is the absolute maximum amount of buffer space we are
372 	 * allowed to reserve in KVM and in real terms.  The absolute maximum
373 	 * is nominally used by buf_daemon.  hibufspace is the nominal maximum
374 	 * used by most other processes.  The differential is required to
375 	 * ensure that buf_daemon is able to run when other processes might
376 	 * be blocked waiting for buffer space.
377 	 *
378 	 * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
379 	 * this may result in KVM fragmentation which is not handled optimally
380 	 * by the system.
381 	 */
382 	maxbufspace = nbuf * BKVASIZE;
383 	hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
384 	lobufspace = hibufspace - MAXBSIZE;
385 
386 	lorunningspace = 512 * 1024;
387 	hirunningspace = 1024 * 1024;
388 
389 /*
390  * Limit the amount of malloc memory since it is wired permanently into
391  * the kernel space.  Even though this is accounted for in the buffer
392  * allocation, we don't want the malloced region to grow uncontrolled.
393  * The malloc scheme improves memory utilization significantly on average
394  * (small) directories.
395  */
396 	maxbufmallocspace = hibufspace / 20;
397 
398 /*
399  * Reduce the chance of a deadlock occuring by limiting the number
400  * of delayed-write dirty buffers we allow to stack up.
401  */
402 	hidirtybuffers = nbuf / 4 + 20;
403 	numdirtybuffers = 0;
404 /*
405  * To support extreme low-memory systems, make sure hidirtybuffers cannot
406  * eat up all available buffer space.  This occurs when our minimum cannot
407  * be met.  We try to size hidirtybuffers to 3/4 our buffer space assuming
408  * BKVASIZE'd (8K) buffers.
409  */
410 	while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
411 		hidirtybuffers >>= 1;
412 	}
413 	lodirtybuffers = hidirtybuffers / 2;
414 
415 /*
416  * Try to keep the number of free buffers in the specified range,
417  * and give special processes (e.g. like buf_daemon) access to an
418  * emergency reserve.
419  */
420 	lofreebuffers = nbuf / 18 + 5;
421 	hifreebuffers = 2 * lofreebuffers;
422 	numfreebuffers = nbuf;
423 
424 /*
425  * Maximum number of async ops initiated per buf_daemon loop.  This is
426  * somewhat of a hack at the moment, we really need to limit ourselves
427  * based on the number of bytes of I/O in-transit that were initiated
428  * from buf_daemon.
429  */
430 
431 	mtx_lock(&vm_mtx);
432 	bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
433 	bogus_page = vm_page_alloc(kernel_object,
434 			((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
435 			VM_ALLOC_NORMAL);
436 	cnt.v_wire_count++;
437 	mtx_unlock(&vm_mtx);
438 
439 }
440 
441 /*
442  * bfreekva() - free the kva allocation for a buffer.
443  *
444  *	Must be called at splbio() or higher as this is the only locking for
445  *	buffer_map.
446  *
447  *	Since this call frees up buffer space, we call bufspacewakeup().
448  *
449  *	Must be called without the vm_mtx.
450  */
451 static void
452 bfreekva(struct buf * bp)
453 {
454 
455 	mtx_assert(&vm_mtx, MA_NOTOWNED);
456 	if (bp->b_kvasize) {
457 		++buffreekvacnt;
458 		bufspace -= bp->b_kvasize;
459 		mtx_lock(&vm_mtx);
460 		vm_map_delete(buffer_map,
461 		    (vm_offset_t) bp->b_kvabase,
462 		    (vm_offset_t) bp->b_kvabase + bp->b_kvasize
463 		);
464 		mtx_unlock(&vm_mtx);
465 		bp->b_kvasize = 0;
466 		bufspacewakeup();
467 	}
468 }
469 
470 /*
471  *	bremfree:
472  *
473  *	Remove the buffer from the appropriate free list.
474  */
475 void
476 bremfree(struct buf * bp)
477 {
478 	int s = splbio();
479 	int old_qindex = bp->b_qindex;
480 
481 	if (bp->b_qindex != QUEUE_NONE) {
482 		KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
483 		TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
484 		bp->b_qindex = QUEUE_NONE;
485 	} else {
486 		if (BUF_REFCNT(bp) <= 1)
487 			panic("bremfree: removing a buffer not on a queue");
488 	}
489 
490 	/*
491 	 * Fixup numfreebuffers count.  If the buffer is invalid or not
492 	 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
493 	 * the buffer was free and we must decrement numfreebuffers.
494 	 */
495 	if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
496 		switch(old_qindex) {
497 		case QUEUE_DIRTY:
498 		case QUEUE_CLEAN:
499 		case QUEUE_EMPTY:
500 		case QUEUE_EMPTYKVA:
501 			--numfreebuffers;
502 			break;
503 		default:
504 			break;
505 		}
506 	}
507 	splx(s);
508 }
509 
510 
511 /*
512  * Get a buffer with the specified data.  Look in the cache first.  We
513  * must clear BIO_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
514  * is set, the buffer is valid and we do not have to do anything ( see
515  * getblk() ).  This is really just a special case of breadn().
516  */
517 int
518 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
519     struct buf ** bpp)
520 {
521 
522 	return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp));
523 }
524 
525 /*
526  * Operates like bread, but also starts asynchronous I/O on
527  * read-ahead blocks.  We must clear BIO_ERROR and B_INVAL prior
528  * to initiating I/O . If B_CACHE is set, the buffer is valid
529  * and we do not have to do anything.
530  */
531 int
532 breadn(struct vnode * vp, daddr_t blkno, int size,
533     daddr_t * rablkno, int *rabsize,
534     int cnt, struct ucred * cred, struct buf ** bpp)
535 {
536 	struct buf *bp, *rabp;
537 	int i;
538 	int rv = 0, readwait = 0;
539 
540 	*bpp = bp = getblk(vp, blkno, size, 0, 0);
541 
542 	/* if not found in cache, do some I/O */
543 	if ((bp->b_flags & B_CACHE) == 0) {
544 		if (curproc != PCPU_GET(idleproc))
545 			curproc->p_stats->p_ru.ru_inblock++;
546 		bp->b_iocmd = BIO_READ;
547 		bp->b_flags &= ~B_INVAL;
548 		bp->b_ioflags &= ~BIO_ERROR;
549 		if (bp->b_rcred == NOCRED) {
550 			if (cred != NOCRED)
551 				crhold(cred);
552 			bp->b_rcred = cred;
553 		}
554 		vfs_busy_pages(bp, 0);
555 		VOP_STRATEGY(vp, bp);
556 		++readwait;
557 	}
558 
559 	for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
560 		if (inmem(vp, *rablkno))
561 			continue;
562 		rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
563 
564 		if ((rabp->b_flags & B_CACHE) == 0) {
565 			if (curproc != PCPU_GET(idleproc))
566 				curproc->p_stats->p_ru.ru_inblock++;
567 			rabp->b_flags |= B_ASYNC;
568 			rabp->b_flags &= ~B_INVAL;
569 			rabp->b_ioflags &= ~BIO_ERROR;
570 			rabp->b_iocmd = BIO_READ;
571 			if (rabp->b_rcred == NOCRED) {
572 				if (cred != NOCRED)
573 					crhold(cred);
574 				rabp->b_rcred = cred;
575 			}
576 			vfs_busy_pages(rabp, 0);
577 			BUF_KERNPROC(rabp);
578 			VOP_STRATEGY(vp, rabp);
579 		} else {
580 			brelse(rabp);
581 		}
582 	}
583 
584 	if (readwait) {
585 		rv = bufwait(bp);
586 	}
587 	return (rv);
588 }
589 
590 /*
591  * Write, release buffer on completion.  (Done by iodone
592  * if async).  Do not bother writing anything if the buffer
593  * is invalid.
594  *
595  * Note that we set B_CACHE here, indicating that buffer is
596  * fully valid and thus cacheable.  This is true even of NFS
597  * now so we set it generally.  This could be set either here
598  * or in biodone() since the I/O is synchronous.  We put it
599  * here.
600  */
601 
602 int dobkgrdwrite = 1;
603 SYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0, "");
604 
605 int
606 bwrite(struct buf * bp)
607 {
608 	int oldflags, s;
609 	struct buf *newbp;
610 
611 	if (bp->b_flags & B_INVAL) {
612 		brelse(bp);
613 		return (0);
614 	}
615 
616 	oldflags = bp->b_flags;
617 
618 	if (BUF_REFCNT(bp) == 0)
619 		panic("bwrite: buffer is not busy???");
620 	s = splbio();
621 	/*
622 	 * If a background write is already in progress, delay
623 	 * writing this block if it is asynchronous. Otherwise
624 	 * wait for the background write to complete.
625 	 */
626 	if (bp->b_xflags & BX_BKGRDINPROG) {
627 		if (bp->b_flags & B_ASYNC) {
628 			splx(s);
629 			bdwrite(bp);
630 			return (0);
631 		}
632 		bp->b_xflags |= BX_BKGRDWAIT;
633 		tsleep(&bp->b_xflags, PRIBIO, "biord", 0);
634 		if (bp->b_xflags & BX_BKGRDINPROG)
635 			panic("bwrite: still writing");
636 	}
637 
638 	/* Mark the buffer clean */
639 	bundirty(bp);
640 
641 	/*
642 	 * If this buffer is marked for background writing and we
643 	 * do not have to wait for it, make a copy and write the
644 	 * copy so as to leave this buffer ready for further use.
645 	 *
646 	 * This optimization eats a lot of memory.  If we have a page
647 	 * or buffer shortfall we can't do it.
648 	 */
649 	if (dobkgrdwrite && (bp->b_xflags & BX_BKGRDWRITE) &&
650 	    (bp->b_flags & B_ASYNC) &&
651 	    !vm_page_count_severe() &&
652 	    !buf_dirty_count_severe()) {
653 		if (bp->b_iodone != NULL) {
654 			printf("bp->b_iodone = %p\n", bp->b_iodone);
655 			panic("bwrite: need chained iodone");
656 		}
657 
658 		/* get a new block */
659 		newbp = geteblk(bp->b_bufsize);
660 
661 		/* set it to be identical to the old block */
662 		memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
663 		bgetvp(bp->b_vp, newbp);
664 		newbp->b_lblkno = bp->b_lblkno;
665 		newbp->b_blkno = bp->b_blkno;
666 		newbp->b_offset = bp->b_offset;
667 		newbp->b_iodone = vfs_backgroundwritedone;
668 		newbp->b_flags |= B_ASYNC;
669 		newbp->b_flags &= ~B_INVAL;
670 
671 		/* move over the dependencies */
672 		if (LIST_FIRST(&bp->b_dep) != NULL)
673 			buf_movedeps(bp, newbp);
674 
675 		/*
676 		 * Initiate write on the copy, release the original to
677 		 * the B_LOCKED queue so that it cannot go away until
678 		 * the background write completes. If not locked it could go
679 		 * away and then be reconstituted while it was being written.
680 		 * If the reconstituted buffer were written, we could end up
681 		 * with two background copies being written at the same time.
682 		 */
683 		bp->b_xflags |= BX_BKGRDINPROG;
684 		bp->b_flags |= B_LOCKED;
685 		bqrelse(bp);
686 		bp = newbp;
687 	}
688 
689 	bp->b_flags &= ~B_DONE;
690 	bp->b_ioflags &= ~BIO_ERROR;
691 	bp->b_flags |= B_WRITEINPROG | B_CACHE;
692 	bp->b_iocmd = BIO_WRITE;
693 
694 	bp->b_vp->v_numoutput++;
695 	vfs_busy_pages(bp, 1);
696 
697 	/*
698 	 * Normal bwrites pipeline writes
699 	 */
700 	bp->b_runningbufspace = bp->b_bufsize;
701 	runningbufspace += bp->b_runningbufspace;
702 
703 	if (curproc != PCPU_GET(idleproc))
704 		curproc->p_stats->p_ru.ru_oublock++;
705 	splx(s);
706 	if (oldflags & B_ASYNC)
707 		BUF_KERNPROC(bp);
708 	BUF_STRATEGY(bp);
709 
710 	if ((oldflags & B_ASYNC) == 0) {
711 		int rtval = bufwait(bp);
712 		brelse(bp);
713 		return (rtval);
714 	} else {
715 		/*
716 		 * don't allow the async write to saturate the I/O
717 		 * system.  There is no chance of deadlock here because
718 		 * we are blocking on I/O that is already in-progress.
719 		 */
720 		waitrunningbufspace();
721 	}
722 
723 	return (0);
724 }
725 
726 /*
727  * Complete a background write started from bwrite.
728  */
729 static void
730 vfs_backgroundwritedone(bp)
731 	struct buf *bp;
732 {
733 	struct buf *origbp;
734 
735 	/*
736 	 * Find the original buffer that we are writing.
737 	 */
738 	if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
739 		panic("backgroundwritedone: lost buffer");
740 	/*
741 	 * Process dependencies then return any unfinished ones.
742 	 */
743 	if (LIST_FIRST(&bp->b_dep) != NULL)
744 		buf_complete(bp);
745 	if (LIST_FIRST(&bp->b_dep) != NULL)
746 		buf_movedeps(bp, origbp);
747 	/*
748 	 * Clear the BX_BKGRDINPROG flag in the original buffer
749 	 * and awaken it if it is waiting for the write to complete.
750 	 * If BX_BKGRDINPROG is not set in the original buffer it must
751 	 * have been released and re-instantiated - which is not legal.
752 	 */
753 	KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
754 	origbp->b_xflags &= ~BX_BKGRDINPROG;
755 	if (origbp->b_xflags & BX_BKGRDWAIT) {
756 		origbp->b_xflags &= ~BX_BKGRDWAIT;
757 		wakeup(&origbp->b_xflags);
758 	}
759 	/*
760 	 * Clear the B_LOCKED flag and remove it from the locked
761 	 * queue if it currently resides there.
762 	 */
763 	origbp->b_flags &= ~B_LOCKED;
764 	if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
765 		bremfree(origbp);
766 		bqrelse(origbp);
767 	}
768 	/*
769 	 * This buffer is marked B_NOCACHE, so when it is released
770 	 * by biodone, it will be tossed. We mark it with BIO_READ
771 	 * to avoid biodone doing a second vwakeup.
772 	 */
773 	bp->b_flags |= B_NOCACHE;
774 	bp->b_iocmd = BIO_READ;
775 	bp->b_flags &= ~(B_CACHE | B_DONE);
776 	bp->b_iodone = 0;
777 	bufdone(bp);
778 }
779 
780 /*
781  * Delayed write. (Buffer is marked dirty).  Do not bother writing
782  * anything if the buffer is marked invalid.
783  *
784  * Note that since the buffer must be completely valid, we can safely
785  * set B_CACHE.  In fact, we have to set B_CACHE here rather then in
786  * biodone() in order to prevent getblk from writing the buffer
787  * out synchronously.
788  */
789 void
790 bdwrite(struct buf * bp)
791 {
792 	if (BUF_REFCNT(bp) == 0)
793 		panic("bdwrite: buffer is not busy");
794 
795 	if (bp->b_flags & B_INVAL) {
796 		brelse(bp);
797 		return;
798 	}
799 	bdirty(bp);
800 
801 	/*
802 	 * Set B_CACHE, indicating that the buffer is fully valid.  This is
803 	 * true even of NFS now.
804 	 */
805 	bp->b_flags |= B_CACHE;
806 
807 	/*
808 	 * This bmap keeps the system from needing to do the bmap later,
809 	 * perhaps when the system is attempting to do a sync.  Since it
810 	 * is likely that the indirect block -- or whatever other datastructure
811 	 * that the filesystem needs is still in memory now, it is a good
812 	 * thing to do this.  Note also, that if the pageout daemon is
813 	 * requesting a sync -- there might not be enough memory to do
814 	 * the bmap then...  So, this is important to do.
815 	 */
816 	if (bp->b_lblkno == bp->b_blkno) {
817 		VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
818 	}
819 
820 	mtx_lock(&vm_mtx);
821 	/*
822 	 * Set the *dirty* buffer range based upon the VM system dirty pages.
823 	 */
824 	vfs_setdirty(bp);
825 
826 	/*
827 	 * We need to do this here to satisfy the vnode_pager and the
828 	 * pageout daemon, so that it thinks that the pages have been
829 	 * "cleaned".  Note that since the pages are in a delayed write
830 	 * buffer -- the VFS layer "will" see that the pages get written
831 	 * out on the next sync, or perhaps the cluster will be completed.
832 	 */
833 	vfs_clean_pages(bp);
834 	mtx_unlock(&vm_mtx);
835 	bqrelse(bp);
836 
837 	/*
838 	 * Wakeup the buffer flushing daemon if we have a lot of dirty
839 	 * buffers (midpoint between our recovery point and our stall
840 	 * point).
841 	 */
842 	bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
843 
844 	/*
845 	 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
846 	 * due to the softdep code.
847 	 */
848 }
849 
850 /*
851  *	bdirty:
852  *
853  *	Turn buffer into delayed write request.  We must clear BIO_READ and
854  *	B_RELBUF, and we must set B_DELWRI.  We reassign the buffer to
855  *	itself to properly update it in the dirty/clean lists.  We mark it
856  *	B_DONE to ensure that any asynchronization of the buffer properly
857  *	clears B_DONE ( else a panic will occur later ).
858  *
859  *	bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
860  *	might have been set pre-getblk().  Unlike bwrite/bdwrite, bdirty()
861  *	should only be called if the buffer is known-good.
862  *
863  *	Since the buffer is not on a queue, we do not update the numfreebuffers
864  *	count.
865  *
866  *	Must be called at splbio().
867  *	The buffer must be on QUEUE_NONE.
868  */
869 void
870 bdirty(bp)
871 	struct buf *bp;
872 {
873 	KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
874 	bp->b_flags &= ~(B_RELBUF);
875 	bp->b_iocmd = BIO_WRITE;
876 
877 	if ((bp->b_flags & B_DELWRI) == 0) {
878 		bp->b_flags |= B_DONE | B_DELWRI;
879 		reassignbuf(bp, bp->b_vp);
880 		++numdirtybuffers;
881 		bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
882 	}
883 }
884 
885 /*
886  *	bundirty:
887  *
888  *	Clear B_DELWRI for buffer.
889  *
890  *	Since the buffer is not on a queue, we do not update the numfreebuffers
891  *	count.
892  *
893  *	Must be called at splbio().
894  *	The buffer must be on QUEUE_NONE.
895  */
896 
897 void
898 bundirty(bp)
899 	struct buf *bp;
900 {
901 	KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
902 
903 	if (bp->b_flags & B_DELWRI) {
904 		bp->b_flags &= ~B_DELWRI;
905 		reassignbuf(bp, bp->b_vp);
906 		--numdirtybuffers;
907 		numdirtywakeup(lodirtybuffers);
908 	}
909 	/*
910 	 * Since it is now being written, we can clear its deferred write flag.
911 	 */
912 	bp->b_flags &= ~B_DEFERRED;
913 }
914 
915 /*
916  *	bawrite:
917  *
918  *	Asynchronous write.  Start output on a buffer, but do not wait for
919  *	it to complete.  The buffer is released when the output completes.
920  *
921  *	bwrite() ( or the VOP routine anyway ) is responsible for handling
922  *	B_INVAL buffers.  Not us.
923  */
924 void
925 bawrite(struct buf * bp)
926 {
927 	bp->b_flags |= B_ASYNC;
928 	(void) BUF_WRITE(bp);
929 }
930 
931 /*
932  *	bowrite:
933  *
934  *	Ordered write.  Start output on a buffer, and flag it so that the
935  *	device will write it in the order it was queued.  The buffer is
936  *	released when the output completes.  bwrite() ( or the VOP routine
937  *	anyway ) is responsible for handling B_INVAL buffers.
938  */
939 int
940 bowrite(struct buf * bp)
941 {
942 	bp->b_ioflags |= BIO_ORDERED;
943 	bp->b_flags |= B_ASYNC;
944 	return (BUF_WRITE(bp));
945 }
946 
947 /*
948  *	bwillwrite:
949  *
950  *	Called prior to the locking of any vnodes when we are expecting to
951  *	write.  We do not want to starve the buffer cache with too many
952  *	dirty buffers so we block here.  By blocking prior to the locking
953  *	of any vnodes we attempt to avoid the situation where a locked vnode
954  *	prevents the various system daemons from flushing related buffers.
955  */
956 
957 void
958 bwillwrite(void)
959 {
960 	if (numdirtybuffers >= hidirtybuffers) {
961 		int s;
962 
963 		s = splbio();
964 		while (numdirtybuffers >= hidirtybuffers) {
965 			bd_wakeup(1);
966 			needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
967 			tsleep(&needsbuffer, (PRIBIO + 4), "flswai", 0);
968 		}
969 		splx(s);
970 	}
971 }
972 
973 /*
974  * Return true if we have too many dirty buffers.
975  */
976 int
977 buf_dirty_count_severe(void)
978 {
979 	return(numdirtybuffers >= hidirtybuffers);
980 }
981 
982 /*
983  *	brelse:
984  *
985  *	Release a busy buffer and, if requested, free its resources.  The
986  *	buffer will be stashed in the appropriate bufqueue[] allowing it
987  *	to be accessed later as a cache entity or reused for other purposes.
988  *
989  *	vm_mtx must be not be held.
990  */
991 void
992 brelse(struct buf * bp)
993 {
994 	int s;
995 
996 	mtx_assert(&vm_mtx, MA_NOTOWNED);
997 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
998 
999 	s = splbio();
1000 
1001 	if (bp->b_flags & B_LOCKED)
1002 		bp->b_ioflags &= ~BIO_ERROR;
1003 
1004 	if (bp->b_iocmd == BIO_WRITE &&
1005 	    (bp->b_ioflags & BIO_ERROR) &&
1006 	    !(bp->b_flags & B_INVAL)) {
1007 		/*
1008 		 * Failed write, redirty.  Must clear BIO_ERROR to prevent
1009 		 * pages from being scrapped.  If B_INVAL is set then
1010 		 * this case is not run and the next case is run to
1011 		 * destroy the buffer.  B_INVAL can occur if the buffer
1012 		 * is outside the range supported by the underlying device.
1013 		 */
1014 		bp->b_ioflags &= ~BIO_ERROR;
1015 		bdirty(bp);
1016 	} else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1017 	    (bp->b_ioflags & BIO_ERROR) ||
1018 	    bp->b_iocmd == BIO_DELETE || (bp->b_bufsize <= 0)) {
1019 		/*
1020 		 * Either a failed I/O or we were asked to free or not
1021 		 * cache the buffer.
1022 		 */
1023 		bp->b_flags |= B_INVAL;
1024 		if (LIST_FIRST(&bp->b_dep) != NULL)
1025 			buf_deallocate(bp);
1026 		if (bp->b_flags & B_DELWRI) {
1027 			--numdirtybuffers;
1028 			numdirtywakeup(lodirtybuffers);
1029 		}
1030 		bp->b_flags &= ~(B_DELWRI | B_CACHE);
1031 		if ((bp->b_flags & B_VMIO) == 0) {
1032 			if (bp->b_bufsize)
1033 				allocbuf(bp, 0);
1034 			if (bp->b_vp)
1035 				brelvp(bp);
1036 		}
1037 	}
1038 
1039 	/*
1040 	 * We must clear B_RELBUF if B_DELWRI is set.  If vfs_vmio_release()
1041 	 * is called with B_DELWRI set, the underlying pages may wind up
1042 	 * getting freed causing a previous write (bdwrite()) to get 'lost'
1043 	 * because pages associated with a B_DELWRI bp are marked clean.
1044 	 *
1045 	 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1046 	 * if B_DELWRI is set.
1047 	 *
1048 	 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1049 	 * on pages to return pages to the VM page queues.
1050 	 */
1051 	if (bp->b_flags & B_DELWRI)
1052 		bp->b_flags &= ~B_RELBUF;
1053 	else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1054 		bp->b_flags |= B_RELBUF;
1055 
1056 	/*
1057 	 * VMIO buffer rundown.  It is not very necessary to keep a VMIO buffer
1058 	 * constituted, not even NFS buffers now.  Two flags effect this.  If
1059 	 * B_INVAL, the struct buf is invalidated but the VM object is kept
1060 	 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1061 	 *
1062 	 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1063 	 * invalidated.  BIO_ERROR cannot be set for a failed write unless the
1064 	 * buffer is also B_INVAL because it hits the re-dirtying code above.
1065 	 *
1066 	 * Normally we can do this whether a buffer is B_DELWRI or not.  If
1067 	 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1068 	 * the commit state and we cannot afford to lose the buffer. If the
1069 	 * buffer has a background write in progress, we need to keep it
1070 	 * around to prevent it from being reconstituted and starting a second
1071 	 * background write.
1072 	 */
1073 	if ((bp->b_flags & B_VMIO)
1074 	    && !(bp->b_vp->v_tag == VT_NFS &&
1075 		 !vn_isdisk(bp->b_vp, NULL) &&
1076 		 (bp->b_flags & B_DELWRI))
1077 	    ) {
1078 
1079 		int i, j, resid;
1080 		vm_page_t m;
1081 		off_t foff;
1082 		vm_pindex_t poff;
1083 		vm_object_t obj;
1084 		struct vnode *vp;
1085 
1086 		vp = bp->b_vp;
1087 
1088 		/*
1089 		 * Get the base offset and length of the buffer.  Note that
1090 		 * for block sizes that are less then PAGE_SIZE, the b_data
1091 		 * base of the buffer does not represent exactly b_offset and
1092 		 * neither b_offset nor b_size are necessarily page aligned.
1093 		 * Instead, the starting position of b_offset is:
1094 		 *
1095 		 * 	b_data + (b_offset & PAGE_MASK)
1096 		 *
1097 		 * block sizes less then DEV_BSIZE (usually 512) are not
1098 		 * supported due to the page granularity bits (m->valid,
1099 		 * m->dirty, etc...).
1100 		 *
1101 		 * See man buf(9) for more information
1102 		 */
1103 		resid = bp->b_bufsize;
1104 		foff = bp->b_offset;
1105 
1106 		mtx_lock(&vm_mtx);
1107 		for (i = 0; i < bp->b_npages; i++) {
1108 			int had_bogus = 0;
1109 
1110 			m = bp->b_pages[i];
1111 			vm_page_flag_clear(m, PG_ZERO);
1112 
1113 			/*
1114 			 * If we hit a bogus page, fixup *all* the bogus pages
1115 			 * now.
1116 			 */
1117 			if (m == bogus_page) {
1118 				mtx_unlock(&vm_mtx);
1119 				VOP_GETVOBJECT(vp, &obj);
1120 				poff = OFF_TO_IDX(bp->b_offset);
1121 				had_bogus = 1;
1122 
1123 				mtx_lock(&vm_mtx);
1124 				for (j = i; j < bp->b_npages; j++) {
1125 					vm_page_t mtmp;
1126 					mtmp = bp->b_pages[j];
1127 					if (mtmp == bogus_page) {
1128 						mtmp = vm_page_lookup(obj, poff + j);
1129 						if (!mtmp) {
1130 							panic("brelse: page missing\n");
1131 						}
1132 						bp->b_pages[j] = mtmp;
1133 					}
1134 				}
1135 
1136 				if ((bp->b_flags & B_INVAL) == 0) {
1137 					pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1138 				}
1139 				m = bp->b_pages[i];
1140 			}
1141 			if ((bp->b_flags & B_NOCACHE) || (bp->b_ioflags & BIO_ERROR)) {
1142 				int poffset = foff & PAGE_MASK;
1143 				int presid = resid > (PAGE_SIZE - poffset) ?
1144 					(PAGE_SIZE - poffset) : resid;
1145 
1146 				KASSERT(presid >= 0, ("brelse: extra page"));
1147 				vm_page_set_invalid(m, poffset, presid);
1148 				if (had_bogus)
1149 					printf("avoided corruption bug in bogus_page/brelse code\n");
1150 			}
1151 			resid -= PAGE_SIZE - (foff & PAGE_MASK);
1152 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1153 		}
1154 
1155 		if (bp->b_flags & (B_INVAL | B_RELBUF))
1156 			vfs_vmio_release(bp);
1157 		mtx_unlock(&vm_mtx);
1158 
1159 	} else if (bp->b_flags & B_VMIO) {
1160 
1161 		if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1162 			mtx_lock(&vm_mtx);
1163 			vfs_vmio_release(bp);
1164 			mtx_unlock(&vm_mtx);
1165 		}
1166 
1167 	}
1168 
1169 	if (bp->b_qindex != QUEUE_NONE)
1170 		panic("brelse: free buffer onto another queue???");
1171 	if (BUF_REFCNT(bp) > 1) {
1172 		/* do not release to free list */
1173 		BUF_UNLOCK(bp);
1174 		splx(s);
1175 		return;
1176 	}
1177 
1178 	/* enqueue */
1179 
1180 	/* buffers with no memory */
1181 	if (bp->b_bufsize == 0) {
1182 		bp->b_flags |= B_INVAL;
1183 		bp->b_xflags &= ~BX_BKGRDWRITE;
1184 		if (bp->b_xflags & BX_BKGRDINPROG)
1185 			panic("losing buffer 1");
1186 		if (bp->b_kvasize) {
1187 			bp->b_qindex = QUEUE_EMPTYKVA;
1188 		} else {
1189 			bp->b_qindex = QUEUE_EMPTY;
1190 		}
1191 		TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1192 		LIST_REMOVE(bp, b_hash);
1193 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1194 		bp->b_dev = NODEV;
1195 	/* buffers with junk contents */
1196 	} else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) || (bp->b_ioflags & BIO_ERROR)) {
1197 		bp->b_flags |= B_INVAL;
1198 		bp->b_xflags &= ~BX_BKGRDWRITE;
1199 		if (bp->b_xflags & BX_BKGRDINPROG)
1200 			panic("losing buffer 2");
1201 		bp->b_qindex = QUEUE_CLEAN;
1202 		TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1203 		LIST_REMOVE(bp, b_hash);
1204 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1205 		bp->b_dev = NODEV;
1206 
1207 	/* buffers that are locked */
1208 	} else if (bp->b_flags & B_LOCKED) {
1209 		bp->b_qindex = QUEUE_LOCKED;
1210 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1211 
1212 	/* remaining buffers */
1213 	} else {
1214 		if (bp->b_flags & B_DELWRI)
1215 			bp->b_qindex = QUEUE_DIRTY;
1216 		else
1217 			bp->b_qindex = QUEUE_CLEAN;
1218 		if (bp->b_flags & B_AGE)
1219 			TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1220 		else
1221 			TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1222 	}
1223 
1224 	/*
1225 	 * If B_INVAL, clear B_DELWRI.  We've already placed the buffer
1226 	 * on the correct queue.
1227 	 */
1228 	if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI)) {
1229 		bp->b_flags &= ~B_DELWRI;
1230 		--numdirtybuffers;
1231 		numdirtywakeup(lodirtybuffers);
1232 	}
1233 
1234 	/*
1235 	 * Fixup numfreebuffers count.  The bp is on an appropriate queue
1236 	 * unless locked.  We then bump numfreebuffers if it is not B_DELWRI.
1237 	 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1238 	 * if B_INVAL is set ).
1239 	 */
1240 
1241 	if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1242 		bufcountwakeup();
1243 
1244 	/*
1245 	 * Something we can maybe free or reuse
1246 	 */
1247 	if (bp->b_bufsize || bp->b_kvasize)
1248 		bufspacewakeup();
1249 
1250 	/* unlock */
1251 	BUF_UNLOCK(bp);
1252 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1253 	bp->b_ioflags &= ~BIO_ORDERED;
1254 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1255 		panic("brelse: not dirty");
1256 	splx(s);
1257 }
1258 
1259 /*
1260  * Release a buffer back to the appropriate queue but do not try to free
1261  * it.  The buffer is expected to be used again soon.
1262  *
1263  * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1264  * biodone() to requeue an async I/O on completion.  It is also used when
1265  * known good buffers need to be requeued but we think we may need the data
1266  * again soon.
1267  *
1268  * XXX we should be able to leave the B_RELBUF hint set on completion.
1269  */
1270 void
1271 bqrelse(struct buf * bp)
1272 {
1273 	int s;
1274 
1275 	s = splbio();
1276 
1277 	KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1278 
1279 	if (bp->b_qindex != QUEUE_NONE)
1280 		panic("bqrelse: free buffer onto another queue???");
1281 	if (BUF_REFCNT(bp) > 1) {
1282 		/* do not release to free list */
1283 		BUF_UNLOCK(bp);
1284 		splx(s);
1285 		return;
1286 	}
1287 	if (bp->b_flags & B_LOCKED) {
1288 		bp->b_ioflags &= ~BIO_ERROR;
1289 		bp->b_qindex = QUEUE_LOCKED;
1290 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1291 		/* buffers with stale but valid contents */
1292 	} else if (bp->b_flags & B_DELWRI) {
1293 		bp->b_qindex = QUEUE_DIRTY;
1294 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1295 	} else if (vm_page_count_severe()) {
1296 		/*
1297 		 * We are too low on memory, we have to try to free the
1298 		 * buffer (most importantly: the wired pages making up its
1299 		 * backing store) *now*.
1300 		 */
1301 		splx(s);
1302 		brelse(bp);
1303 		return;
1304 	} else {
1305 		bp->b_qindex = QUEUE_CLEAN;
1306 		TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1307 	}
1308 
1309 	if ((bp->b_flags & B_LOCKED) == 0 &&
1310 	    ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1311 		bufcountwakeup();
1312 	}
1313 
1314 	/*
1315 	 * Something we can maybe free or reuse.
1316 	 */
1317 	if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1318 		bufspacewakeup();
1319 
1320 	/* unlock */
1321 	BUF_UNLOCK(bp);
1322 	bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1323 	bp->b_ioflags &= ~BIO_ORDERED;
1324 	if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1325 		panic("bqrelse: not dirty");
1326 	splx(s);
1327 }
1328 
1329 /*
1330  * Must be called with vm_mtx held.
1331  */
1332 static void
1333 vfs_vmio_release(bp)
1334 	struct buf *bp;
1335 {
1336 	int i;
1337 	vm_page_t m;
1338 
1339 	mtx_assert(&vm_mtx, MA_OWNED);
1340 	for (i = 0; i < bp->b_npages; i++) {
1341 		m = bp->b_pages[i];
1342 		bp->b_pages[i] = NULL;
1343 		/*
1344 		 * In order to keep page LRU ordering consistent, put
1345 		 * everything on the inactive queue.
1346 		 */
1347 		vm_page_unwire(m, 0);
1348 		/*
1349 		 * We don't mess with busy pages, it is
1350 		 * the responsibility of the process that
1351 		 * busied the pages to deal with them.
1352 		 */
1353 		if ((m->flags & PG_BUSY) || (m->busy != 0))
1354 			continue;
1355 
1356 		if (m->wire_count == 0) {
1357 			vm_page_flag_clear(m, PG_ZERO);
1358 			/*
1359 			 * Might as well free the page if we can and it has
1360 			 * no valid data.  We also free the page if the
1361 			 * buffer was used for direct I/O
1362 			 */
1363 			if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1364 				vm_page_busy(m);
1365 				vm_page_protect(m, VM_PROT_NONE);
1366 				vm_page_free(m);
1367 			} else if (bp->b_flags & B_DIRECT) {
1368 				vm_page_try_to_free(m);
1369 			} else if (vm_page_count_severe()) {
1370 				vm_page_try_to_cache(m);
1371 			}
1372 		}
1373 	}
1374 	pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1375 
1376 	/* could drop vm_mtx here */
1377 
1378 	if (bp->b_bufsize) {
1379 		bufspacewakeup();
1380 		bp->b_bufsize = 0;
1381 	}
1382 	bp->b_npages = 0;
1383 	bp->b_flags &= ~B_VMIO;
1384 	if (bp->b_vp)
1385 		brelvp(bp);
1386 }
1387 
1388 /*
1389  * Check to see if a block is currently memory resident.
1390  */
1391 struct buf *
1392 gbincore(struct vnode * vp, daddr_t blkno)
1393 {
1394 	struct buf *bp;
1395 	struct bufhashhdr *bh;
1396 
1397 	bh = bufhash(vp, blkno);
1398 
1399 	/* Search hash chain */
1400 	LIST_FOREACH(bp, bh, b_hash) {
1401 		/* hit */
1402 		if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1403 		    (bp->b_flags & B_INVAL) == 0) {
1404 			break;
1405 		}
1406 	}
1407 	return (bp);
1408 }
1409 
1410 /*
1411  *	vfs_bio_awrite:
1412  *
1413  *	Implement clustered async writes for clearing out B_DELWRI buffers.
1414  *	This is much better then the old way of writing only one buffer at
1415  *	a time.  Note that we may not be presented with the buffers in the
1416  *	correct order, so we search for the cluster in both directions.
1417  */
1418 int
1419 vfs_bio_awrite(struct buf * bp)
1420 {
1421 	int i;
1422 	int j;
1423 	daddr_t lblkno = bp->b_lblkno;
1424 	struct vnode *vp = bp->b_vp;
1425 	int s;
1426 	int ncl;
1427 	struct buf *bpa;
1428 	int nwritten;
1429 	int size;
1430 	int maxcl;
1431 
1432 	s = splbio();
1433 	/*
1434 	 * right now we support clustered writing only to regular files.  If
1435 	 * we find a clusterable block we could be in the middle of a cluster
1436 	 * rather then at the beginning.
1437 	 */
1438 	if ((vp->v_type == VREG) &&
1439 	    (vp->v_mount != 0) && /* Only on nodes that have the size info */
1440 	    (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1441 
1442 		size = vp->v_mount->mnt_stat.f_iosize;
1443 		maxcl = MAXPHYS / size;
1444 
1445 		for (i = 1; i < maxcl; i++) {
1446 			if ((bpa = gbincore(vp, lblkno + i)) &&
1447 			    BUF_REFCNT(bpa) == 0 &&
1448 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1449 			    (B_DELWRI | B_CLUSTEROK)) &&
1450 			    (bpa->b_bufsize == size)) {
1451 				if ((bpa->b_blkno == bpa->b_lblkno) ||
1452 				    (bpa->b_blkno !=
1453 				     bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1454 					break;
1455 			} else {
1456 				break;
1457 			}
1458 		}
1459 		for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1460 			if ((bpa = gbincore(vp, lblkno - j)) &&
1461 			    BUF_REFCNT(bpa) == 0 &&
1462 			    ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1463 			    (B_DELWRI | B_CLUSTEROK)) &&
1464 			    (bpa->b_bufsize == size)) {
1465 				if ((bpa->b_blkno == bpa->b_lblkno) ||
1466 				    (bpa->b_blkno !=
1467 				     bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1468 					break;
1469 			} else {
1470 				break;
1471 			}
1472 		}
1473 		--j;
1474 		ncl = i + j;
1475 		/*
1476 		 * this is a possible cluster write
1477 		 */
1478 		if (ncl != 1) {
1479 			nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1480 			splx(s);
1481 			return nwritten;
1482 		}
1483 	}
1484 
1485 	BUF_LOCK(bp, LK_EXCLUSIVE);
1486 	bremfree(bp);
1487 	bp->b_flags |= B_ASYNC;
1488 
1489 	splx(s);
1490 	/*
1491 	 * default (old) behavior, writing out only one block
1492 	 *
1493 	 * XXX returns b_bufsize instead of b_bcount for nwritten?
1494 	 */
1495 	nwritten = bp->b_bufsize;
1496 	(void) BUF_WRITE(bp);
1497 
1498 	return nwritten;
1499 }
1500 
1501 /*
1502  *	getnewbuf:
1503  *
1504  *	Find and initialize a new buffer header, freeing up existing buffers
1505  *	in the bufqueues as necessary.  The new buffer is returned locked.
1506  *
1507  *	Important:  B_INVAL is not set.  If the caller wishes to throw the
1508  *	buffer away, the caller must set B_INVAL prior to calling brelse().
1509  *
1510  *	We block if:
1511  *		We have insufficient buffer headers
1512  *		We have insufficient buffer space
1513  *		buffer_map is too fragmented ( space reservation fails )
1514  *		If we have to flush dirty buffers ( but we try to avoid this )
1515  *
1516  *	To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1517  *	Instead we ask the buf daemon to do it for us.  We attempt to
1518  *	avoid piecemeal wakeups of the pageout daemon.
1519  */
1520 
1521 static struct buf *
1522 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1523 {
1524 	struct buf *bp;
1525 	struct buf *nbp;
1526 	int defrag = 0;
1527 	int nqindex;
1528 	static int flushingbufs;
1529 
1530 	/*
1531 	 * We can't afford to block since we might be holding a vnode lock,
1532 	 * which may prevent system daemons from running.  We deal with
1533 	 * low-memory situations by proactively returning memory and running
1534 	 * async I/O rather then sync I/O.
1535 	 */
1536 
1537 	++getnewbufcalls;
1538 	--getnewbufrestarts;
1539 restart:
1540 	++getnewbufrestarts;
1541 
1542 	/*
1543 	 * Setup for scan.  If we do not have enough free buffers,
1544 	 * we setup a degenerate case that immediately fails.  Note
1545 	 * that if we are specially marked process, we are allowed to
1546 	 * dip into our reserves.
1547 	 *
1548 	 * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1549 	 *
1550 	 * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1551 	 * However, there are a number of cases (defragging, reusing, ...)
1552 	 * where we cannot backup.
1553 	 */
1554 	nqindex = QUEUE_EMPTYKVA;
1555 	nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1556 
1557 	if (nbp == NULL) {
1558 		/*
1559 		 * If no EMPTYKVA buffers and we are either
1560 		 * defragging or reusing, locate a CLEAN buffer
1561 		 * to free or reuse.  If bufspace useage is low
1562 		 * skip this step so we can allocate a new buffer.
1563 		 */
1564 		if (defrag || bufspace >= lobufspace) {
1565 			nqindex = QUEUE_CLEAN;
1566 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1567 		}
1568 
1569 		/*
1570 		 * If we could not find or were not allowed to reuse a
1571 		 * CLEAN buffer, check to see if it is ok to use an EMPTY
1572 		 * buffer.  We can only use an EMPTY buffer if allocating
1573 		 * its KVA would not otherwise run us out of buffer space.
1574 		 */
1575 		if (nbp == NULL && defrag == 0 &&
1576 		    bufspace + maxsize < hibufspace) {
1577 			nqindex = QUEUE_EMPTY;
1578 			nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1579 		}
1580 	}
1581 
1582 	/*
1583 	 * Run scan, possibly freeing data and/or kva mappings on the fly
1584 	 * depending.
1585 	 */
1586 
1587 	while ((bp = nbp) != NULL) {
1588 		int qindex = nqindex;
1589 
1590 		/*
1591 		 * Calculate next bp ( we can only use it if we do not block
1592 		 * or do other fancy things ).
1593 		 */
1594 		if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1595 			switch(qindex) {
1596 			case QUEUE_EMPTY:
1597 				nqindex = QUEUE_EMPTYKVA;
1598 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1599 					break;
1600 				/* fall through */
1601 			case QUEUE_EMPTYKVA:
1602 				nqindex = QUEUE_CLEAN;
1603 				if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1604 					break;
1605 				/* fall through */
1606 			case QUEUE_CLEAN:
1607 				/*
1608 				 * nbp is NULL.
1609 				 */
1610 				break;
1611 			}
1612 		}
1613 
1614 		/*
1615 		 * Sanity Checks
1616 		 */
1617 		KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1618 
1619 		/*
1620 		 * Note: we no longer distinguish between VMIO and non-VMIO
1621 		 * buffers.
1622 		 */
1623 
1624 		KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1625 
1626 		/*
1627 		 * If we are defragging then we need a buffer with
1628 		 * b_kvasize != 0.  XXX this situation should no longer
1629 		 * occur, if defrag is non-zero the buffer's b_kvasize
1630 		 * should also be non-zero at this point.  XXX
1631 		 */
1632 		if (defrag && bp->b_kvasize == 0) {
1633 			printf("Warning: defrag empty buffer %p\n", bp);
1634 			continue;
1635 		}
1636 
1637 		/*
1638 		 * Start freeing the bp.  This is somewhat involved.  nbp
1639 		 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1640 		 */
1641 
1642 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1643 			panic("getnewbuf: locked buf");
1644 		bremfree(bp);
1645 
1646 		if (qindex == QUEUE_CLEAN) {
1647 			if (bp->b_flags & B_VMIO) {
1648 				bp->b_flags &= ~B_ASYNC;
1649 				mtx_lock(&vm_mtx);
1650 				vfs_vmio_release(bp);
1651 				mtx_unlock(&vm_mtx);
1652 			}
1653 			if (bp->b_vp)
1654 				brelvp(bp);
1655 		}
1656 
1657 		/*
1658 		 * NOTE:  nbp is now entirely invalid.  We can only restart
1659 		 * the scan from this point on.
1660 		 *
1661 		 * Get the rest of the buffer freed up.  b_kva* is still
1662 		 * valid after this operation.
1663 		 */
1664 
1665 		if (bp->b_rcred != NOCRED) {
1666 			crfree(bp->b_rcred);
1667 			bp->b_rcred = NOCRED;
1668 		}
1669 		if (bp->b_wcred != NOCRED) {
1670 			crfree(bp->b_wcred);
1671 			bp->b_wcred = NOCRED;
1672 		}
1673 		if (LIST_FIRST(&bp->b_dep) != NULL)
1674 			buf_deallocate(bp);
1675 		if (bp->b_xflags & BX_BKGRDINPROG)
1676 			panic("losing buffer 3");
1677 		LIST_REMOVE(bp, b_hash);
1678 		LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1679 
1680 		if (bp->b_bufsize)
1681 			allocbuf(bp, 0);
1682 
1683 		bp->b_flags = 0;
1684 		bp->b_ioflags = 0;
1685 		bp->b_xflags = 0;
1686 		bp->b_dev = NODEV;
1687 		bp->b_vp = NULL;
1688 		bp->b_blkno = bp->b_lblkno = 0;
1689 		bp->b_offset = NOOFFSET;
1690 		bp->b_iodone = 0;
1691 		bp->b_error = 0;
1692 		bp->b_resid = 0;
1693 		bp->b_bcount = 0;
1694 		bp->b_npages = 0;
1695 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1696 		bp->b_magic = B_MAGIC_BIO;
1697 		bp->b_op = &buf_ops_bio;
1698 
1699 		LIST_INIT(&bp->b_dep);
1700 
1701 		/*
1702 		 * If we are defragging then free the buffer.
1703 		 */
1704 		if (defrag) {
1705 			bp->b_flags |= B_INVAL;
1706 			bfreekva(bp);
1707 			brelse(bp);
1708 			defrag = 0;
1709 			goto restart;
1710 		}
1711 
1712 		/*
1713 		 * If we are overcomitted then recover the buffer and its
1714 		 * KVM space.  This occurs in rare situations when multiple
1715 		 * processes are blocked in getnewbuf() or allocbuf().
1716 		 */
1717 		if (bufspace >= hibufspace)
1718 			flushingbufs = 1;
1719 		if (flushingbufs && bp->b_kvasize != 0) {
1720 			bp->b_flags |= B_INVAL;
1721 			bfreekva(bp);
1722 			brelse(bp);
1723 			goto restart;
1724 		}
1725 		if (bufspace < lobufspace)
1726 			flushingbufs = 0;
1727 		break;
1728 	}
1729 
1730 	/*
1731 	 * If we exhausted our list, sleep as appropriate.  We may have to
1732 	 * wakeup various daemons and write out some dirty buffers.
1733 	 *
1734 	 * Generally we are sleeping due to insufficient buffer space.
1735 	 */
1736 
1737 	if (bp == NULL) {
1738 		int flags;
1739 		char *waitmsg;
1740 
1741 		if (defrag) {
1742 			flags = VFS_BIO_NEED_BUFSPACE;
1743 			waitmsg = "nbufkv";
1744 		} else if (bufspace >= hibufspace) {
1745 			waitmsg = "nbufbs";
1746 			flags = VFS_BIO_NEED_BUFSPACE;
1747 		} else {
1748 			waitmsg = "newbuf";
1749 			flags = VFS_BIO_NEED_ANY;
1750 		}
1751 
1752 		bd_speedup();	/* heeeelp */
1753 
1754 		needsbuffer |= flags;
1755 		while (needsbuffer & flags) {
1756 			if (tsleep(&needsbuffer, (PRIBIO + 4) | slpflag,
1757 			    waitmsg, slptimeo))
1758 				return (NULL);
1759 		}
1760 	} else {
1761 		/*
1762 		 * We finally have a valid bp.  We aren't quite out of the
1763 		 * woods, we still have to reserve kva space.  In order
1764 		 * to keep fragmentation sane we only allocate kva in
1765 		 * BKVASIZE chunks.
1766 		 */
1767 		maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1768 
1769 		if (maxsize != bp->b_kvasize) {
1770 			vm_offset_t addr = 0;
1771 
1772 			bfreekva(bp);
1773 
1774 			mtx_lock(&vm_mtx);
1775 			if (vm_map_findspace(buffer_map,
1776 				vm_map_min(buffer_map), maxsize, &addr)) {
1777 				/*
1778 				 * Uh oh.  Buffer map is to fragmented.  We
1779 				 * must defragment the map.
1780 				 */
1781 				mtx_unlock(&vm_mtx);
1782 				++bufdefragcnt;
1783 				defrag = 1;
1784 				bp->b_flags |= B_INVAL;
1785 				brelse(bp);
1786 				goto restart;
1787 			}
1788 			if (addr) {
1789 				vm_map_insert(buffer_map, NULL, 0,
1790 					addr, addr + maxsize,
1791 					VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1792 
1793 				bp->b_kvabase = (caddr_t) addr;
1794 				bp->b_kvasize = maxsize;
1795 				bufspace += bp->b_kvasize;
1796 				++bufreusecnt;
1797 			}
1798 			mtx_unlock(&vm_mtx);
1799 		}
1800 		bp->b_data = bp->b_kvabase;
1801 	}
1802 	return(bp);
1803 }
1804 
1805 /*
1806  *	buf_daemon:
1807  *
1808  *	buffer flushing daemon.  Buffers are normally flushed by the
1809  *	update daemon but if it cannot keep up this process starts to
1810  *	take the load in an attempt to prevent getnewbuf() from blocking.
1811  */
1812 
1813 static struct proc *bufdaemonproc;
1814 
1815 static struct kproc_desc buf_kp = {
1816 	"bufdaemon",
1817 	buf_daemon,
1818 	&bufdaemonproc
1819 };
1820 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1821 
1822 static void
1823 buf_daemon()
1824 {
1825 	int s;
1826 
1827 	mtx_lock(&Giant);
1828 
1829 	/*
1830 	 * This process needs to be suspended prior to shutdown sync.
1831 	 */
1832 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
1833 	    SHUTDOWN_PRI_LAST);
1834 
1835 	/*
1836 	 * This process is allowed to take the buffer cache to the limit
1837 	 */
1838 	curproc->p_flag |= P_BUFEXHAUST;
1839 	s = splbio();
1840 
1841 	for (;;) {
1842 		kthread_suspend_check(bufdaemonproc);
1843 
1844 		bd_request = 0;
1845 
1846 		/*
1847 		 * Do the flush.  Limit the amount of in-transit I/O we
1848 		 * allow to build up, otherwise we would completely saturate
1849 		 * the I/O system.  Wakeup any waiting processes before we
1850 		 * normally would so they can run in parallel with our drain.
1851 		 */
1852 		while (numdirtybuffers > lodirtybuffers) {
1853 			if (flushbufqueues() == 0)
1854 				break;
1855 			waitrunningbufspace();
1856 			numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1857 		}
1858 
1859 		/*
1860 		 * Only clear bd_request if we have reached our low water
1861 		 * mark.  The buf_daemon normally waits 5 seconds and
1862 		 * then incrementally flushes any dirty buffers that have
1863 		 * built up, within reason.
1864 		 *
1865 		 * If we were unable to hit our low water mark and couldn't
1866 		 * find any flushable buffers, we sleep half a second.
1867 		 * Otherwise we loop immediately.
1868 		 */
1869 		if (numdirtybuffers <= lodirtybuffers) {
1870 			/*
1871 			 * We reached our low water mark, reset the
1872 			 * request and sleep until we are needed again.
1873 			 * The sleep is just so the suspend code works.
1874 			 */
1875 			bd_request = 0;
1876 			tsleep(&bd_request, PVM, "psleep", hz);
1877 		} else {
1878 			/*
1879 			 * We couldn't find any flushable dirty buffers but
1880 			 * still have too many dirty buffers, we
1881 			 * have to sleep and try again.  (rare)
1882 			 */
1883 			tsleep(&bd_request, PVM, "qsleep", hz / 2);
1884 		}
1885 	}
1886 }
1887 
1888 /*
1889  *	flushbufqueues:
1890  *
1891  *	Try to flush a buffer in the dirty queue.  We must be careful to
1892  *	free up B_INVAL buffers instead of write them, which NFS is
1893  *	particularly sensitive to.
1894  */
1895 
1896 static int
1897 flushbufqueues(void)
1898 {
1899 	struct buf *bp;
1900 	int r = 0;
1901 
1902 	bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1903 
1904 	while (bp) {
1905 		KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1906 		if ((bp->b_flags & B_DELWRI) != 0 &&
1907 		    (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1908 			if (bp->b_flags & B_INVAL) {
1909 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1910 					panic("flushbufqueues: locked buf");
1911 				bremfree(bp);
1912 				brelse(bp);
1913 				++r;
1914 				break;
1915 			}
1916 			if (LIST_FIRST(&bp->b_dep) != NULL &&
1917 			    (bp->b_flags & B_DEFERRED) == 0 &&
1918 			    buf_countdeps(bp, 0)) {
1919 				TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
1920 				    bp, b_freelist);
1921 				TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
1922 				    bp, b_freelist);
1923 				bp->b_flags |= B_DEFERRED;
1924 				bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1925 				continue;
1926 			}
1927 			vfs_bio_awrite(bp);
1928 			++r;
1929 			break;
1930 		}
1931 		bp = TAILQ_NEXT(bp, b_freelist);
1932 	}
1933 	return (r);
1934 }
1935 
1936 /*
1937  * Check to see if a block is currently memory resident.
1938  */
1939 struct buf *
1940 incore(struct vnode * vp, daddr_t blkno)
1941 {
1942 	struct buf *bp;
1943 
1944 	int s = splbio();
1945 	bp = gbincore(vp, blkno);
1946 	splx(s);
1947 	return (bp);
1948 }
1949 
1950 /*
1951  * Returns true if no I/O is needed to access the
1952  * associated VM object.  This is like incore except
1953  * it also hunts around in the VM system for the data.
1954  */
1955 
1956 int
1957 inmem(struct vnode * vp, daddr_t blkno)
1958 {
1959 	vm_object_t obj;
1960 	vm_offset_t toff, tinc, size;
1961 	vm_page_t m;
1962 	vm_ooffset_t off;
1963 
1964 	if (incore(vp, blkno))
1965 		return 1;
1966 	if (vp->v_mount == NULL)
1967 		return 0;
1968 	if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
1969 		return 0;
1970 
1971 	size = PAGE_SIZE;
1972 	if (size > vp->v_mount->mnt_stat.f_iosize)
1973 		size = vp->v_mount->mnt_stat.f_iosize;
1974 	off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
1975 
1976 	mtx_lock(&vm_mtx);
1977 	for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1978 		m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1979 		if (!m)
1980 			goto notinmem;
1981 		tinc = size;
1982 		if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
1983 			tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
1984 		if (vm_page_is_valid(m,
1985 		    (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
1986 			goto notinmem;
1987 	}
1988 	mtx_unlock(&vm_mtx);
1989 	return 1;
1990 
1991 notinmem:
1992 	mtx_unlock(&vm_mtx);
1993 	return (0);
1994 }
1995 
1996 /*
1997  *	vfs_setdirty:
1998  *
1999  *	Sets the dirty range for a buffer based on the status of the dirty
2000  *	bits in the pages comprising the buffer.
2001  *
2002  *	The range is limited to the size of the buffer.
2003  *
2004  *	This routine is primarily used by NFS, but is generalized for the
2005  *	B_VMIO case.
2006  *
2007  *	Must be called with vm_mtx
2008  */
2009 static void
2010 vfs_setdirty(struct buf *bp)
2011 {
2012 	int i;
2013 	vm_object_t object;
2014 
2015 	mtx_assert(&vm_mtx, MA_OWNED);
2016 	/*
2017 	 * Degenerate case - empty buffer
2018 	 */
2019 
2020 	if (bp->b_bufsize == 0)
2021 		return;
2022 
2023 	/*
2024 	 * We qualify the scan for modified pages on whether the
2025 	 * object has been flushed yet.  The OBJ_WRITEABLE flag
2026 	 * is not cleared simply by protecting pages off.
2027 	 */
2028 
2029 	if ((bp->b_flags & B_VMIO) == 0)
2030 		return;
2031 
2032 	object = bp->b_pages[0]->object;
2033 
2034 	if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2035 		printf("Warning: object %p writeable but not mightbedirty\n", object);
2036 	if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2037 		printf("Warning: object %p mightbedirty but not writeable\n", object);
2038 
2039 	if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2040 		vm_offset_t boffset;
2041 		vm_offset_t eoffset;
2042 
2043 		/*
2044 		 * test the pages to see if they have been modified directly
2045 		 * by users through the VM system.
2046 		 */
2047 		for (i = 0; i < bp->b_npages; i++) {
2048 			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
2049 			vm_page_test_dirty(bp->b_pages[i]);
2050 		}
2051 
2052 		/*
2053 		 * Calculate the encompassing dirty range, boffset and eoffset,
2054 		 * (eoffset - boffset) bytes.
2055 		 */
2056 
2057 		for (i = 0; i < bp->b_npages; i++) {
2058 			if (bp->b_pages[i]->dirty)
2059 				break;
2060 		}
2061 		boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2062 
2063 		for (i = bp->b_npages - 1; i >= 0; --i) {
2064 			if (bp->b_pages[i]->dirty) {
2065 				break;
2066 			}
2067 		}
2068 		eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2069 
2070 		/*
2071 		 * Fit it to the buffer.
2072 		 */
2073 
2074 		if (eoffset > bp->b_bcount)
2075 			eoffset = bp->b_bcount;
2076 
2077 		/*
2078 		 * If we have a good dirty range, merge with the existing
2079 		 * dirty range.
2080 		 */
2081 
2082 		if (boffset < eoffset) {
2083 			if (bp->b_dirtyoff > boffset)
2084 				bp->b_dirtyoff = boffset;
2085 			if (bp->b_dirtyend < eoffset)
2086 				bp->b_dirtyend = eoffset;
2087 		}
2088 	}
2089 }
2090 
2091 /*
2092  *	getblk:
2093  *
2094  *	Get a block given a specified block and offset into a file/device.
2095  *	The buffers B_DONE bit will be cleared on return, making it almost
2096  * 	ready for an I/O initiation.  B_INVAL may or may not be set on
2097  *	return.  The caller should clear B_INVAL prior to initiating a
2098  *	READ.
2099  *
2100  *	For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2101  *	an existing buffer.
2102  *
2103  *	For a VMIO buffer, B_CACHE is modified according to the backing VM.
2104  *	If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2105  *	and then cleared based on the backing VM.  If the previous buffer is
2106  *	non-0-sized but invalid, B_CACHE will be cleared.
2107  *
2108  *	If getblk() must create a new buffer, the new buffer is returned with
2109  *	both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2110  *	case it is returned with B_INVAL clear and B_CACHE set based on the
2111  *	backing VM.
2112  *
2113  *	getblk() also forces a BUF_WRITE() for any B_DELWRI buffer whos
2114  *	B_CACHE bit is clear.
2115  *
2116  *	What this means, basically, is that the caller should use B_CACHE to
2117  *	determine whether the buffer is fully valid or not and should clear
2118  *	B_INVAL prior to issuing a read.  If the caller intends to validate
2119  *	the buffer by loading its data area with something, the caller needs
2120  *	to clear B_INVAL.  If the caller does this without issuing an I/O,
2121  *	the caller should set B_CACHE ( as an optimization ), else the caller
2122  *	should issue the I/O and biodone() will set B_CACHE if the I/O was
2123  *	a write attempt or if it was a successfull read.  If the caller
2124  *	intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
2125  *	prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2126  */
2127 struct buf *
2128 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2129 {
2130 	struct buf *bp;
2131 	int s;
2132 	struct bufhashhdr *bh;
2133 
2134 	if (size > MAXBSIZE)
2135 		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2136 
2137 	s = splbio();
2138 loop:
2139 	/*
2140 	 * Block if we are low on buffers.   Certain processes are allowed
2141 	 * to completely exhaust the buffer cache.
2142          *
2143          * If this check ever becomes a bottleneck it may be better to
2144          * move it into the else, when gbincore() fails.  At the moment
2145          * it isn't a problem.
2146 	 *
2147 	 * XXX remove if 0 sections (clean this up after its proven)
2148          */
2149 	if (numfreebuffers == 0) {
2150 		if (curproc == PCPU_GET(idleproc))
2151 			return NULL;
2152 		needsbuffer |= VFS_BIO_NEED_ANY;
2153 	}
2154 
2155 	if ((bp = gbincore(vp, blkno))) {
2156 		/*
2157 		 * Buffer is in-core.  If the buffer is not busy, it must
2158 		 * be on a queue.
2159 		 */
2160 
2161 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2162 			if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2163 			    "getblk", slpflag, slptimeo) == ENOLCK)
2164 				goto loop;
2165 			splx(s);
2166 			return (struct buf *) NULL;
2167 		}
2168 
2169 		/*
2170 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2171 		 * invalid.  Ohterwise, for a non-VMIO buffer, B_CACHE is set
2172 		 * and for a VMIO buffer B_CACHE is adjusted according to the
2173 		 * backing VM cache.
2174 		 */
2175 		if (bp->b_flags & B_INVAL)
2176 			bp->b_flags &= ~B_CACHE;
2177 		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2178 			bp->b_flags |= B_CACHE;
2179 		bremfree(bp);
2180 
2181 		/*
2182 		 * check for size inconsistancies for non-VMIO case.
2183 		 */
2184 
2185 		if (bp->b_bcount != size) {
2186 			if ((bp->b_flags & B_VMIO) == 0 ||
2187 			    (size > bp->b_kvasize)) {
2188 				if (bp->b_flags & B_DELWRI) {
2189 					bp->b_flags |= B_NOCACHE;
2190 					BUF_WRITE(bp);
2191 				} else {
2192 					if ((bp->b_flags & B_VMIO) &&
2193 					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2194 						bp->b_flags |= B_RELBUF;
2195 						brelse(bp);
2196 					} else {
2197 						bp->b_flags |= B_NOCACHE;
2198 						BUF_WRITE(bp);
2199 					}
2200 				}
2201 				goto loop;
2202 			}
2203 		}
2204 
2205 		/*
2206 		 * If the size is inconsistant in the VMIO case, we can resize
2207 		 * the buffer.  This might lead to B_CACHE getting set or
2208 		 * cleared.  If the size has not changed, B_CACHE remains
2209 		 * unchanged from its previous state.
2210 		 */
2211 
2212 		if (bp->b_bcount != size)
2213 			allocbuf(bp, size);
2214 
2215 		KASSERT(bp->b_offset != NOOFFSET,
2216 		    ("getblk: no buffer offset"));
2217 
2218 		/*
2219 		 * A buffer with B_DELWRI set and B_CACHE clear must
2220 		 * be committed before we can return the buffer in
2221 		 * order to prevent the caller from issuing a read
2222 		 * ( due to B_CACHE not being set ) and overwriting
2223 		 * it.
2224 		 *
2225 		 * Most callers, including NFS and FFS, need this to
2226 		 * operate properly either because they assume they
2227 		 * can issue a read if B_CACHE is not set, or because
2228 		 * ( for example ) an uncached B_DELWRI might loop due
2229 		 * to softupdates re-dirtying the buffer.  In the latter
2230 		 * case, B_CACHE is set after the first write completes,
2231 		 * preventing further loops.
2232 		 */
2233 
2234 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2235 			BUF_WRITE(bp);
2236 			goto loop;
2237 		}
2238 
2239 		splx(s);
2240 		bp->b_flags &= ~B_DONE;
2241 	} else {
2242 		/*
2243 		 * Buffer is not in-core, create new buffer.  The buffer
2244 		 * returned by getnewbuf() is locked.  Note that the returned
2245 		 * buffer is also considered valid (not marked B_INVAL).
2246 		 */
2247 		int bsize, maxsize, vmio;
2248 		off_t offset;
2249 
2250 		if (vn_isdisk(vp, NULL))
2251 			bsize = DEV_BSIZE;
2252 		else if (vp->v_mountedhere)
2253 			bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2254 		else if (vp->v_mount)
2255 			bsize = vp->v_mount->mnt_stat.f_iosize;
2256 		else
2257 			bsize = size;
2258 
2259 		offset = (off_t)blkno * bsize;
2260 		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2261 		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2262 		maxsize = imax(maxsize, bsize);
2263 
2264 		if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2265 			if (slpflag || slptimeo) {
2266 				splx(s);
2267 				return NULL;
2268 			}
2269 			goto loop;
2270 		}
2271 
2272 		/*
2273 		 * This code is used to make sure that a buffer is not
2274 		 * created while the getnewbuf routine is blocked.
2275 		 * This can be a problem whether the vnode is locked or not.
2276 		 * If the buffer is created out from under us, we have to
2277 		 * throw away the one we just created.  There is now window
2278 		 * race because we are safely running at splbio() from the
2279 		 * point of the duplicate buffer creation through to here,
2280 		 * and we've locked the buffer.
2281 		 */
2282 		if (gbincore(vp, blkno)) {
2283 			bp->b_flags |= B_INVAL;
2284 			brelse(bp);
2285 			goto loop;
2286 		}
2287 
2288 		/*
2289 		 * Insert the buffer into the hash, so that it can
2290 		 * be found by incore.
2291 		 */
2292 		bp->b_blkno = bp->b_lblkno = blkno;
2293 		bp->b_offset = offset;
2294 
2295 		bgetvp(vp, bp);
2296 		LIST_REMOVE(bp, b_hash);
2297 		bh = bufhash(vp, blkno);
2298 		LIST_INSERT_HEAD(bh, bp, b_hash);
2299 
2300 		/*
2301 		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2302 		 * buffer size starts out as 0, B_CACHE will be set by
2303 		 * allocbuf() for the VMIO case prior to it testing the
2304 		 * backing store for validity.
2305 		 */
2306 
2307 		if (vmio) {
2308 			bp->b_flags |= B_VMIO;
2309 #if defined(VFS_BIO_DEBUG)
2310 			if (vp->v_type != VREG)
2311 				printf("getblk: vmioing file type %d???\n", vp->v_type);
2312 #endif
2313 		} else {
2314 			bp->b_flags &= ~B_VMIO;
2315 		}
2316 
2317 		allocbuf(bp, size);
2318 
2319 		splx(s);
2320 		bp->b_flags &= ~B_DONE;
2321 	}
2322 	return (bp);
2323 }
2324 
2325 /*
2326  * Get an empty, disassociated buffer of given size.  The buffer is initially
2327  * set to B_INVAL.
2328  */
2329 struct buf *
2330 geteblk(int size)
2331 {
2332 	struct buf *bp;
2333 	int s;
2334 	int maxsize;
2335 
2336 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2337 
2338 	s = splbio();
2339 	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2340 	splx(s);
2341 	allocbuf(bp, size);
2342 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2343 	return (bp);
2344 }
2345 
2346 
2347 /*
2348  * This code constitutes the buffer memory from either anonymous system
2349  * memory (in the case of non-VMIO operations) or from an associated
2350  * VM object (in the case of VMIO operations).  This code is able to
2351  * resize a buffer up or down.
2352  *
2353  * Note that this code is tricky, and has many complications to resolve
2354  * deadlock or inconsistant data situations.  Tread lightly!!!
2355  * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2356  * the caller.  Calling this code willy nilly can result in the loss of data.
2357  *
2358  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2359  * B_CACHE for the non-VMIO case.
2360  */
2361 
2362 int
2363 allocbuf(struct buf *bp, int size)
2364 {
2365 	int newbsize, mbsize;
2366 	int i;
2367 
2368 	if (BUF_REFCNT(bp) == 0)
2369 		panic("allocbuf: buffer not busy");
2370 
2371 	if (bp->b_kvasize < size)
2372 		panic("allocbuf: buffer too small");
2373 
2374 	if ((bp->b_flags & B_VMIO) == 0) {
2375 		caddr_t origbuf;
2376 		int origbufsize;
2377 		/*
2378 		 * Just get anonymous memory from the kernel.  Don't
2379 		 * mess with B_CACHE.
2380 		 */
2381 		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2382 #if !defined(NO_B_MALLOC)
2383 		if (bp->b_flags & B_MALLOC)
2384 			newbsize = mbsize;
2385 		else
2386 #endif
2387 			newbsize = round_page(size);
2388 
2389 		if (newbsize < bp->b_bufsize) {
2390 #if !defined(NO_B_MALLOC)
2391 			/*
2392 			 * malloced buffers are not shrunk
2393 			 */
2394 			if (bp->b_flags & B_MALLOC) {
2395 				if (newbsize) {
2396 					bp->b_bcount = size;
2397 				} else {
2398 					free(bp->b_data, M_BIOBUF);
2399 					if (bp->b_bufsize) {
2400 						bufmallocspace -= bp->b_bufsize;
2401 						bufspacewakeup();
2402 						bp->b_bufsize = 0;
2403 					}
2404 					bp->b_data = bp->b_kvabase;
2405 					bp->b_bcount = 0;
2406 					bp->b_flags &= ~B_MALLOC;
2407 				}
2408 				return 1;
2409 			}
2410 #endif
2411 			vm_hold_free_pages(
2412 			    bp,
2413 			    (vm_offset_t) bp->b_data + newbsize,
2414 			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2415 		} else if (newbsize > bp->b_bufsize) {
2416 #if !defined(NO_B_MALLOC)
2417 			/*
2418 			 * We only use malloced memory on the first allocation.
2419 			 * and revert to page-allocated memory when the buffer
2420 			 * grows.
2421 			 */
2422 			if ( (bufmallocspace < maxbufmallocspace) &&
2423 				(bp->b_bufsize == 0) &&
2424 				(mbsize <= PAGE_SIZE/2)) {
2425 
2426 				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2427 				bp->b_bufsize = mbsize;
2428 				bp->b_bcount = size;
2429 				bp->b_flags |= B_MALLOC;
2430 				bufmallocspace += mbsize;
2431 				return 1;
2432 			}
2433 #endif
2434 			origbuf = NULL;
2435 			origbufsize = 0;
2436 #if !defined(NO_B_MALLOC)
2437 			/*
2438 			 * If the buffer is growing on its other-than-first allocation,
2439 			 * then we revert to the page-allocation scheme.
2440 			 */
2441 			if (bp->b_flags & B_MALLOC) {
2442 				origbuf = bp->b_data;
2443 				origbufsize = bp->b_bufsize;
2444 				bp->b_data = bp->b_kvabase;
2445 				if (bp->b_bufsize) {
2446 					bufmallocspace -= bp->b_bufsize;
2447 					bufspacewakeup();
2448 					bp->b_bufsize = 0;
2449 				}
2450 				bp->b_flags &= ~B_MALLOC;
2451 				newbsize = round_page(newbsize);
2452 			}
2453 #endif
2454 			vm_hold_load_pages(
2455 			    bp,
2456 			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2457 			    (vm_offset_t) bp->b_data + newbsize);
2458 #if !defined(NO_B_MALLOC)
2459 			if (origbuf) {
2460 				bcopy(origbuf, bp->b_data, origbufsize);
2461 				free(origbuf, M_BIOBUF);
2462 			}
2463 #endif
2464 		}
2465 	} else {
2466 		vm_page_t m;
2467 		int desiredpages;
2468 
2469 		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2470 		desiredpages = (size == 0) ? 0 :
2471 			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2472 
2473 #if !defined(NO_B_MALLOC)
2474 		if (bp->b_flags & B_MALLOC)
2475 			panic("allocbuf: VMIO buffer can't be malloced");
2476 #endif
2477 		/*
2478 		 * Set B_CACHE initially if buffer is 0 length or will become
2479 		 * 0-length.
2480 		 */
2481 		if (size == 0 || bp->b_bufsize == 0)
2482 			bp->b_flags |= B_CACHE;
2483 
2484 		if (newbsize < bp->b_bufsize) {
2485 			/*
2486 			 * DEV_BSIZE aligned new buffer size is less then the
2487 			 * DEV_BSIZE aligned existing buffer size.  Figure out
2488 			 * if we have to remove any pages.
2489 			 */
2490 			mtx_lock(&vm_mtx);
2491 			if (desiredpages < bp->b_npages) {
2492 				for (i = desiredpages; i < bp->b_npages; i++) {
2493 					/*
2494 					 * the page is not freed here -- it
2495 					 * is the responsibility of
2496 					 * vnode_pager_setsize
2497 					 */
2498 					m = bp->b_pages[i];
2499 					KASSERT(m != bogus_page,
2500 					    ("allocbuf: bogus page found"));
2501 					while (vm_page_sleep_busy(m, TRUE, "biodep"))
2502 						;
2503 
2504 					bp->b_pages[i] = NULL;
2505 					vm_page_unwire(m, 0);
2506 				}
2507 				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2508 				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2509 				bp->b_npages = desiredpages;
2510 			}
2511 			mtx_unlock(&vm_mtx);
2512 		} else if (size > bp->b_bcount) {
2513 			/*
2514 			 * We are growing the buffer, possibly in a
2515 			 * byte-granular fashion.
2516 			 */
2517 			struct vnode *vp;
2518 			vm_object_t obj;
2519 			vm_offset_t toff;
2520 			vm_offset_t tinc;
2521 
2522 			/*
2523 			 * Step 1, bring in the VM pages from the object,
2524 			 * allocating them if necessary.  We must clear
2525 			 * B_CACHE if these pages are not valid for the
2526 			 * range covered by the buffer.
2527 			 */
2528 
2529 			vp = bp->b_vp;
2530 			VOP_GETVOBJECT(vp, &obj);
2531 
2532 			mtx_lock(&vm_mtx);
2533 			while (bp->b_npages < desiredpages) {
2534 				vm_page_t m;
2535 				vm_pindex_t pi;
2536 
2537 				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2538 				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2539 					/*
2540 					 * note: must allocate system pages
2541 					 * since blocking here could intefere
2542 					 * with paging I/O, no matter which
2543 					 * process we are.
2544 					 */
2545 					m = vm_page_alloc(obj, pi, VM_ALLOC_SYSTEM);
2546 					if (m == NULL) {
2547 						VM_WAIT;
2548 						vm_pageout_deficit += desiredpages - bp->b_npages;
2549 					} else {
2550 						vm_page_wire(m);
2551 						vm_page_wakeup(m);
2552 						bp->b_flags &= ~B_CACHE;
2553 						bp->b_pages[bp->b_npages] = m;
2554 						++bp->b_npages;
2555 					}
2556 					continue;
2557 				}
2558 
2559 				/*
2560 				 * We found a page.  If we have to sleep on it,
2561 				 * retry because it might have gotten freed out
2562 				 * from under us.
2563 				 *
2564 				 * We can only test PG_BUSY here.  Blocking on
2565 				 * m->busy might lead to a deadlock:
2566 				 *
2567 				 *  vm_fault->getpages->cluster_read->allocbuf
2568 				 *
2569 				 */
2570 
2571 				if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2572 					continue;
2573 
2574 				/*
2575 				 * We have a good page.  Should we wakeup the
2576 				 * page daemon?
2577 				 */
2578 				if ((curproc != pageproc) &&
2579 				    ((m->queue - m->pc) == PQ_CACHE) &&
2580 				    ((cnt.v_free_count + cnt.v_cache_count) <
2581 					(cnt.v_free_min + cnt.v_cache_min))) {
2582 					pagedaemon_wakeup();
2583 				}
2584 				vm_page_flag_clear(m, PG_ZERO);
2585 				vm_page_wire(m);
2586 				bp->b_pages[bp->b_npages] = m;
2587 				++bp->b_npages;
2588 			}
2589 
2590 			/*
2591 			 * Step 2.  We've loaded the pages into the buffer,
2592 			 * we have to figure out if we can still have B_CACHE
2593 			 * set.  Note that B_CACHE is set according to the
2594 			 * byte-granular range ( bcount and size ), new the
2595 			 * aligned range ( newbsize ).
2596 			 *
2597 			 * The VM test is against m->valid, which is DEV_BSIZE
2598 			 * aligned.  Needless to say, the validity of the data
2599 			 * needs to also be DEV_BSIZE aligned.  Note that this
2600 			 * fails with NFS if the server or some other client
2601 			 * extends the file's EOF.  If our buffer is resized,
2602 			 * B_CACHE may remain set! XXX
2603 			 */
2604 
2605 			toff = bp->b_bcount;
2606 			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2607 
2608 			while ((bp->b_flags & B_CACHE) && toff < size) {
2609 				vm_pindex_t pi;
2610 
2611 				if (tinc > (size - toff))
2612 					tinc = size - toff;
2613 
2614 				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2615 				    PAGE_SHIFT;
2616 
2617 				vfs_buf_test_cache(
2618 				    bp,
2619 				    bp->b_offset,
2620 				    toff,
2621 				    tinc,
2622 				    bp->b_pages[pi]
2623 				);
2624 				toff += tinc;
2625 				tinc = PAGE_SIZE;
2626 			}
2627 
2628 			/*
2629 			 * Step 3, fixup the KVM pmap.  Remember that
2630 			 * bp->b_data is relative to bp->b_offset, but
2631 			 * bp->b_offset may be offset into the first page.
2632 			 */
2633 
2634 			bp->b_data = (caddr_t)
2635 			    trunc_page((vm_offset_t)bp->b_data);
2636 			pmap_qenter(
2637 			    (vm_offset_t)bp->b_data,
2638 			    bp->b_pages,
2639 			    bp->b_npages
2640 			);
2641 
2642 			mtx_unlock(&vm_mtx);
2643 
2644 			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2645 			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2646 		}
2647 	}
2648 	if (newbsize < bp->b_bufsize)
2649 		bufspacewakeup();
2650 	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2651 	bp->b_bcount = size;		/* requested buffer size	*/
2652 	return 1;
2653 }
2654 
2655 /*
2656  *	bufwait:
2657  *
2658  *	Wait for buffer I/O completion, returning error status.  The buffer
2659  *	is left locked and B_DONE on return.  B_EINTR is converted into a EINTR
2660  *	error and cleared.
2661  */
2662 int
2663 bufwait(register struct buf * bp)
2664 {
2665 	int s;
2666 
2667 	s = splbio();
2668 	while ((bp->b_flags & B_DONE) == 0) {
2669 		if (bp->b_iocmd == BIO_READ)
2670 			tsleep(bp, PRIBIO, "biord", 0);
2671 		else
2672 			tsleep(bp, PRIBIO, "biowr", 0);
2673 	}
2674 	splx(s);
2675 	if (bp->b_flags & B_EINTR) {
2676 		bp->b_flags &= ~B_EINTR;
2677 		return (EINTR);
2678 	}
2679 	if (bp->b_ioflags & BIO_ERROR) {
2680 		return (bp->b_error ? bp->b_error : EIO);
2681 	} else {
2682 		return (0);
2683 	}
2684 }
2685 
2686  /*
2687   * Call back function from struct bio back up to struct buf.
2688   * The corresponding initialization lives in sys/conf.h:DEV_STRATEGY().
2689   */
2690 void
2691 bufdonebio(struct bio *bp)
2692 {
2693 	bufdone(bp->bio_caller2);
2694 }
2695 
2696 /*
2697  *	bufdone:
2698  *
2699  *	Finish I/O on a buffer, optionally calling a completion function.
2700  *	This is usually called from an interrupt so process blocking is
2701  *	not allowed.
2702  *
2703  *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2704  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
2705  *	assuming B_INVAL is clear.
2706  *
2707  *	For the VMIO case, we set B_CACHE if the op was a read and no
2708  *	read error occured, or if the op was a write.  B_CACHE is never
2709  *	set if the buffer is invalid or otherwise uncacheable.
2710  *
2711  *	biodone does not mess with B_INVAL, allowing the I/O routine or the
2712  *	initiator to leave B_INVAL set to brelse the buffer out of existance
2713  *	in the biodone routine.
2714  */
2715 void
2716 bufdone(struct buf *bp)
2717 {
2718 	int s, error;
2719 	void    (*biodone) __P((struct buf *));
2720 
2721 	s = splbio();
2722 
2723 	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2724 	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2725 
2726 	bp->b_flags |= B_DONE;
2727 	runningbufwakeup(bp);
2728 
2729 	if (bp->b_iocmd == BIO_DELETE) {
2730 		brelse(bp);
2731 		splx(s);
2732 		return;
2733 	}
2734 
2735 	if (bp->b_iocmd == BIO_WRITE) {
2736 		vwakeup(bp);
2737 	}
2738 
2739 	/* call optional completion function if requested */
2740 	if (bp->b_iodone != NULL) {
2741 		biodone = bp->b_iodone;
2742 		bp->b_iodone = NULL;
2743 		(*biodone) (bp);
2744 		splx(s);
2745 		return;
2746 	}
2747 	if (LIST_FIRST(&bp->b_dep) != NULL)
2748 		buf_complete(bp);
2749 
2750 	if (bp->b_flags & B_VMIO) {
2751 		int i;
2752 		vm_ooffset_t foff;
2753 		vm_page_t m;
2754 		vm_object_t obj;
2755 		int iosize;
2756 		struct vnode *vp = bp->b_vp;
2757 
2758 		error = VOP_GETVOBJECT(vp, &obj);
2759 
2760 #if defined(VFS_BIO_DEBUG)
2761 		if (vp->v_usecount == 0) {
2762 			panic("biodone: zero vnode ref count");
2763 		}
2764 
2765 		if (error) {
2766 			panic("biodone: missing VM object");
2767 		}
2768 
2769 		if ((vp->v_flag & VOBJBUF) == 0) {
2770 			panic("biodone: vnode is not setup for merged cache");
2771 		}
2772 #endif
2773 
2774 		foff = bp->b_offset;
2775 		KASSERT(bp->b_offset != NOOFFSET,
2776 		    ("biodone: no buffer offset"));
2777 
2778 		if (error) {
2779 			panic("biodone: no object");
2780 		}
2781 		mtx_lock(&vm_mtx);
2782 #if defined(VFS_BIO_DEBUG)
2783 		if (obj->paging_in_progress < bp->b_npages) {
2784 			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2785 			    obj->paging_in_progress, bp->b_npages);
2786 		}
2787 #endif
2788 
2789 		/*
2790 		 * Set B_CACHE if the op was a normal read and no error
2791 		 * occured.  B_CACHE is set for writes in the b*write()
2792 		 * routines.
2793 		 */
2794 		iosize = bp->b_bcount - bp->b_resid;
2795 		if (bp->b_iocmd == BIO_READ &&
2796 		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
2797 		    !(bp->b_ioflags & BIO_ERROR)) {
2798 			bp->b_flags |= B_CACHE;
2799 		}
2800 
2801 		for (i = 0; i < bp->b_npages; i++) {
2802 			int bogusflag = 0;
2803 			int resid;
2804 
2805 			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2806 			if (resid > iosize)
2807 				resid = iosize;
2808 
2809 			/*
2810 			 * cleanup bogus pages, restoring the originals
2811 			 */
2812 			m = bp->b_pages[i];
2813 			if (m == bogus_page) {
2814 				bogusflag = 1;
2815 				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2816 				if (m == NULL)
2817 					panic("biodone: page disappeared!");
2818 				bp->b_pages[i] = m;
2819 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2820 			}
2821 #if defined(VFS_BIO_DEBUG)
2822 			if (OFF_TO_IDX(foff) != m->pindex) {
2823 				printf(
2824 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2825 				    (unsigned long)foff, m->pindex);
2826 			}
2827 #endif
2828 
2829 			/*
2830 			 * In the write case, the valid and clean bits are
2831 			 * already changed correctly ( see bdwrite() ), so we
2832 			 * only need to do this here in the read case.
2833 			 */
2834 			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
2835 				vfs_page_set_valid(bp, foff, i, m);
2836 			}
2837 			vm_page_flag_clear(m, PG_ZERO);
2838 
2839 			/*
2840 			 * when debugging new filesystems or buffer I/O methods, this
2841 			 * is the most common error that pops up.  if you see this, you
2842 			 * have not set the page busy flag correctly!!!
2843 			 */
2844 			if (m->busy == 0) {
2845 				printf("biodone: page busy < 0, "
2846 				    "pindex: %d, foff: 0x(%x,%x), "
2847 				    "resid: %d, index: %d\n",
2848 				    (int) m->pindex, (int)(foff >> 32),
2849 						(int) foff & 0xffffffff, resid, i);
2850 				if (!vn_isdisk(vp, NULL))
2851 					printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2852 					    bp->b_vp->v_mount->mnt_stat.f_iosize,
2853 					    (int) bp->b_lblkno,
2854 					    bp->b_flags, bp->b_npages);
2855 				else
2856 					printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2857 					    (int) bp->b_lblkno,
2858 					    bp->b_flags, bp->b_npages);
2859 				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2860 				    m->valid, m->dirty, m->wire_count);
2861 				panic("biodone: page busy < 0\n");
2862 			}
2863 			vm_page_io_finish(m);
2864 			vm_object_pip_subtract(obj, 1);
2865 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2866 			iosize -= resid;
2867 		}
2868 		if (obj)
2869 			vm_object_pip_wakeupn(obj, 0);
2870 		mtx_unlock(&vm_mtx);
2871 	}
2872 
2873 	/*
2874 	 * For asynchronous completions, release the buffer now. The brelse
2875 	 * will do a wakeup there if necessary - so no need to do a wakeup
2876 	 * here in the async case. The sync case always needs to do a wakeup.
2877 	 */
2878 
2879 	if (bp->b_flags & B_ASYNC) {
2880 		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
2881 			brelse(bp);
2882 		else
2883 			bqrelse(bp);
2884 	} else {
2885 		wakeup(bp);
2886 	}
2887 	splx(s);
2888 }
2889 
2890 /*
2891  * This routine is called in lieu of iodone in the case of
2892  * incomplete I/O.  This keeps the busy status for pages
2893  * consistant.
2894  *
2895  * vm_mtx should not be held
2896  */
2897 void
2898 vfs_unbusy_pages(struct buf * bp)
2899 {
2900 	int i;
2901 
2902 	mtx_assert(&vm_mtx, MA_NOTOWNED);
2903 	runningbufwakeup(bp);
2904 	if (bp->b_flags & B_VMIO) {
2905 		struct vnode *vp = bp->b_vp;
2906 		vm_object_t obj;
2907 
2908 		VOP_GETVOBJECT(vp, &obj);
2909 
2910 		mtx_lock(&vm_mtx);
2911 		for (i = 0; i < bp->b_npages; i++) {
2912 			vm_page_t m = bp->b_pages[i];
2913 
2914 			if (m == bogus_page) {
2915 				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2916 				if (!m) {
2917 					panic("vfs_unbusy_pages: page missing\n");
2918 				}
2919 				bp->b_pages[i] = m;
2920 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2921 			}
2922 			vm_object_pip_subtract(obj, 1);
2923 			vm_page_flag_clear(m, PG_ZERO);
2924 			vm_page_io_finish(m);
2925 		}
2926 		vm_object_pip_wakeupn(obj, 0);
2927 		mtx_unlock(&vm_mtx);
2928 	}
2929 }
2930 
2931 /*
2932  * vfs_page_set_valid:
2933  *
2934  *	Set the valid bits in a page based on the supplied offset.   The
2935  *	range is restricted to the buffer's size.
2936  *
2937  *	This routine is typically called after a read completes.
2938  *
2939  *	vm_mtx should be held
2940  */
2941 static void
2942 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2943 {
2944 	vm_ooffset_t soff, eoff;
2945 
2946 	mtx_assert(&vm_mtx, MA_OWNED);
2947 	/*
2948 	 * Start and end offsets in buffer.  eoff - soff may not cross a
2949 	 * page boundry or cross the end of the buffer.  The end of the
2950 	 * buffer, in this case, is our file EOF, not the allocation size
2951 	 * of the buffer.
2952 	 */
2953 	soff = off;
2954 	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2955 	if (eoff > bp->b_offset + bp->b_bcount)
2956 		eoff = bp->b_offset + bp->b_bcount;
2957 
2958 	/*
2959 	 * Set valid range.  This is typically the entire buffer and thus the
2960 	 * entire page.
2961 	 */
2962 	if (eoff > soff) {
2963 		vm_page_set_validclean(
2964 		    m,
2965 		   (vm_offset_t) (soff & PAGE_MASK),
2966 		   (vm_offset_t) (eoff - soff)
2967 		);
2968 	}
2969 }
2970 
2971 /*
2972  * This routine is called before a device strategy routine.
2973  * It is used to tell the VM system that paging I/O is in
2974  * progress, and treat the pages associated with the buffer
2975  * almost as being PG_BUSY.  Also the object paging_in_progress
2976  * flag is handled to make sure that the object doesn't become
2977  * inconsistant.
2978  *
2979  * Since I/O has not been initiated yet, certain buffer flags
2980  * such as BIO_ERROR or B_INVAL may be in an inconsistant state
2981  * and should be ignored.
2982  *
2983  * vm_mtx should not be held
2984  */
2985 void
2986 vfs_busy_pages(struct buf * bp, int clear_modify)
2987 {
2988 	int i, bogus;
2989 
2990 	mtx_assert(&vm_mtx, MA_NOTOWNED);
2991 	if (bp->b_flags & B_VMIO) {
2992 		struct vnode *vp = bp->b_vp;
2993 		vm_object_t obj;
2994 		vm_ooffset_t foff;
2995 
2996 		VOP_GETVOBJECT(vp, &obj);
2997 		foff = bp->b_offset;
2998 		KASSERT(bp->b_offset != NOOFFSET,
2999 		    ("vfs_busy_pages: no buffer offset"));
3000 		mtx_lock(&vm_mtx);
3001 		vfs_setdirty(bp);
3002 
3003 retry:
3004 		for (i = 0; i < bp->b_npages; i++) {
3005 			vm_page_t m = bp->b_pages[i];
3006 			if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3007 				goto retry;
3008 		}
3009 
3010 		bogus = 0;
3011 		for (i = 0; i < bp->b_npages; i++) {
3012 			vm_page_t m = bp->b_pages[i];
3013 
3014 			vm_page_flag_clear(m, PG_ZERO);
3015 			if ((bp->b_flags & B_CLUSTER) == 0) {
3016 				vm_object_pip_add(obj, 1);
3017 				vm_page_io_start(m);
3018 			}
3019 
3020 			/*
3021 			 * When readying a buffer for a read ( i.e
3022 			 * clear_modify == 0 ), it is important to do
3023 			 * bogus_page replacement for valid pages in
3024 			 * partially instantiated buffers.  Partially
3025 			 * instantiated buffers can, in turn, occur when
3026 			 * reconstituting a buffer from its VM backing store
3027 			 * base.  We only have to do this if B_CACHE is
3028 			 * clear ( which causes the I/O to occur in the
3029 			 * first place ).  The replacement prevents the read
3030 			 * I/O from overwriting potentially dirty VM-backed
3031 			 * pages.  XXX bogus page replacement is, uh, bogus.
3032 			 * It may not work properly with small-block devices.
3033 			 * We need to find a better way.
3034 			 */
3035 
3036 			vm_page_protect(m, VM_PROT_NONE);
3037 			if (clear_modify)
3038 				vfs_page_set_valid(bp, foff, i, m);
3039 			else if (m->valid == VM_PAGE_BITS_ALL &&
3040 				(bp->b_flags & B_CACHE) == 0) {
3041 				bp->b_pages[i] = bogus_page;
3042 				bogus++;
3043 			}
3044 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3045 		}
3046 		if (bogus)
3047 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3048 		mtx_unlock(&vm_mtx);
3049 	}
3050 }
3051 
3052 /*
3053  * Tell the VM system that the pages associated with this buffer
3054  * are clean.  This is used for delayed writes where the data is
3055  * going to go to disk eventually without additional VM intevention.
3056  *
3057  * Note that while we only really need to clean through to b_bcount, we
3058  * just go ahead and clean through to b_bufsize.
3059  *
3060  * should be called with vm_mtx held
3061  */
3062 static void
3063 vfs_clean_pages(struct buf * bp)
3064 {
3065 	int i;
3066 
3067 	mtx_assert(&vm_mtx, MA_OWNED);
3068 	if (bp->b_flags & B_VMIO) {
3069 		vm_ooffset_t foff;
3070 
3071 		foff = bp->b_offset;
3072 		KASSERT(bp->b_offset != NOOFFSET,
3073 		    ("vfs_clean_pages: no buffer offset"));
3074 		for (i = 0; i < bp->b_npages; i++) {
3075 			vm_page_t m = bp->b_pages[i];
3076 			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3077 			vm_ooffset_t eoff = noff;
3078 
3079 			if (eoff > bp->b_offset + bp->b_bufsize)
3080 				eoff = bp->b_offset + bp->b_bufsize;
3081 			vfs_page_set_valid(bp, foff, i, m);
3082 			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3083 			foff = noff;
3084 		}
3085 	}
3086 }
3087 
3088 /*
3089  *	vfs_bio_set_validclean:
3090  *
3091  *	Set the range within the buffer to valid and clean.  The range is
3092  *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3093  *	itself may be offset from the beginning of the first page.
3094  *
3095  */
3096 
3097 void
3098 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3099 {
3100 	if (bp->b_flags & B_VMIO) {
3101 		int i;
3102 		int n;
3103 
3104 		/*
3105 		 * Fixup base to be relative to beginning of first page.
3106 		 * Set initial n to be the maximum number of bytes in the
3107 		 * first page that can be validated.
3108 		 */
3109 
3110 		base += (bp->b_offset & PAGE_MASK);
3111 		n = PAGE_SIZE - (base & PAGE_MASK);
3112 
3113 		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3114 			vm_page_t m = bp->b_pages[i];
3115 
3116 			if (n > size)
3117 				n = size;
3118 
3119 			vm_page_set_validclean(m, base & PAGE_MASK, n);
3120 			base += n;
3121 			size -= n;
3122 			n = PAGE_SIZE;
3123 		}
3124 	}
3125 }
3126 
3127 /*
3128  *	vfs_bio_clrbuf:
3129  *
3130  *	clear a buffer.  This routine essentially fakes an I/O, so we need
3131  *	to clear BIO_ERROR and B_INVAL.
3132  *
3133  *	Note that while we only theoretically need to clear through b_bcount,
3134  *	we go ahead and clear through b_bufsize.
3135  *
3136  *	We'll get vm_mtx here for safety if processing a VMIO buffer.
3137  *	I don't think vm_mtx is needed, but we're twiddling vm_page flags.
3138  */
3139 
3140 void
3141 vfs_bio_clrbuf(struct buf *bp) {
3142 	int i, mask = 0;
3143 	caddr_t sa, ea;
3144 
3145 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3146 		mtx_lock(&vm_mtx);
3147 		bp->b_flags &= ~B_INVAL;
3148 		bp->b_ioflags &= ~BIO_ERROR;
3149 		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3150 		    (bp->b_offset & PAGE_MASK) == 0) {
3151 			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3152 			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3153 			    ((bp->b_pages[0]->valid & mask) != mask)) {
3154 				bzero(bp->b_data, bp->b_bufsize);
3155 			}
3156 			bp->b_pages[0]->valid |= mask;
3157 			bp->b_resid = 0;
3158 			mtx_unlock(&vm_mtx);
3159 			return;
3160 		}
3161 		ea = sa = bp->b_data;
3162 		for(i=0;i<bp->b_npages;i++,sa=ea) {
3163 			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3164 			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3165 			ea = (caddr_t)(vm_offset_t)ulmin(
3166 			    (u_long)(vm_offset_t)ea,
3167 			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3168 			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3169 			if ((bp->b_pages[i]->valid & mask) == mask)
3170 				continue;
3171 			if ((bp->b_pages[i]->valid & mask) == 0) {
3172 				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3173 					bzero(sa, ea - sa);
3174 				}
3175 			} else {
3176 				for (; sa < ea; sa += DEV_BSIZE, j++) {
3177 					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3178 						(bp->b_pages[i]->valid & (1<<j)) == 0)
3179 						bzero(sa, DEV_BSIZE);
3180 				}
3181 			}
3182 			bp->b_pages[i]->valid |= mask;
3183 			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3184 		}
3185 		bp->b_resid = 0;
3186 		mtx_unlock(&vm_mtx);
3187 	} else {
3188 		clrbuf(bp);
3189 	}
3190 }
3191 
3192 /*
3193  * vm_hold_load_pages and vm_hold_free_pages get pages into
3194  * a buffers address space.  The pages are anonymous and are
3195  * not associated with a file object.
3196  *
3197  * vm_mtx should not be held
3198  */
3199 static void
3200 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3201 {
3202 	vm_offset_t pg;
3203 	vm_page_t p;
3204 	int index;
3205 
3206 	mtx_assert(&vm_mtx, MA_NOTOWNED);
3207 	to = round_page(to);
3208 	from = round_page(from);
3209 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3210 
3211 	mtx_lock(&vm_mtx);
3212 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3213 
3214 tryagain:
3215 
3216 		/*
3217 		 * note: must allocate system pages since blocking here
3218 		 * could intefere with paging I/O, no matter which
3219 		 * process we are.
3220 		 */
3221 		p = vm_page_alloc(kernel_object,
3222 			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3223 		    VM_ALLOC_SYSTEM);
3224 		if (!p) {
3225 			vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3226 			VM_WAIT;
3227 			goto tryagain;
3228 		}
3229 		vm_page_wire(p);
3230 		p->valid = VM_PAGE_BITS_ALL;
3231 		vm_page_flag_clear(p, PG_ZERO);
3232 		pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3233 		bp->b_pages[index] = p;
3234 		vm_page_wakeup(p);
3235 	}
3236 	bp->b_npages = index;
3237 	mtx_unlock(&vm_mtx);
3238 }
3239 
3240 void
3241 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3242 {
3243 	vm_offset_t pg;
3244 	vm_page_t p;
3245 	int index, newnpages;
3246 
3247 	mtx_assert(&vm_mtx, MA_NOTOWNED);
3248 	from = round_page(from);
3249 	to = round_page(to);
3250 	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3251 
3252 	mtx_lock(&vm_mtx);
3253 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3254 		p = bp->b_pages[index];
3255 		if (p && (index < bp->b_npages)) {
3256 			if (p->busy) {
3257 				printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3258 					bp->b_blkno, bp->b_lblkno);
3259 			}
3260 			bp->b_pages[index] = NULL;
3261 			pmap_kremove(pg);
3262 			vm_page_busy(p);
3263 			vm_page_unwire(p, 0);
3264 			vm_page_free(p);
3265 		}
3266 	}
3267 	bp->b_npages = newnpages;
3268 	mtx_unlock(&vm_mtx);
3269 }
3270 
3271 
3272 #include "opt_ddb.h"
3273 #ifdef DDB
3274 #include <ddb/ddb.h>
3275 
3276 DB_SHOW_COMMAND(buffer, db_show_buffer)
3277 {
3278 	/* get args */
3279 	struct buf *bp = (struct buf *)addr;
3280 
3281 	if (!have_addr) {
3282 		db_printf("usage: show buffer <addr>\n");
3283 		return;
3284 	}
3285 
3286 	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3287 	db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3288 		  "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3289 		  "b_blkno = %d, b_pblkno = %d\n",
3290 		  bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3291 		  major(bp->b_dev), minor(bp->b_dev),
3292 		  bp->b_data, bp->b_blkno, bp->b_pblkno);
3293 	if (bp->b_npages) {
3294 		int i;
3295 		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3296 		for (i = 0; i < bp->b_npages; i++) {
3297 			vm_page_t m;
3298 			m = bp->b_pages[i];
3299 			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3300 			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3301 			if ((i + 1) < bp->b_npages)
3302 				db_printf(",");
3303 		}
3304 		db_printf("\n");
3305 	}
3306 }
3307 #endif /* DDB */
3308