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