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