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