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