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