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