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