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