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