xref: /freebsd/sys/kern/vfs_bio.c (revision 81d1ffee089aab2652954909acbe6aadd8a1a72c)
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, 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, 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     int flags)
2372 {
2373 	struct buf *bp;
2374 	int s;
2375 	int error;
2376 	ASSERT_VOP_LOCKED(vp, "getblk");
2377 
2378 	if (size > MAXBSIZE)
2379 		panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2380 
2381 	s = splbio();
2382 loop:
2383 	/*
2384 	 * Block if we are low on buffers.   Certain processes are allowed
2385 	 * to completely exhaust the buffer cache.
2386          *
2387          * If this check ever becomes a bottleneck it may be better to
2388          * move it into the else, when gbincore() fails.  At the moment
2389          * it isn't a problem.
2390 	 *
2391 	 * XXX remove if 0 sections (clean this up after its proven)
2392          */
2393 	if (numfreebuffers == 0) {
2394 		if (curthread == PCPU_GET(idlethread))
2395 			return NULL;
2396 		mtx_lock(&nblock);
2397 		needsbuffer |= VFS_BIO_NEED_ANY;
2398 		mtx_unlock(&nblock);
2399 	}
2400 
2401 	VI_LOCK(vp);
2402 	if ((bp = gbincore(vp, blkno))) {
2403 		int lockflags;
2404 		/*
2405 		 * Buffer is in-core.  If the buffer is not busy, it must
2406 		 * be on a queue.
2407 		 */
2408 		lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
2409 
2410 		if (flags & GB_LOCK_NOWAIT)
2411 			lockflags |= LK_NOWAIT;
2412 
2413 		error = BUF_TIMELOCK(bp, lockflags,
2414 		    VI_MTX(vp), "getblk", slpflag, slptimeo);
2415 
2416 		/*
2417 		 * If we slept and got the lock we have to restart in case
2418 		 * the buffer changed identities.
2419 		 */
2420 		if (error == ENOLCK)
2421 			goto loop;
2422 		/* We timed out or were interrupted. */
2423 		else if (error)
2424 			return (NULL);
2425 
2426 		/*
2427 		 * The buffer is locked.  B_CACHE is cleared if the buffer is
2428 		 * invalid.  Otherwise, for a non-VMIO buffer, B_CACHE is set
2429 		 * and for a VMIO buffer B_CACHE is adjusted according to the
2430 		 * backing VM cache.
2431 		 */
2432 		if (bp->b_flags & B_INVAL)
2433 			bp->b_flags &= ~B_CACHE;
2434 		else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2435 			bp->b_flags |= B_CACHE;
2436 		bremfree(bp);
2437 
2438 		/*
2439 		 * check for size inconsistancies for non-VMIO case.
2440 		 */
2441 
2442 		if (bp->b_bcount != size) {
2443 			if ((bp->b_flags & B_VMIO) == 0 ||
2444 			    (size > bp->b_kvasize)) {
2445 				if (bp->b_flags & B_DELWRI) {
2446 					bp->b_flags |= B_NOCACHE;
2447 					BUF_WRITE(bp);
2448 				} else {
2449 					if ((bp->b_flags & B_VMIO) &&
2450 					   (LIST_FIRST(&bp->b_dep) == NULL)) {
2451 						bp->b_flags |= B_RELBUF;
2452 						brelse(bp);
2453 					} else {
2454 						bp->b_flags |= B_NOCACHE;
2455 						BUF_WRITE(bp);
2456 					}
2457 				}
2458 				goto loop;
2459 			}
2460 		}
2461 
2462 		/*
2463 		 * If the size is inconsistant in the VMIO case, we can resize
2464 		 * the buffer.  This might lead to B_CACHE getting set or
2465 		 * cleared.  If the size has not changed, B_CACHE remains
2466 		 * unchanged from its previous state.
2467 		 */
2468 
2469 		if (bp->b_bcount != size)
2470 			allocbuf(bp, size);
2471 
2472 		KASSERT(bp->b_offset != NOOFFSET,
2473 		    ("getblk: no buffer offset"));
2474 
2475 		/*
2476 		 * A buffer with B_DELWRI set and B_CACHE clear must
2477 		 * be committed before we can return the buffer in
2478 		 * order to prevent the caller from issuing a read
2479 		 * ( due to B_CACHE not being set ) and overwriting
2480 		 * it.
2481 		 *
2482 		 * Most callers, including NFS and FFS, need this to
2483 		 * operate properly either because they assume they
2484 		 * can issue a read if B_CACHE is not set, or because
2485 		 * ( for example ) an uncached B_DELWRI might loop due
2486 		 * to softupdates re-dirtying the buffer.  In the latter
2487 		 * case, B_CACHE is set after the first write completes,
2488 		 * preventing further loops.
2489 		 * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2490 		 * above while extending the buffer, we cannot allow the
2491 		 * buffer to remain with B_CACHE set after the write
2492 		 * completes or it will represent a corrupt state.  To
2493 		 * deal with this we set B_NOCACHE to scrap the buffer
2494 		 * after the write.
2495 		 *
2496 		 * We might be able to do something fancy, like setting
2497 		 * B_CACHE in bwrite() except if B_DELWRI is already set,
2498 		 * so the below call doesn't set B_CACHE, but that gets real
2499 		 * confusing.  This is much easier.
2500 		 */
2501 
2502 		if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2503 			bp->b_flags |= B_NOCACHE;
2504 			BUF_WRITE(bp);
2505 			goto loop;
2506 		}
2507 
2508 		splx(s);
2509 		bp->b_flags &= ~B_DONE;
2510 	} else {
2511 		int bsize, maxsize, vmio;
2512 		off_t offset;
2513 
2514 		/*
2515 		 * Buffer is not in-core, create new buffer.  The buffer
2516 		 * returned by getnewbuf() is locked.  Note that the returned
2517 		 * buffer is also considered valid (not marked B_INVAL).
2518 		 */
2519 		VI_UNLOCK(vp);
2520 		if (vn_isdisk(vp, NULL))
2521 			bsize = DEV_BSIZE;
2522 		else if (vp->v_mountedhere)
2523 			bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2524 		else if (vp->v_mount)
2525 			bsize = vp->v_mount->mnt_stat.f_iosize;
2526 		else
2527 			bsize = size;
2528 
2529 		offset = blkno * bsize;
2530 		vmio = (VOP_GETVOBJECT(vp, NULL) == 0) &&
2531 		    (vp->v_vflag & VV_OBJBUF);
2532 		maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2533 		maxsize = imax(maxsize, bsize);
2534 
2535 		if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2536 			if (slpflag || slptimeo) {
2537 				splx(s);
2538 				return NULL;
2539 			}
2540 			goto loop;
2541 		}
2542 
2543 		/*
2544 		 * This code is used to make sure that a buffer is not
2545 		 * created while the getnewbuf routine is blocked.
2546 		 * This can be a problem whether the vnode is locked or not.
2547 		 * If the buffer is created out from under us, we have to
2548 		 * throw away the one we just created.  There is now window
2549 		 * race because we are safely running at splbio() from the
2550 		 * point of the duplicate buffer creation through to here,
2551 		 * and we've locked the buffer.
2552 		 *
2553 		 * Note: this must occur before we associate the buffer
2554 		 * with the vp especially considering limitations in
2555 		 * the splay tree implementation when dealing with duplicate
2556 		 * lblkno's.
2557 		 */
2558 		VI_LOCK(vp);
2559 		if (gbincore(vp, blkno)) {
2560 			VI_UNLOCK(vp);
2561 			bp->b_flags |= B_INVAL;
2562 			brelse(bp);
2563 			goto loop;
2564 		}
2565 
2566 		/*
2567 		 * Insert the buffer into the hash, so that it can
2568 		 * be found by incore.
2569 		 */
2570 		bp->b_blkno = bp->b_lblkno = blkno;
2571 		bp->b_offset = offset;
2572 
2573 		bgetvp(vp, bp);
2574 		VI_UNLOCK(vp);
2575 
2576 		/*
2577 		 * set B_VMIO bit.  allocbuf() the buffer bigger.  Since the
2578 		 * buffer size starts out as 0, B_CACHE will be set by
2579 		 * allocbuf() for the VMIO case prior to it testing the
2580 		 * backing store for validity.
2581 		 */
2582 
2583 		if (vmio) {
2584 			bp->b_flags |= B_VMIO;
2585 #if defined(VFS_BIO_DEBUG)
2586 			if (vp->v_type != VREG)
2587 				printf("getblk: vmioing file type %d???\n", vp->v_type);
2588 #endif
2589 			VOP_GETVOBJECT(vp, &bp->b_object);
2590 		} else {
2591 			bp->b_flags &= ~B_VMIO;
2592 			bp->b_object = NULL;
2593 		}
2594 
2595 		allocbuf(bp, size);
2596 
2597 		splx(s);
2598 		bp->b_flags &= ~B_DONE;
2599 	}
2600 	KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp));
2601 	return (bp);
2602 }
2603 
2604 /*
2605  * Get an empty, disassociated buffer of given size.  The buffer is initially
2606  * set to B_INVAL.
2607  */
2608 struct buf *
2609 geteblk(int size)
2610 {
2611 	struct buf *bp;
2612 	int s;
2613 	int maxsize;
2614 
2615 	maxsize = (size + BKVAMASK) & ~BKVAMASK;
2616 
2617 	s = splbio();
2618 	while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2619 		continue;
2620 	splx(s);
2621 	allocbuf(bp, size);
2622 	bp->b_flags |= B_INVAL;	/* b_dep cleared by getnewbuf() */
2623 	KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp));
2624 	return (bp);
2625 }
2626 
2627 
2628 /*
2629  * This code constitutes the buffer memory from either anonymous system
2630  * memory (in the case of non-VMIO operations) or from an associated
2631  * VM object (in the case of VMIO operations).  This code is able to
2632  * resize a buffer up or down.
2633  *
2634  * Note that this code is tricky, and has many complications to resolve
2635  * deadlock or inconsistant data situations.  Tread lightly!!!
2636  * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2637  * the caller.  Calling this code willy nilly can result in the loss of data.
2638  *
2639  * allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2640  * B_CACHE for the non-VMIO case.
2641  */
2642 
2643 int
2644 allocbuf(struct buf *bp, int size)
2645 {
2646 	int newbsize, mbsize;
2647 	int i;
2648 
2649 	GIANT_REQUIRED;
2650 
2651 	if (BUF_REFCNT(bp) == 0)
2652 		panic("allocbuf: buffer not busy");
2653 
2654 	if (bp->b_kvasize < size)
2655 		panic("allocbuf: buffer too small");
2656 
2657 	if ((bp->b_flags & B_VMIO) == 0) {
2658 		caddr_t origbuf;
2659 		int origbufsize;
2660 		/*
2661 		 * Just get anonymous memory from the kernel.  Don't
2662 		 * mess with B_CACHE.
2663 		 */
2664 		mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2665 		if (bp->b_flags & B_MALLOC)
2666 			newbsize = mbsize;
2667 		else
2668 			newbsize = round_page(size);
2669 
2670 		if (newbsize < bp->b_bufsize) {
2671 			/*
2672 			 * malloced buffers are not shrunk
2673 			 */
2674 			if (bp->b_flags & B_MALLOC) {
2675 				if (newbsize) {
2676 					bp->b_bcount = size;
2677 				} else {
2678 					free(bp->b_data, M_BIOBUF);
2679 					if (bp->b_bufsize) {
2680 						atomic_subtract_int(
2681 						    &bufmallocspace,
2682 						    bp->b_bufsize);
2683 						bufspacewakeup();
2684 						bp->b_bufsize = 0;
2685 					}
2686 					bp->b_data = bp->b_kvabase;
2687 					bp->b_bcount = 0;
2688 					bp->b_flags &= ~B_MALLOC;
2689 				}
2690 				return 1;
2691 			}
2692 			vm_hold_free_pages(
2693 			    bp,
2694 			    (vm_offset_t) bp->b_data + newbsize,
2695 			    (vm_offset_t) bp->b_data + bp->b_bufsize);
2696 		} else if (newbsize > bp->b_bufsize) {
2697 			/*
2698 			 * We only use malloced memory on the first allocation.
2699 			 * and revert to page-allocated memory when the buffer
2700 			 * grows.
2701 			 */
2702 			/*
2703 			 * There is a potential smp race here that could lead
2704 			 * to bufmallocspace slightly passing the max.  It
2705 			 * is probably extremely rare and not worth worrying
2706 			 * over.
2707 			 */
2708 			if ( (bufmallocspace < maxbufmallocspace) &&
2709 				(bp->b_bufsize == 0) &&
2710 				(mbsize <= PAGE_SIZE/2)) {
2711 
2712 				bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2713 				bp->b_bufsize = mbsize;
2714 				bp->b_bcount = size;
2715 				bp->b_flags |= B_MALLOC;
2716 				atomic_add_int(&bufmallocspace, mbsize);
2717 				return 1;
2718 			}
2719 			origbuf = NULL;
2720 			origbufsize = 0;
2721 			/*
2722 			 * If the buffer is growing on its other-than-first allocation,
2723 			 * then we revert to the page-allocation scheme.
2724 			 */
2725 			if (bp->b_flags & B_MALLOC) {
2726 				origbuf = bp->b_data;
2727 				origbufsize = bp->b_bufsize;
2728 				bp->b_data = bp->b_kvabase;
2729 				if (bp->b_bufsize) {
2730 					atomic_subtract_int(&bufmallocspace,
2731 					    bp->b_bufsize);
2732 					bufspacewakeup();
2733 					bp->b_bufsize = 0;
2734 				}
2735 				bp->b_flags &= ~B_MALLOC;
2736 				newbsize = round_page(newbsize);
2737 			}
2738 			vm_hold_load_pages(
2739 			    bp,
2740 			    (vm_offset_t) bp->b_data + bp->b_bufsize,
2741 			    (vm_offset_t) bp->b_data + newbsize);
2742 			if (origbuf) {
2743 				bcopy(origbuf, bp->b_data, origbufsize);
2744 				free(origbuf, M_BIOBUF);
2745 			}
2746 		}
2747 	} else {
2748 		int desiredpages;
2749 
2750 		newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2751 		desiredpages = (size == 0) ? 0 :
2752 			num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2753 
2754 		if (bp->b_flags & B_MALLOC)
2755 			panic("allocbuf: VMIO buffer can't be malloced");
2756 		/*
2757 		 * Set B_CACHE initially if buffer is 0 length or will become
2758 		 * 0-length.
2759 		 */
2760 		if (size == 0 || bp->b_bufsize == 0)
2761 			bp->b_flags |= B_CACHE;
2762 
2763 		if (newbsize < bp->b_bufsize) {
2764 			/*
2765 			 * DEV_BSIZE aligned new buffer size is less then the
2766 			 * DEV_BSIZE aligned existing buffer size.  Figure out
2767 			 * if we have to remove any pages.
2768 			 */
2769 			if (desiredpages < bp->b_npages) {
2770 				vm_page_t m;
2771 
2772 				vm_page_lock_queues();
2773 				for (i = desiredpages; i < bp->b_npages; i++) {
2774 					/*
2775 					 * the page is not freed here -- it
2776 					 * is the responsibility of
2777 					 * vnode_pager_setsize
2778 					 */
2779 					m = bp->b_pages[i];
2780 					KASSERT(m != bogus_page,
2781 					    ("allocbuf: bogus page found"));
2782 					while (vm_page_sleep_if_busy(m, TRUE, "biodep"))
2783 						vm_page_lock_queues();
2784 
2785 					bp->b_pages[i] = NULL;
2786 					vm_page_unwire(m, 0);
2787 				}
2788 				vm_page_unlock_queues();
2789 				pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2790 				    (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2791 				bp->b_npages = desiredpages;
2792 			}
2793 		} else if (size > bp->b_bcount) {
2794 			/*
2795 			 * We are growing the buffer, possibly in a
2796 			 * byte-granular fashion.
2797 			 */
2798 			struct vnode *vp;
2799 			vm_object_t obj;
2800 			vm_offset_t toff;
2801 			vm_offset_t tinc;
2802 
2803 			/*
2804 			 * Step 1, bring in the VM pages from the object,
2805 			 * allocating them if necessary.  We must clear
2806 			 * B_CACHE if these pages are not valid for the
2807 			 * range covered by the buffer.
2808 			 */
2809 
2810 			vp = bp->b_vp;
2811 			obj = bp->b_object;
2812 
2813 			while (bp->b_npages < desiredpages) {
2814 				vm_page_t m;
2815 				vm_pindex_t pi;
2816 
2817 				pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2818 				if ((m = vm_page_lookup(obj, pi)) == NULL) {
2819 					/*
2820 					 * note: must allocate system pages
2821 					 * since blocking here could intefere
2822 					 * with paging I/O, no matter which
2823 					 * process we are.
2824 					 */
2825 					m = vm_page_alloc(obj, pi,
2826 					    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
2827 					if (m == NULL) {
2828 						atomic_add_int(&vm_pageout_deficit,
2829 						    desiredpages - bp->b_npages);
2830 						VM_WAIT;
2831 					} else {
2832 						vm_page_lock_queues();
2833 						vm_page_wakeup(m);
2834 						vm_page_unlock_queues();
2835 						bp->b_flags &= ~B_CACHE;
2836 						bp->b_pages[bp->b_npages] = m;
2837 						++bp->b_npages;
2838 					}
2839 					continue;
2840 				}
2841 
2842 				/*
2843 				 * We found a page.  If we have to sleep on it,
2844 				 * retry because it might have gotten freed out
2845 				 * from under us.
2846 				 *
2847 				 * We can only test PG_BUSY here.  Blocking on
2848 				 * m->busy might lead to a deadlock:
2849 				 *
2850 				 *  vm_fault->getpages->cluster_read->allocbuf
2851 				 *
2852 				 */
2853 				vm_page_lock_queues();
2854 				if (vm_page_sleep_if_busy(m, FALSE, "pgtblk"))
2855 					continue;
2856 
2857 				/*
2858 				 * We have a good page.  Should we wakeup the
2859 				 * page daemon?
2860 				 */
2861 				if ((curproc != pageproc) &&
2862 				    ((m->queue - m->pc) == PQ_CACHE) &&
2863 				    ((cnt.v_free_count + cnt.v_cache_count) <
2864 					(cnt.v_free_min + cnt.v_cache_min))) {
2865 					pagedaemon_wakeup();
2866 				}
2867 				vm_page_flag_clear(m, PG_ZERO);
2868 				vm_page_wire(m);
2869 				vm_page_unlock_queues();
2870 				bp->b_pages[bp->b_npages] = m;
2871 				++bp->b_npages;
2872 			}
2873 
2874 			/*
2875 			 * Step 2.  We've loaded the pages into the buffer,
2876 			 * we have to figure out if we can still have B_CACHE
2877 			 * set.  Note that B_CACHE is set according to the
2878 			 * byte-granular range ( bcount and size ), new the
2879 			 * aligned range ( newbsize ).
2880 			 *
2881 			 * The VM test is against m->valid, which is DEV_BSIZE
2882 			 * aligned.  Needless to say, the validity of the data
2883 			 * needs to also be DEV_BSIZE aligned.  Note that this
2884 			 * fails with NFS if the server or some other client
2885 			 * extends the file's EOF.  If our buffer is resized,
2886 			 * B_CACHE may remain set! XXX
2887 			 */
2888 
2889 			toff = bp->b_bcount;
2890 			tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2891 
2892 			while ((bp->b_flags & B_CACHE) && toff < size) {
2893 				vm_pindex_t pi;
2894 
2895 				if (tinc > (size - toff))
2896 					tinc = size - toff;
2897 
2898 				pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2899 				    PAGE_SHIFT;
2900 
2901 				vfs_buf_test_cache(
2902 				    bp,
2903 				    bp->b_offset,
2904 				    toff,
2905 				    tinc,
2906 				    bp->b_pages[pi]
2907 				);
2908 				toff += tinc;
2909 				tinc = PAGE_SIZE;
2910 			}
2911 
2912 			/*
2913 			 * Step 3, fixup the KVM pmap.  Remember that
2914 			 * bp->b_data is relative to bp->b_offset, but
2915 			 * bp->b_offset may be offset into the first page.
2916 			 */
2917 
2918 			bp->b_data = (caddr_t)
2919 			    trunc_page((vm_offset_t)bp->b_data);
2920 			pmap_qenter(
2921 			    (vm_offset_t)bp->b_data,
2922 			    bp->b_pages,
2923 			    bp->b_npages
2924 			);
2925 
2926 			bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2927 			    (vm_offset_t)(bp->b_offset & PAGE_MASK));
2928 		}
2929 	}
2930 	if (newbsize < bp->b_bufsize)
2931 		bufspacewakeup();
2932 	bp->b_bufsize = newbsize;	/* actual buffer allocation	*/
2933 	bp->b_bcount = size;		/* requested buffer size	*/
2934 	return 1;
2935 }
2936 
2937 void
2938 biodone(struct bio *bp)
2939 {
2940 	bp->bio_flags |= BIO_DONE;
2941 	if (bp->bio_done != NULL)
2942 		bp->bio_done(bp);
2943 	else
2944 		wakeup(bp);
2945 }
2946 
2947 /*
2948  * Wait for a BIO to finish.
2949  *
2950  * XXX: resort to a timeout for now.  The optimal locking (if any) for this
2951  * case is not yet clear.
2952  */
2953 int
2954 biowait(struct bio *bp, const char *wchan)
2955 {
2956 
2957 	while ((bp->bio_flags & BIO_DONE) == 0)
2958 		msleep(bp, NULL, PRIBIO, wchan, hz / 10);
2959 	if (bp->bio_error != 0)
2960 		return (bp->bio_error);
2961 	if (!(bp->bio_flags & BIO_ERROR))
2962 		return (0);
2963 	return (EIO);
2964 }
2965 
2966 void
2967 biofinish(struct bio *bp, struct devstat *stat, int error)
2968 {
2969 
2970 	if (error) {
2971 		bp->bio_error = error;
2972 		bp->bio_flags |= BIO_ERROR;
2973 	}
2974 	if (stat != NULL)
2975 		devstat_end_transaction_bio(stat, bp);
2976 	biodone(bp);
2977 }
2978 
2979 void
2980 bioq_init(struct bio_queue_head *head)
2981 {
2982 	TAILQ_INIT(&head->queue);
2983 	head->last_pblkno = 0;
2984 	head->insert_point = NULL;
2985 	head->switch_point = NULL;
2986 }
2987 
2988 void
2989 bioq_remove(struct bio_queue_head *head, struct bio *bp)
2990 {
2991 	if (bp == head->switch_point)
2992 		head->switch_point = TAILQ_NEXT(bp, bio_queue);
2993 	if (bp == head->insert_point) {
2994 		head->insert_point = TAILQ_PREV(bp, bio_queue, bio_queue);
2995 		if (head->insert_point == NULL)
2996 			head->last_pblkno = 0;
2997 	} else if (bp == TAILQ_FIRST(&head->queue))
2998 		head->last_pblkno = bp->bio_pblkno;
2999 	TAILQ_REMOVE(&head->queue, bp, bio_queue);
3000 	if (TAILQ_FIRST(&head->queue) == head->switch_point)
3001 		head->switch_point = NULL;
3002 }
3003 
3004 /*
3005  *	bufwait:
3006  *
3007  *	Wait for buffer I/O completion, returning error status.  The buffer
3008  *	is left locked and B_DONE on return.  B_EINTR is converted into an EINTR
3009  *	error and cleared.
3010  */
3011 int
3012 bufwait(register struct buf * bp)
3013 {
3014 	int s;
3015 
3016 	s = splbio();
3017 	while ((bp->b_flags & B_DONE) == 0) {
3018 		if (bp->b_iocmd == BIO_READ)
3019 			tsleep(bp, PRIBIO, "biord", 0);
3020 		else
3021 			tsleep(bp, PRIBIO, "biowr", 0);
3022 	}
3023 	splx(s);
3024 	if (bp->b_flags & B_EINTR) {
3025 		bp->b_flags &= ~B_EINTR;
3026 		return (EINTR);
3027 	}
3028 	if (bp->b_ioflags & BIO_ERROR) {
3029 		return (bp->b_error ? bp->b_error : EIO);
3030 	} else {
3031 		return (0);
3032 	}
3033 }
3034 
3035  /*
3036   * Call back function from struct bio back up to struct buf.
3037   * The corresponding initialization lives in sys/conf.h:DEV_STRATEGY().
3038   */
3039 void
3040 bufdonebio(struct bio *bp)
3041 {
3042 	bufdone(bp->bio_caller2);
3043 }
3044 
3045 /*
3046  *	bufdone:
3047  *
3048  *	Finish I/O on a buffer, optionally calling a completion function.
3049  *	This is usually called from an interrupt so process blocking is
3050  *	not allowed.
3051  *
3052  *	biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3053  *	In a non-VMIO bp, B_CACHE will be set on the next getblk()
3054  *	assuming B_INVAL is clear.
3055  *
3056  *	For the VMIO case, we set B_CACHE if the op was a read and no
3057  *	read error occured, or if the op was a write.  B_CACHE is never
3058  *	set if the buffer is invalid or otherwise uncacheable.
3059  *
3060  *	biodone does not mess with B_INVAL, allowing the I/O routine or the
3061  *	initiator to leave B_INVAL set to brelse the buffer out of existance
3062  *	in the biodone routine.
3063  */
3064 void
3065 bufdone(struct buf *bp)
3066 {
3067 	int s;
3068 	void    (*biodone)(struct buf *);
3069 
3070 	GIANT_REQUIRED;
3071 
3072 	s = splbio();
3073 
3074 	KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
3075 	KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3076 
3077 	bp->b_flags |= B_DONE;
3078 	runningbufwakeup(bp);
3079 
3080 	if (bp->b_iocmd == BIO_DELETE) {
3081 		brelse(bp);
3082 		splx(s);
3083 		return;
3084 	}
3085 
3086 	if (bp->b_iocmd == BIO_WRITE) {
3087 		vwakeup(bp);
3088 	}
3089 
3090 	/* call optional completion function if requested */
3091 	if (bp->b_iodone != NULL) {
3092 		biodone = bp->b_iodone;
3093 		bp->b_iodone = NULL;
3094 		(*biodone) (bp);
3095 		splx(s);
3096 		return;
3097 	}
3098 	if (LIST_FIRST(&bp->b_dep) != NULL)
3099 		buf_complete(bp);
3100 
3101 	if (bp->b_flags & B_VMIO) {
3102 		int i;
3103 		vm_ooffset_t foff;
3104 		vm_page_t m;
3105 		vm_object_t obj;
3106 		int iosize;
3107 		struct vnode *vp = bp->b_vp;
3108 
3109 		obj = bp->b_object;
3110 
3111 #if defined(VFS_BIO_DEBUG)
3112 		mp_fixme("usecount and vflag accessed without locks.");
3113 		if (vp->v_usecount == 0) {
3114 			panic("biodone: zero vnode ref count");
3115 		}
3116 
3117 		if ((vp->v_vflag & VV_OBJBUF) == 0) {
3118 			panic("biodone: vnode is not setup for merged cache");
3119 		}
3120 #endif
3121 
3122 		foff = bp->b_offset;
3123 		KASSERT(bp->b_offset != NOOFFSET,
3124 		    ("biodone: no buffer offset"));
3125 
3126 #if defined(VFS_BIO_DEBUG)
3127 		if (obj->paging_in_progress < bp->b_npages) {
3128 			printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
3129 			    obj->paging_in_progress, bp->b_npages);
3130 		}
3131 #endif
3132 
3133 		/*
3134 		 * Set B_CACHE if the op was a normal read and no error
3135 		 * occured.  B_CACHE is set for writes in the b*write()
3136 		 * routines.
3137 		 */
3138 		iosize = bp->b_bcount - bp->b_resid;
3139 		if (bp->b_iocmd == BIO_READ &&
3140 		    !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3141 		    !(bp->b_ioflags & BIO_ERROR)) {
3142 			bp->b_flags |= B_CACHE;
3143 		}
3144 		vm_page_lock_queues();
3145 		for (i = 0; i < bp->b_npages; i++) {
3146 			int bogusflag = 0;
3147 			int resid;
3148 
3149 			resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3150 			if (resid > iosize)
3151 				resid = iosize;
3152 
3153 			/*
3154 			 * cleanup bogus pages, restoring the originals
3155 			 */
3156 			m = bp->b_pages[i];
3157 			if (m == bogus_page) {
3158 				bogusflag = 1;
3159 				m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3160 				if (m == NULL)
3161 					panic("biodone: page disappeared!");
3162 				bp->b_pages[i] = m;
3163 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3164 			}
3165 #if defined(VFS_BIO_DEBUG)
3166 			if (OFF_TO_IDX(foff) != m->pindex) {
3167 				printf(
3168 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n",
3169 				    (intmax_t)foff, (uintmax_t)m->pindex);
3170 			}
3171 #endif
3172 
3173 			/*
3174 			 * In the write case, the valid and clean bits are
3175 			 * already changed correctly ( see bdwrite() ), so we
3176 			 * only need to do this here in the read case.
3177 			 */
3178 			if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3179 				vfs_page_set_valid(bp, foff, i, m);
3180 			}
3181 			vm_page_flag_clear(m, PG_ZERO);
3182 
3183 			/*
3184 			 * when debugging new filesystems or buffer I/O methods, this
3185 			 * is the most common error that pops up.  if you see this, you
3186 			 * have not set the page busy flag correctly!!!
3187 			 */
3188 			if (m->busy == 0) {
3189 				printf("biodone: page busy < 0, "
3190 				    "pindex: %d, foff: 0x(%x,%x), "
3191 				    "resid: %d, index: %d\n",
3192 				    (int) m->pindex, (int)(foff >> 32),
3193 						(int) foff & 0xffffffff, resid, i);
3194 				if (!vn_isdisk(vp, NULL))
3195 					printf(" iosize: %ld, lblkno: %jd, flags: 0x%x, npages: %d\n",
3196 					    bp->b_vp->v_mount->mnt_stat.f_iosize,
3197 					    (intmax_t) bp->b_lblkno,
3198 					    bp->b_flags, bp->b_npages);
3199 				else
3200 					printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n",
3201 					    (intmax_t) bp->b_lblkno,
3202 					    bp->b_flags, bp->b_npages);
3203 				printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3204 				    m->valid, m->dirty, m->wire_count);
3205 				panic("biodone: page busy < 0\n");
3206 			}
3207 			vm_page_io_finish(m);
3208 			vm_object_pip_subtract(obj, 1);
3209 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3210 			iosize -= resid;
3211 		}
3212 		vm_page_unlock_queues();
3213 		if (obj)
3214 			vm_object_pip_wakeupn(obj, 0);
3215 	}
3216 
3217 	/*
3218 	 * For asynchronous completions, release the buffer now. The brelse
3219 	 * will do a wakeup there if necessary - so no need to do a wakeup
3220 	 * here in the async case. The sync case always needs to do a wakeup.
3221 	 */
3222 
3223 	if (bp->b_flags & B_ASYNC) {
3224 		if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3225 			brelse(bp);
3226 		else
3227 			bqrelse(bp);
3228 	} else {
3229 		wakeup(bp);
3230 	}
3231 	splx(s);
3232 }
3233 
3234 /*
3235  * This routine is called in lieu of iodone in the case of
3236  * incomplete I/O.  This keeps the busy status for pages
3237  * consistant.
3238  */
3239 void
3240 vfs_unbusy_pages(struct buf * bp)
3241 {
3242 	int i;
3243 
3244 	GIANT_REQUIRED;
3245 
3246 	runningbufwakeup(bp);
3247 	if (bp->b_flags & B_VMIO) {
3248 		vm_object_t obj;
3249 
3250 		obj = bp->b_object;
3251 		vm_page_lock_queues();
3252 		for (i = 0; i < bp->b_npages; i++) {
3253 			vm_page_t m = bp->b_pages[i];
3254 
3255 			if (m == bogus_page) {
3256 				m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3257 				if (!m) {
3258 					panic("vfs_unbusy_pages: page missing\n");
3259 				}
3260 				bp->b_pages[i] = m;
3261 				pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3262 			}
3263 			vm_object_pip_subtract(obj, 1);
3264 			vm_page_flag_clear(m, PG_ZERO);
3265 			vm_page_io_finish(m);
3266 		}
3267 		vm_page_unlock_queues();
3268 		vm_object_pip_wakeupn(obj, 0);
3269 	}
3270 }
3271 
3272 /*
3273  * vfs_page_set_valid:
3274  *
3275  *	Set the valid bits in a page based on the supplied offset.   The
3276  *	range is restricted to the buffer's size.
3277  *
3278  *	This routine is typically called after a read completes.
3279  */
3280 static void
3281 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3282 {
3283 	vm_ooffset_t soff, eoff;
3284 
3285 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3286 	/*
3287 	 * Start and end offsets in buffer.  eoff - soff may not cross a
3288 	 * page boundry or cross the end of the buffer.  The end of the
3289 	 * buffer, in this case, is our file EOF, not the allocation size
3290 	 * of the buffer.
3291 	 */
3292 	soff = off;
3293 	eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3294 	if (eoff > bp->b_offset + bp->b_bcount)
3295 		eoff = bp->b_offset + bp->b_bcount;
3296 
3297 	/*
3298 	 * Set valid range.  This is typically the entire buffer and thus the
3299 	 * entire page.
3300 	 */
3301 	if (eoff > soff) {
3302 		vm_page_set_validclean(
3303 		    m,
3304 		   (vm_offset_t) (soff & PAGE_MASK),
3305 		   (vm_offset_t) (eoff - soff)
3306 		);
3307 	}
3308 }
3309 
3310 /*
3311  * This routine is called before a device strategy routine.
3312  * It is used to tell the VM system that paging I/O is in
3313  * progress, and treat the pages associated with the buffer
3314  * almost as being PG_BUSY.  Also the object paging_in_progress
3315  * flag is handled to make sure that the object doesn't become
3316  * inconsistant.
3317  *
3318  * Since I/O has not been initiated yet, certain buffer flags
3319  * such as BIO_ERROR or B_INVAL may be in an inconsistant state
3320  * and should be ignored.
3321  */
3322 void
3323 vfs_busy_pages(struct buf * bp, int clear_modify)
3324 {
3325 	int i, bogus;
3326 
3327 	if (bp->b_flags & B_VMIO) {
3328 		vm_object_t obj;
3329 		vm_ooffset_t foff;
3330 
3331 		obj = bp->b_object;
3332 		foff = bp->b_offset;
3333 		KASSERT(bp->b_offset != NOOFFSET,
3334 		    ("vfs_busy_pages: no buffer offset"));
3335 		vfs_setdirty(bp);
3336 retry:
3337 		vm_page_lock_queues();
3338 		for (i = 0; i < bp->b_npages; i++) {
3339 			vm_page_t m = bp->b_pages[i];
3340 
3341 			if (vm_page_sleep_if_busy(m, FALSE, "vbpage"))
3342 				goto retry;
3343 		}
3344 		bogus = 0;
3345 		for (i = 0; i < bp->b_npages; i++) {
3346 			vm_page_t m = bp->b_pages[i];
3347 
3348 			vm_page_flag_clear(m, PG_ZERO);
3349 			if ((bp->b_flags & B_CLUSTER) == 0) {
3350 				vm_object_pip_add(obj, 1);
3351 				vm_page_io_start(m);
3352 			}
3353 			/*
3354 			 * When readying a buffer for a read ( i.e
3355 			 * clear_modify == 0 ), it is important to do
3356 			 * bogus_page replacement for valid pages in
3357 			 * partially instantiated buffers.  Partially
3358 			 * instantiated buffers can, in turn, occur when
3359 			 * reconstituting a buffer from its VM backing store
3360 			 * base.  We only have to do this if B_CACHE is
3361 			 * clear ( which causes the I/O to occur in the
3362 			 * first place ).  The replacement prevents the read
3363 			 * I/O from overwriting potentially dirty VM-backed
3364 			 * pages.  XXX bogus page replacement is, uh, bogus.
3365 			 * It may not work properly with small-block devices.
3366 			 * We need to find a better way.
3367 			 */
3368 			pmap_remove_all(m);
3369 			if (clear_modify)
3370 				vfs_page_set_valid(bp, foff, i, m);
3371 			else if (m->valid == VM_PAGE_BITS_ALL &&
3372 				(bp->b_flags & B_CACHE) == 0) {
3373 				bp->b_pages[i] = bogus_page;
3374 				bogus++;
3375 			}
3376 			foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3377 		}
3378 		vm_page_unlock_queues();
3379 		if (bogus)
3380 			pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
3381 	}
3382 }
3383 
3384 /*
3385  * Tell the VM system that the pages associated with this buffer
3386  * are clean.  This is used for delayed writes where the data is
3387  * going to go to disk eventually without additional VM intevention.
3388  *
3389  * Note that while we only really need to clean through to b_bcount, we
3390  * just go ahead and clean through to b_bufsize.
3391  */
3392 static void
3393 vfs_clean_pages(struct buf * bp)
3394 {
3395 	int i;
3396 
3397 	GIANT_REQUIRED;
3398 
3399 	if (bp->b_flags & B_VMIO) {
3400 		vm_ooffset_t foff;
3401 
3402 		foff = bp->b_offset;
3403 		KASSERT(bp->b_offset != NOOFFSET,
3404 		    ("vfs_clean_pages: no buffer offset"));
3405 		vm_page_lock_queues();
3406 		for (i = 0; i < bp->b_npages; i++) {
3407 			vm_page_t m = bp->b_pages[i];
3408 			vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3409 			vm_ooffset_t eoff = noff;
3410 
3411 			if (eoff > bp->b_offset + bp->b_bufsize)
3412 				eoff = bp->b_offset + bp->b_bufsize;
3413 			vfs_page_set_valid(bp, foff, i, m);
3414 			/* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3415 			foff = noff;
3416 		}
3417 		vm_page_unlock_queues();
3418 	}
3419 }
3420 
3421 /*
3422  *	vfs_bio_set_validclean:
3423  *
3424  *	Set the range within the buffer to valid and clean.  The range is
3425  *	relative to the beginning of the buffer, b_offset.  Note that b_offset
3426  *	itself may be offset from the beginning of the first page.
3427  *
3428  */
3429 
3430 void
3431 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3432 {
3433 	if (bp->b_flags & B_VMIO) {
3434 		int i;
3435 		int n;
3436 
3437 		/*
3438 		 * Fixup base to be relative to beginning of first page.
3439 		 * Set initial n to be the maximum number of bytes in the
3440 		 * first page that can be validated.
3441 		 */
3442 
3443 		base += (bp->b_offset & PAGE_MASK);
3444 		n = PAGE_SIZE - (base & PAGE_MASK);
3445 
3446 		vm_page_lock_queues();
3447 		for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3448 			vm_page_t m = bp->b_pages[i];
3449 
3450 			if (n > size)
3451 				n = size;
3452 
3453 			vm_page_set_validclean(m, base & PAGE_MASK, n);
3454 			base += n;
3455 			size -= n;
3456 			n = PAGE_SIZE;
3457 		}
3458 		vm_page_unlock_queues();
3459 	}
3460 }
3461 
3462 /*
3463  *	vfs_bio_clrbuf:
3464  *
3465  *	clear a buffer.  This routine essentially fakes an I/O, so we need
3466  *	to clear BIO_ERROR and B_INVAL.
3467  *
3468  *	Note that while we only theoretically need to clear through b_bcount,
3469  *	we go ahead and clear through b_bufsize.
3470  */
3471 
3472 void
3473 vfs_bio_clrbuf(struct buf *bp)
3474 {
3475 	int i, mask = 0;
3476 	caddr_t sa, ea;
3477 
3478 	GIANT_REQUIRED;
3479 
3480 	if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3481 		bp->b_flags &= ~B_INVAL;
3482 		bp->b_ioflags &= ~BIO_ERROR;
3483 		if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3484 		    (bp->b_offset & PAGE_MASK) == 0) {
3485 			mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3486 			if ((bp->b_pages[0]->valid & mask) == mask) {
3487 				bp->b_resid = 0;
3488 				return;
3489 			}
3490 			if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3491 			    ((bp->b_pages[0]->valid & mask) == 0)) {
3492 				bzero(bp->b_data, bp->b_bufsize);
3493 				bp->b_pages[0]->valid |= mask;
3494 				bp->b_resid = 0;
3495 				return;
3496 			}
3497 		}
3498 		ea = sa = bp->b_data;
3499 		for(i=0;i<bp->b_npages;i++,sa=ea) {
3500 			int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3501 			ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3502 			ea = (caddr_t)(vm_offset_t)ulmin(
3503 			    (u_long)(vm_offset_t)ea,
3504 			    (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3505 			mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3506 			if ((bp->b_pages[i]->valid & mask) == mask)
3507 				continue;
3508 			if ((bp->b_pages[i]->valid & mask) == 0) {
3509 				if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3510 					bzero(sa, ea - sa);
3511 				}
3512 			} else {
3513 				for (; sa < ea; sa += DEV_BSIZE, j++) {
3514 					if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3515 						(bp->b_pages[i]->valid & (1<<j)) == 0)
3516 						bzero(sa, DEV_BSIZE);
3517 				}
3518 			}
3519 			bp->b_pages[i]->valid |= mask;
3520 			vm_page_lock_queues();
3521 			vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3522 			vm_page_unlock_queues();
3523 		}
3524 		bp->b_resid = 0;
3525 	} else {
3526 		clrbuf(bp);
3527 	}
3528 }
3529 
3530 /*
3531  * vm_hold_load_pages and vm_hold_free_pages get pages into
3532  * a buffers address space.  The pages are anonymous and are
3533  * not associated with a file object.
3534  */
3535 static void
3536 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3537 {
3538 	vm_offset_t pg;
3539 	vm_page_t p;
3540 	int index;
3541 
3542 	GIANT_REQUIRED;
3543 
3544 	to = round_page(to);
3545 	from = round_page(from);
3546 	index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3547 
3548 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3549 tryagain:
3550 		/*
3551 		 * note: must allocate system pages since blocking here
3552 		 * could intefere with paging I/O, no matter which
3553 		 * process we are.
3554 		 */
3555 		vm_object_lock(kernel_object);
3556 		p = vm_page_alloc(kernel_object,
3557 			((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3558 		    VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
3559 		vm_object_unlock(kernel_object);
3560 		if (!p) {
3561 			atomic_add_int(&vm_pageout_deficit,
3562 			    (to - pg) >> PAGE_SHIFT);
3563 			VM_WAIT;
3564 			goto tryagain;
3565 		}
3566 		vm_page_lock_queues();
3567 		p->valid = VM_PAGE_BITS_ALL;
3568 		vm_page_unlock_queues();
3569 		pmap_qenter(pg, &p, 1);
3570 		bp->b_pages[index] = p;
3571 		vm_page_lock_queues();
3572 		vm_page_wakeup(p);
3573 		vm_page_unlock_queues();
3574 	}
3575 	bp->b_npages = index;
3576 }
3577 
3578 /* Return pages associated with this buf to the vm system */
3579 static void
3580 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3581 {
3582 	vm_offset_t pg;
3583 	vm_page_t p;
3584 	int index, newnpages;
3585 
3586 	GIANT_REQUIRED;
3587 
3588 	from = round_page(from);
3589 	to = round_page(to);
3590 	newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3591 
3592 	for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3593 		p = bp->b_pages[index];
3594 		if (p && (index < bp->b_npages)) {
3595 			if (p->busy) {
3596 				printf(
3597 			    "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
3598 				    (intmax_t)bp->b_blkno,
3599 				    (intmax_t)bp->b_lblkno);
3600 			}
3601 			bp->b_pages[index] = NULL;
3602 			pmap_qremove(pg, 1);
3603 			vm_page_lock_queues();
3604 			vm_page_busy(p);
3605 			vm_page_unwire(p, 0);
3606 			vm_page_free(p);
3607 			vm_page_unlock_queues();
3608 		}
3609 	}
3610 	bp->b_npages = newnpages;
3611 }
3612 
3613 /*
3614  * Map an IO request into kernel virtual address space.
3615  *
3616  * All requests are (re)mapped into kernel VA space.
3617  * Notice that we use b_bufsize for the size of the buffer
3618  * to be mapped.  b_bcount might be modified by the driver.
3619  *
3620  * Note that even if the caller determines that the address space should
3621  * be valid, a race or a smaller-file mapped into a larger space may
3622  * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
3623  * check the return value.
3624  */
3625 int
3626 vmapbuf(struct buf *bp)
3627 {
3628 	caddr_t addr, kva;
3629 	vm_offset_t pa;
3630 	int pidx, i;
3631 	struct vm_page *m;
3632 	struct pmap *pmap = &curproc->p_vmspace->vm_pmap;
3633 
3634 	GIANT_REQUIRED;
3635 
3636 	if ((bp->b_flags & B_PHYS) == 0)
3637 		panic("vmapbuf");
3638 
3639 	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0;
3640 	     addr < bp->b_data + bp->b_bufsize;
3641 	     addr += PAGE_SIZE, pidx++) {
3642 		/*
3643 		 * Do the vm_fault if needed; do the copy-on-write thing
3644 		 * when reading stuff off device into memory.
3645 		 *
3646 		 * NOTE! Must use pmap_extract() because addr may be in
3647 		 * the userland address space, and kextract is only guarenteed
3648 		 * to work for the kernland address space (see: sparc64 port).
3649 		 */
3650 retry:
3651 		i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3652 			(bp->b_iocmd == BIO_READ) ?
3653 			(VM_PROT_READ|VM_PROT_WRITE) : VM_PROT_READ);
3654 		if (i < 0) {
3655 			printf("vmapbuf: warning, bad user address during I/O\n");
3656 			vm_page_lock_queues();
3657 			for (i = 0; i < pidx; ++i) {
3658 				vm_page_unhold(bp->b_pages[i]);
3659 				bp->b_pages[i] = NULL;
3660 			}
3661 			vm_page_unlock_queues();
3662 			return(-1);
3663 		}
3664 		pa = trunc_page(pmap_extract(pmap, (vm_offset_t) addr));
3665 		if (pa == 0) {
3666 			printf("vmapbuf: warning, race against user address during I/O");
3667 			goto retry;
3668 		}
3669 		m = PHYS_TO_VM_PAGE(pa);
3670 		vm_page_lock_queues();
3671 		vm_page_hold(m);
3672 		vm_page_unlock_queues();
3673 		bp->b_pages[pidx] = m;
3674 	}
3675 	if (pidx > btoc(MAXPHYS))
3676 		panic("vmapbuf: mapped more than MAXPHYS");
3677 	pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3678 
3679 	kva = bp->b_saveaddr;
3680 	bp->b_npages = pidx;
3681 	bp->b_saveaddr = bp->b_data;
3682 	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3683 	return(0);
3684 }
3685 
3686 /*
3687  * Free the io map PTEs associated with this IO operation.
3688  * We also invalidate the TLB entries and restore the original b_addr.
3689  */
3690 void
3691 vunmapbuf(struct buf *bp)
3692 {
3693 	int pidx;
3694 	int npages;
3695 
3696 	GIANT_REQUIRED;
3697 
3698 	if ((bp->b_flags & B_PHYS) == 0)
3699 		panic("vunmapbuf");
3700 
3701 	npages = bp->b_npages;
3702 	pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3703 		     npages);
3704 	vm_page_lock_queues();
3705 	for (pidx = 0; pidx < npages; pidx++)
3706 		vm_page_unhold(bp->b_pages[pidx]);
3707 	vm_page_unlock_queues();
3708 
3709 	bp->b_data = bp->b_saveaddr;
3710 }
3711 
3712 #include "opt_ddb.h"
3713 #ifdef DDB
3714 #include <ddb/ddb.h>
3715 
3716 /* DDB command to show buffer data */
3717 DB_SHOW_COMMAND(buffer, db_show_buffer)
3718 {
3719 	/* get args */
3720 	struct buf *bp = (struct buf *)addr;
3721 
3722 	if (!have_addr) {
3723 		db_printf("usage: show buffer <addr>\n");
3724 		return;
3725 	}
3726 
3727 	db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3728 	db_printf(
3729 	    "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
3730 	    "b_dev = (%d,%d), b_data = %p, b_blkno = %jd, b_pblkno = %jd\n",
3731 	    bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3732 	    major(bp->b_dev), minor(bp->b_dev), bp->b_data,
3733 	    (intmax_t)bp->b_blkno, (intmax_t)bp->b_pblkno);
3734 	if (bp->b_npages) {
3735 		int i;
3736 		db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3737 		for (i = 0; i < bp->b_npages; i++) {
3738 			vm_page_t m;
3739 			m = bp->b_pages[i];
3740 			db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3741 			    (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3742 			if ((i + 1) < bp->b_npages)
3743 				db_printf(",");
3744 		}
3745 		db_printf("\n");
3746 	}
3747 }
3748 #endif /* DDB */
3749