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