2 * Copyright (c) 2004 Poul-Henning Kamp
3 * Copyright (c) 1994,1997 John S. Dyson
4 * Copyright (c) 2013 The FreeBSD Foundation
7 * Portions of this software were developed by Konstantin Belousov
8 * under sponsorship from the FreeBSD Foundation.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * this file contains a new buffer I/O scheme implementing a coherent
34 * VM object and buffer cache scheme. Pains have been taken to make
35 * sure that the performance degradation associated with schemes such
36 * as this is not realized.
38 * Author: John S. Dyson
39 * Significant help during the development and debugging phases
40 * had been provided by David Greenman, also of the FreeBSD core team.
42 * see man buf(9) for more info.
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
49 #include <sys/systm.h>
53 #include <sys/devicestat.h>
54 #include <sys/eventhandler.h>
56 #include <sys/limits.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mutex.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
64 #include <sys/resourcevar.h>
65 #include <sys/rwlock.h>
66 #include <sys/sysctl.h>
68 #include <sys/vmmeter.h>
69 #include <sys/vnode.h>
70 #include <geom/geom.h>
72 #include <vm/vm_param.h>
73 #include <vm/vm_kern.h>
74 #include <vm/vm_pageout.h>
75 #include <vm/vm_page.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_map.h>
79 #include "opt_compat.h"
80 #include "opt_directio.h"
83 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
85 struct bio_ops bioops; /* I/O operation notification */
87 struct buf_ops buf_ops_bio = {
88 .bop_name = "buf_ops_bio",
89 .bop_write = bufwrite,
90 .bop_strategy = bufstrategy,
92 .bop_bdflush = bufbdflush,
96 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
97 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c.
99 struct buf *buf; /* buffer header pool */
100 caddr_t unmapped_buf;
102 static struct proc *bufdaemonproc;
104 static int inmem(struct vnode *vp, daddr_t blkno);
105 static void vm_hold_free_pages(struct buf *bp, int newbsize);
106 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
108 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
109 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
111 static void vfs_clean_pages_dirty_buf(struct buf *bp);
112 static void vfs_setdirty_locked_object(struct buf *bp);
113 static void vfs_vmio_release(struct buf *bp);
114 static int vfs_bio_clcheck(struct vnode *vp, int size,
115 daddr_t lblkno, daddr_t blkno);
116 static int buf_flush(struct vnode *vp, int);
117 static int flushbufqueues(struct vnode *, int, int);
118 static void buf_daemon(void);
119 static void bremfreel(struct buf *bp);
120 static __inline void bd_wakeup(void);
121 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
122 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
123 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
126 int vmiodirenable = TRUE;
127 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
128 "Use the VM system for directory writes");
129 long runningbufspace;
130 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
131 "Amount of presently outstanding async buffer io");
132 static long bufspace;
133 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
134 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
135 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
136 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
138 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
139 "Virtual memory used for buffers");
141 static long unmapped_bufspace;
142 SYSCTL_LONG(_vfs, OID_AUTO, unmapped_bufspace, CTLFLAG_RD,
143 &unmapped_bufspace, 0,
144 "Amount of unmapped buffers, inclusive in the bufspace");
145 static long maxbufspace;
146 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
147 "Maximum allowed value of bufspace (including buf_daemon)");
148 static long bufmallocspace;
149 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
150 "Amount of malloced memory for buffers");
151 static long maxbufmallocspace;
152 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
153 "Maximum amount of malloced memory for buffers");
154 static long lobufspace;
155 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
156 "Minimum amount of buffers we want to have");
158 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
159 "Maximum allowed value of bufspace (excluding buf_daemon)");
160 static int bufreusecnt;
161 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
162 "Number of times we have reused a buffer");
163 static int buffreekvacnt;
164 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
165 "Number of times we have freed the KVA space from some buffer");
166 static int bufdefragcnt;
167 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
168 "Number of times we have had to repeat buffer allocation to defragment");
169 static long lorunningspace;
170 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
171 "Minimum preferred space used for in-progress I/O");
172 static long hirunningspace;
173 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
174 "Maximum amount of space to use for in-progress I/O");
175 int dirtybufferflushes;
176 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
177 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
179 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
180 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
181 int altbufferflushes;
182 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
183 0, "Number of fsync flushes to limit dirty buffers");
184 static int recursiveflushes;
185 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
186 0, "Number of flushes skipped due to being recursive");
187 static int numdirtybuffers;
188 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
189 "Number of buffers that are dirty (has unwritten changes) at the moment");
190 static int lodirtybuffers;
191 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
192 "How many buffers we want to have free before bufdaemon can sleep");
193 static int hidirtybuffers;
194 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
195 "When the number of dirty buffers is considered severe");
197 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
198 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
199 static int numfreebuffers;
200 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
201 "Number of free buffers");
202 static int lofreebuffers;
203 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
205 static int hifreebuffers;
206 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
207 "XXX Complicatedly unused");
208 static int getnewbufcalls;
209 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
210 "Number of calls to getnewbuf");
211 static int getnewbufrestarts;
212 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
213 "Number of times getnewbuf has had to restart a buffer aquisition");
214 static int mappingrestarts;
215 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
216 "Number of times getblk has had to restart a buffer mapping for "
218 static int flushbufqtarget = 100;
219 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
220 "Amount of work to do in flushbufqueues when helping bufdaemon");
221 static long notbufdflushes;
222 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 0,
223 "Number of dirty buffer flushes done by the bufdaemon helpers");
224 static long barrierwrites;
225 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
226 "Number of barrier writes");
227 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
228 &unmapped_buf_allowed, 0,
229 "Permit the use of the unmapped i/o");
232 * Lock for the non-dirty bufqueues
234 static struct mtx_padalign bqclean;
237 * Lock for the dirty queue.
239 static struct mtx_padalign bqdirty;
242 * This lock synchronizes access to bd_request.
244 static struct mtx_padalign bdlock;
247 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
248 * waitrunningbufspace().
250 static struct mtx_padalign rbreqlock;
253 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
255 static struct mtx_padalign nblock;
258 * Lock that protects bdirtywait.
260 static struct mtx_padalign bdirtylock;
263 * Wakeup point for bufdaemon, as well as indicator of whether it is already
264 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
267 static int bd_request;
270 * Request for the buf daemon to write more buffers than is indicated by
271 * lodirtybuf. This may be necessary to push out excess dependencies or
272 * defragment the address space where a simple count of the number of dirty
273 * buffers is insufficient to characterize the demand for flushing them.
275 static int bd_speedupreq;
278 * bogus page -- for I/O to/from partially complete buffers
279 * this is a temporary solution to the problem, but it is not
280 * really that bad. it would be better to split the buffer
281 * for input in the case of buffers partially already in memory,
282 * but the code is intricate enough already.
284 vm_page_t bogus_page;
287 * Synchronization (sleep/wakeup) variable for active buffer space requests.
288 * Set when wait starts, cleared prior to wakeup().
289 * Used in runningbufwakeup() and waitrunningbufspace().
291 static int runningbufreq;
294 * Synchronization (sleep/wakeup) variable for buffer requests.
295 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
297 * Used in numdirtywakeup(), bufspacewakeup(), bufcountadd(), bwillwrite(),
298 * getnewbuf(), and getblk().
300 static int needsbuffer;
303 * Synchronization for bwillwrite() waiters.
305 static int bdirtywait;
308 * Definitions for the buffer free lists.
310 #define BUFFER_QUEUES 5 /* number of free buffer queues */
312 #define QUEUE_NONE 0 /* on no queue */
313 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */
314 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
315 #define QUEUE_EMPTYKVA 3 /* empty buffer headers w/KVA assignment */
316 #define QUEUE_EMPTY 4 /* empty buffer headers */
317 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
319 /* Queues for free buffers with various properties */
320 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
322 static int bq_len[BUFFER_QUEUES];
326 * Single global constant for BUF_WMESG, to avoid getting multiple references.
327 * buf_wmesg is referred from macros.
329 const char *buf_wmesg = BUF_WMESG;
331 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
332 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
333 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
335 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
336 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
338 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
343 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
344 return (sysctl_handle_long(oidp, arg1, arg2, req));
345 lvalue = *(long *)arg1;
346 if (lvalue > INT_MAX)
347 /* On overflow, still write out a long to trigger ENOMEM. */
348 return (sysctl_handle_long(oidp, &lvalue, 0, req));
350 return (sysctl_handle_int(oidp, &ivalue, 0, req));
355 extern void ffs_rawread_setup(void);
356 #endif /* DIRECTIO */
361 * Return the appropriate queue lock based on the index.
363 static inline struct mtx *
367 if (qindex == QUEUE_DIRTY)
368 return (struct mtx *)(&bqdirty);
369 return (struct mtx *)(&bqclean);
375 * Wakeup any bwillwrite() waiters.
380 mtx_lock(&bdirtylock);
385 mtx_unlock(&bdirtylock);
391 * Decrement the numdirtybuffers count by one and wakeup any
392 * threads blocked in bwillwrite().
398 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
399 (lodirtybuffers + hidirtybuffers) / 2)
406 * Increment the numdirtybuffers count by one and wakeup the buf
414 * Only do the wakeup once as we cross the boundary. The
415 * buf daemon will keep running until the condition clears.
417 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
418 (lodirtybuffers + hidirtybuffers) / 2)
425 * Called when buffer space is potentially available for recovery.
426 * getnewbuf() will block on this flag when it is unable to free
427 * sufficient buffer space. Buffer space becomes recoverable when
428 * bp's get placed back in the queues.
436 * If someone is waiting for BUF space, wake them up. Even
437 * though we haven't freed the kva space yet, the waiting
438 * process will be able to now.
441 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
442 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
443 wakeup(&needsbuffer);
451 * Wake up processes that are waiting on asynchronous writes to fall
452 * below lorunningspace.
458 mtx_lock(&rbreqlock);
461 wakeup(&runningbufreq);
463 mtx_unlock(&rbreqlock);
469 * Decrement the outstanding write count according.
472 runningbufwakeup(struct buf *bp)
476 bspace = bp->b_runningbufspace;
479 space = atomic_fetchadd_long(&runningbufspace, -bspace);
480 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
482 bp->b_runningbufspace = 0;
484 * Only acquire the lock and wakeup on the transition from exceeding
485 * the threshold to falling below it.
487 if (space < lorunningspace)
489 if (space - bspace > lorunningspace)
497 * Called when a buffer has been added to one of the free queues to
498 * account for the buffer and to wakeup anyone waiting for free buffers.
499 * This typically occurs when large amounts of metadata are being handled
500 * by the buffer cache ( else buffer space runs out first, usually ).
503 bufcountadd(struct buf *bp)
507 KASSERT((bp->b_flags & B_INFREECNT) == 0,
508 ("buf %p already counted as free", bp));
509 bp->b_flags |= B_INFREECNT;
510 old = atomic_fetchadd_int(&numfreebuffers, 1);
511 KASSERT(old >= 0 && old < nbuf,
512 ("numfreebuffers climbed to %d", old + 1));
515 needsbuffer &= ~VFS_BIO_NEED_ANY;
516 if (numfreebuffers >= hifreebuffers)
517 needsbuffer &= ~VFS_BIO_NEED_FREE;
518 wakeup(&needsbuffer);
526 * Decrement the numfreebuffers count as needed.
529 bufcountsub(struct buf *bp)
534 * Fixup numfreebuffers count. If the buffer is invalid or not
535 * delayed-write, the buffer was free and we must decrement
538 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
539 KASSERT((bp->b_flags & B_INFREECNT) != 0,
540 ("buf %p not counted in numfreebuffers", bp));
541 bp->b_flags &= ~B_INFREECNT;
542 old = atomic_fetchadd_int(&numfreebuffers, -1);
543 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
548 * waitrunningbufspace()
550 * runningbufspace is a measure of the amount of I/O currently
551 * running. This routine is used in async-write situations to
552 * prevent creating huge backups of pending writes to a device.
553 * Only asynchronous writes are governed by this function.
555 * This does NOT turn an async write into a sync write. It waits
556 * for earlier writes to complete and generally returns before the
557 * caller's write has reached the device.
560 waitrunningbufspace(void)
563 mtx_lock(&rbreqlock);
564 while (runningbufspace > hirunningspace) {
566 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
568 mtx_unlock(&rbreqlock);
573 * vfs_buf_test_cache:
575 * Called when a buffer is extended. This function clears the B_CACHE
576 * bit if the newly extended portion of the buffer does not contain
581 vfs_buf_test_cache(struct buf *bp,
582 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
586 VM_OBJECT_ASSERT_LOCKED(m->object);
587 if (bp->b_flags & B_CACHE) {
588 int base = (foff + off) & PAGE_MASK;
589 if (vm_page_is_valid(m, base, size) == 0)
590 bp->b_flags &= ~B_CACHE;
594 /* Wake up the buffer daemon if necessary */
600 if (bd_request == 0) {
608 * bd_speedup - speedup the buffer cache flushing code
617 if (bd_speedupreq == 0 || bd_request == 0)
627 #define TRANSIENT_DENOM 5
629 #define TRANSIENT_DENOM 10
633 * Calculating buffer cache scaling values and reserve space for buffer
634 * headers. This is called during low level kernel initialization and
635 * may be called more then once. We CANNOT write to the memory area
636 * being reserved at this time.
639 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
642 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
645 * physmem_est is in pages. Convert it to kilobytes (assumes
646 * PAGE_SIZE is >= 1K)
648 physmem_est = physmem_est * (PAGE_SIZE / 1024);
651 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
652 * For the first 64MB of ram nominally allocate sufficient buffers to
653 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
654 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
655 * the buffer cache we limit the eventual kva reservation to
658 * factor represents the 1/4 x ram conversion.
661 int factor = 4 * BKVASIZE / 1024;
664 if (physmem_est > 4096)
665 nbuf += min((physmem_est - 4096) / factor,
667 if (physmem_est > 65536)
668 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
669 32 * 1024 * 1024 / (factor * 5));
671 if (maxbcache && nbuf > maxbcache / BKVASIZE)
672 nbuf = maxbcache / BKVASIZE;
677 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
678 maxbuf = (LONG_MAX / 3) / BKVASIZE;
681 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
687 * Ideal allocation size for the transient bio submap if 10%
688 * of the maximal space buffer map. This roughly corresponds
689 * to the amount of the buffer mapped for typical UFS load.
691 * Clip the buffer map to reserve space for the transient
692 * BIOs, if its extent is bigger than 90% (80% on i386) of the
693 * maximum buffer map extent on the platform.
695 * The fall-back to the maxbuf in case of maxbcache unset,
696 * allows to not trim the buffer KVA for the architectures
697 * with ample KVA space.
699 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
700 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
701 buf_sz = (long)nbuf * BKVASIZE;
702 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
703 (TRANSIENT_DENOM - 1)) {
705 * There is more KVA than memory. Do not
706 * adjust buffer map size, and assign the rest
707 * of maxbuf to transient map.
709 biotmap_sz = maxbuf_sz - buf_sz;
712 * Buffer map spans all KVA we could afford on
713 * this platform. Give 10% (20% on i386) of
714 * the buffer map to the transient bio map.
716 biotmap_sz = buf_sz / TRANSIENT_DENOM;
717 buf_sz -= biotmap_sz;
719 if (biotmap_sz / INT_MAX > MAXPHYS)
720 bio_transient_maxcnt = INT_MAX;
722 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
724 * Artifically limit to 1024 simultaneous in-flight I/Os
725 * using the transient mapping.
727 if (bio_transient_maxcnt > 1024)
728 bio_transient_maxcnt = 1024;
730 nbuf = buf_sz / BKVASIZE;
734 * swbufs are used as temporary holders for I/O, such as paging I/O.
735 * We have no less then 16 and no more then 256.
737 nswbuf = max(min(nbuf/4, 256), 16);
739 if (nswbuf < NSWBUF_MIN)
747 * Reserve space for the buffer cache buffers
750 v = (caddr_t)(swbuf + nswbuf);
752 v = (caddr_t)(buf + nbuf);
757 /* Initialize the buffer subsystem. Called before use of any buffers. */
764 mtx_init(&bqclean, "bufq clean lock", NULL, MTX_DEF);
765 mtx_init(&bqdirty, "bufq dirty lock", NULL, MTX_DEF);
766 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
767 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
768 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
769 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
771 /* next, make a null set of free lists */
772 for (i = 0; i < BUFFER_QUEUES; i++)
773 TAILQ_INIT(&bufqueues[i]);
775 /* finally, initialize each buffer header and stick on empty q */
776 for (i = 0; i < nbuf; i++) {
778 bzero(bp, sizeof *bp);
779 bp->b_flags = B_INVAL | B_INFREECNT;
780 bp->b_rcred = NOCRED;
781 bp->b_wcred = NOCRED;
782 bp->b_qindex = QUEUE_EMPTY;
784 LIST_INIT(&bp->b_dep);
786 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
788 bq_len[QUEUE_EMPTY]++;
793 * maxbufspace is the absolute maximum amount of buffer space we are
794 * allowed to reserve in KVM and in real terms. The absolute maximum
795 * is nominally used by buf_daemon. hibufspace is the nominal maximum
796 * used by most other processes. The differential is required to
797 * ensure that buf_daemon is able to run when other processes might
798 * be blocked waiting for buffer space.
800 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
801 * this may result in KVM fragmentation which is not handled optimally
804 maxbufspace = (long)nbuf * BKVASIZE;
805 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
806 lobufspace = hibufspace - MAXBSIZE;
809 * Note: The 16 MiB upper limit for hirunningspace was chosen
810 * arbitrarily and may need further tuning. It corresponds to
811 * 128 outstanding write IO requests (if IO size is 128 KiB),
812 * which fits with many RAID controllers' tagged queuing limits.
813 * The lower 1 MiB limit is the historical upper limit for
816 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
817 16 * 1024 * 1024), 1024 * 1024);
818 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
821 * Limit the amount of malloc memory since it is wired permanently into
822 * the kernel space. Even though this is accounted for in the buffer
823 * allocation, we don't want the malloced region to grow uncontrolled.
824 * The malloc scheme improves memory utilization significantly on average
825 * (small) directories.
827 maxbufmallocspace = hibufspace / 20;
830 * Reduce the chance of a deadlock occuring by limiting the number
831 * of delayed-write dirty buffers we allow to stack up.
833 hidirtybuffers = nbuf / 4 + 20;
834 dirtybufthresh = hidirtybuffers * 9 / 10;
837 * To support extreme low-memory systems, make sure hidirtybuffers cannot
838 * eat up all available buffer space. This occurs when our minimum cannot
839 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
840 * BKVASIZE'd buffers.
842 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
843 hidirtybuffers >>= 1;
845 lodirtybuffers = hidirtybuffers / 2;
848 * Try to keep the number of free buffers in the specified range,
849 * and give special processes (e.g. like buf_daemon) access to an
852 lofreebuffers = nbuf / 18 + 5;
853 hifreebuffers = 2 * lofreebuffers;
854 numfreebuffers = nbuf;
856 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
857 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
858 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
863 vfs_buf_check_mapped(struct buf *bp)
866 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
867 ("mapped buf %p %x", bp, bp->b_flags));
868 KASSERT(bp->b_kvabase != unmapped_buf,
869 ("mapped buf: b_kvabase was not updated %p", bp));
870 KASSERT(bp->b_data != unmapped_buf,
871 ("mapped buf: b_data was not updated %p", bp));
875 vfs_buf_check_unmapped(struct buf *bp)
878 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
879 ("unmapped buf %p %x", bp, bp->b_flags));
880 KASSERT(bp->b_kvabase == unmapped_buf,
881 ("unmapped buf: corrupted b_kvabase %p", bp));
882 KASSERT(bp->b_data == unmapped_buf,
883 ("unmapped buf: corrupted b_data %p", bp));
886 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
887 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
889 #define BUF_CHECK_MAPPED(bp) do {} while (0)
890 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
894 bpmap_qenter(struct buf *bp)
897 BUF_CHECK_MAPPED(bp);
900 * bp->b_data is relative to bp->b_offset, but
901 * bp->b_offset may be offset into the first page.
903 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
904 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
905 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
906 (vm_offset_t)(bp->b_offset & PAGE_MASK));
910 * bfreekva() - free the kva allocation for a buffer.
912 * Since this call frees up buffer space, we call bufspacewakeup().
915 bfreekva(struct buf *bp)
918 if (bp->b_kvasize == 0)
921 atomic_add_int(&buffreekvacnt, 1);
922 atomic_subtract_long(&bufspace, bp->b_kvasize);
923 if ((bp->b_flags & B_UNMAPPED) == 0) {
924 BUF_CHECK_MAPPED(bp);
925 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase,
928 BUF_CHECK_UNMAPPED(bp);
929 if ((bp->b_flags & B_KVAALLOC) != 0) {
930 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvaalloc,
933 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
934 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
943 * Insert the buffer into the appropriate free list.
946 binsfree(struct buf *bp, int qindex)
948 struct mtx *olock, *nlock;
950 BUF_ASSERT_XLOCKED(bp);
952 olock = bqlock(bp->b_qindex);
953 nlock = bqlock(qindex);
955 /* Handle delayed bremfree() processing. */
956 if (bp->b_flags & B_REMFREE)
959 if (bp->b_qindex != QUEUE_NONE)
960 panic("binsfree: free buffer onto another queue???");
962 bp->b_qindex = qindex;
963 if (olock != nlock) {
967 if (bp->b_flags & B_AGE)
968 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
970 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
972 bq_len[bp->b_qindex]++;
977 * Something we can maybe free or reuse.
979 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
982 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
989 * Mark the buffer for removal from the appropriate free list.
993 bremfree(struct buf *bp)
996 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
997 KASSERT((bp->b_flags & B_REMFREE) == 0,
998 ("bremfree: buffer %p already marked for delayed removal.", bp));
999 KASSERT(bp->b_qindex != QUEUE_NONE,
1000 ("bremfree: buffer %p not on a queue.", bp));
1001 BUF_ASSERT_XLOCKED(bp);
1003 bp->b_flags |= B_REMFREE;
1010 * Force an immediate removal from a free list. Used only in nfs when
1011 * it abuses the b_freelist pointer.
1014 bremfreef(struct buf *bp)
1018 qlock = bqlock(bp->b_qindex);
1027 * Removes a buffer from the free list, must be called with the
1028 * correct qlock held.
1031 bremfreel(struct buf *bp)
1034 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1035 bp, bp->b_vp, bp->b_flags);
1036 KASSERT(bp->b_qindex != QUEUE_NONE,
1037 ("bremfreel: buffer %p not on a queue.", bp));
1038 BUF_ASSERT_XLOCKED(bp);
1039 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1041 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1043 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1045 bq_len[bp->b_qindex]--;
1047 bp->b_qindex = QUEUE_NONE;
1049 * If this was a delayed bremfree() we only need to remove the buffer
1050 * from the queue and return the stats are already done.
1052 if (bp->b_flags & B_REMFREE) {
1053 bp->b_flags &= ~B_REMFREE;
1060 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1061 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1062 * the buffer is valid and we do not have to do anything.
1065 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1066 int cnt, struct ucred * cred)
1071 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1072 if (inmem(vp, *rablkno))
1074 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1076 if ((rabp->b_flags & B_CACHE) == 0) {
1077 if (!TD_IS_IDLETHREAD(curthread))
1078 curthread->td_ru.ru_inblock++;
1079 rabp->b_flags |= B_ASYNC;
1080 rabp->b_flags &= ~B_INVAL;
1081 rabp->b_ioflags &= ~BIO_ERROR;
1082 rabp->b_iocmd = BIO_READ;
1083 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1084 rabp->b_rcred = crhold(cred);
1085 vfs_busy_pages(rabp, 0);
1087 rabp->b_iooffset = dbtob(rabp->b_blkno);
1096 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1098 * Get a buffer with the specified data. Look in the cache first. We
1099 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1100 * is set, the buffer is valid and we do not have to do anything, see
1101 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1104 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1105 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1108 int rv = 0, readwait = 0;
1110 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1112 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1114 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1118 /* if not found in cache, do some I/O */
1119 if ((bp->b_flags & B_CACHE) == 0) {
1120 if (!TD_IS_IDLETHREAD(curthread))
1121 curthread->td_ru.ru_inblock++;
1122 bp->b_iocmd = BIO_READ;
1123 bp->b_flags &= ~B_INVAL;
1124 bp->b_ioflags &= ~BIO_ERROR;
1125 if (bp->b_rcred == NOCRED && cred != NOCRED)
1126 bp->b_rcred = crhold(cred);
1127 vfs_busy_pages(bp, 0);
1128 bp->b_iooffset = dbtob(bp->b_blkno);
1133 breada(vp, rablkno, rabsize, cnt, cred);
1142 * Write, release buffer on completion. (Done by iodone
1143 * if async). Do not bother writing anything if the buffer
1146 * Note that we set B_CACHE here, indicating that buffer is
1147 * fully valid and thus cacheable. This is true even of NFS
1148 * now so we set it generally. This could be set either here
1149 * or in biodone() since the I/O is synchronous. We put it
1153 bufwrite(struct buf *bp)
1160 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1161 if (bp->b_flags & B_INVAL) {
1166 if (bp->b_flags & B_BARRIER)
1169 oldflags = bp->b_flags;
1171 BUF_ASSERT_HELD(bp);
1173 if (bp->b_pin_count > 0)
1176 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1177 ("FFS background buffer should not get here %p", bp));
1181 vp_md = vp->v_vflag & VV_MD;
1186 * Mark the buffer clean. Increment the bufobj write count
1187 * before bundirty() call, to prevent other thread from seeing
1188 * empty dirty list and zero counter for writes in progress,
1189 * falsely indicating that the bufobj is clean.
1191 bufobj_wref(bp->b_bufobj);
1194 bp->b_flags &= ~B_DONE;
1195 bp->b_ioflags &= ~BIO_ERROR;
1196 bp->b_flags |= B_CACHE;
1197 bp->b_iocmd = BIO_WRITE;
1199 vfs_busy_pages(bp, 1);
1202 * Normal bwrites pipeline writes
1204 bp->b_runningbufspace = bp->b_bufsize;
1205 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1207 if (!TD_IS_IDLETHREAD(curthread))
1208 curthread->td_ru.ru_oublock++;
1209 if (oldflags & B_ASYNC)
1211 bp->b_iooffset = dbtob(bp->b_blkno);
1214 if ((oldflags & B_ASYNC) == 0) {
1215 int rtval = bufwait(bp);
1218 } else if (space > hirunningspace) {
1220 * don't allow the async write to saturate the I/O
1221 * system. We will not deadlock here because
1222 * we are blocking waiting for I/O that is already in-progress
1223 * to complete. We do not block here if it is the update
1224 * or syncer daemon trying to clean up as that can lead
1227 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1228 waitrunningbufspace();
1235 bufbdflush(struct bufobj *bo, struct buf *bp)
1239 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1240 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1242 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1245 * Try to find a buffer to flush.
1247 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1248 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1250 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1253 panic("bdwrite: found ourselves");
1255 /* Don't countdeps with the bo lock held. */
1256 if (buf_countdeps(nbp, 0)) {
1261 if (nbp->b_flags & B_CLUSTEROK) {
1262 vfs_bio_awrite(nbp);
1267 dirtybufferflushes++;
1276 * Delayed write. (Buffer is marked dirty). Do not bother writing
1277 * anything if the buffer is marked invalid.
1279 * Note that since the buffer must be completely valid, we can safely
1280 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1281 * biodone() in order to prevent getblk from writing the buffer
1282 * out synchronously.
1285 bdwrite(struct buf *bp)
1287 struct thread *td = curthread;
1291 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1292 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1293 KASSERT((bp->b_flags & B_BARRIER) == 0,
1294 ("Barrier request in delayed write %p", bp));
1295 BUF_ASSERT_HELD(bp);
1297 if (bp->b_flags & B_INVAL) {
1303 * If we have too many dirty buffers, don't create any more.
1304 * If we are wildly over our limit, then force a complete
1305 * cleanup. Otherwise, just keep the situation from getting
1306 * out of control. Note that we have to avoid a recursive
1307 * disaster and not try to clean up after our own cleanup!
1311 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1312 td->td_pflags |= TDP_INBDFLUSH;
1314 td->td_pflags &= ~TDP_INBDFLUSH;
1320 * Set B_CACHE, indicating that the buffer is fully valid. This is
1321 * true even of NFS now.
1323 bp->b_flags |= B_CACHE;
1326 * This bmap keeps the system from needing to do the bmap later,
1327 * perhaps when the system is attempting to do a sync. Since it
1328 * is likely that the indirect block -- or whatever other datastructure
1329 * that the filesystem needs is still in memory now, it is a good
1330 * thing to do this. Note also, that if the pageout daemon is
1331 * requesting a sync -- there might not be enough memory to do
1332 * the bmap then... So, this is important to do.
1334 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1335 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1339 * Set the *dirty* buffer range based upon the VM system dirty
1342 * Mark the buffer pages as clean. We need to do this here to
1343 * satisfy the vnode_pager and the pageout daemon, so that it
1344 * thinks that the pages have been "cleaned". Note that since
1345 * the pages are in a delayed write buffer -- the VFS layer
1346 * "will" see that the pages get written out on the next sync,
1347 * or perhaps the cluster will be completed.
1349 vfs_clean_pages_dirty_buf(bp);
1353 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1354 * due to the softdep code.
1361 * Turn buffer into delayed write request. We must clear BIO_READ and
1362 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1363 * itself to properly update it in the dirty/clean lists. We mark it
1364 * B_DONE to ensure that any asynchronization of the buffer properly
1365 * clears B_DONE ( else a panic will occur later ).
1367 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1368 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1369 * should only be called if the buffer is known-good.
1371 * Since the buffer is not on a queue, we do not update the numfreebuffers
1374 * The buffer must be on QUEUE_NONE.
1377 bdirty(struct buf *bp)
1380 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1381 bp, bp->b_vp, bp->b_flags);
1382 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1383 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1384 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1385 BUF_ASSERT_HELD(bp);
1386 bp->b_flags &= ~(B_RELBUF);
1387 bp->b_iocmd = BIO_WRITE;
1389 if ((bp->b_flags & B_DELWRI) == 0) {
1390 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1399 * Clear B_DELWRI for buffer.
1401 * Since the buffer is not on a queue, we do not update the numfreebuffers
1404 * The buffer must be on QUEUE_NONE.
1408 bundirty(struct buf *bp)
1411 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1412 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1413 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1414 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1415 BUF_ASSERT_HELD(bp);
1417 if (bp->b_flags & B_DELWRI) {
1418 bp->b_flags &= ~B_DELWRI;
1423 * Since it is now being written, we can clear its deferred write flag.
1425 bp->b_flags &= ~B_DEFERRED;
1431 * Asynchronous write. Start output on a buffer, but do not wait for
1432 * it to complete. The buffer is released when the output completes.
1434 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1435 * B_INVAL buffers. Not us.
1438 bawrite(struct buf *bp)
1441 bp->b_flags |= B_ASYNC;
1448 * Asynchronous barrier write. Start output on a buffer, but do not
1449 * wait for it to complete. Place a write barrier after this write so
1450 * that this buffer and all buffers written before it are committed to
1451 * the disk before any buffers written after this write are committed
1452 * to the disk. The buffer is released when the output completes.
1455 babarrierwrite(struct buf *bp)
1458 bp->b_flags |= B_ASYNC | B_BARRIER;
1465 * Synchronous barrier write. Start output on a buffer and wait for
1466 * it to complete. Place a write barrier after this write so that
1467 * this buffer and all buffers written before it are committed to
1468 * the disk before any buffers written after this write are committed
1469 * to the disk. The buffer is released when the output completes.
1472 bbarrierwrite(struct buf *bp)
1475 bp->b_flags |= B_BARRIER;
1476 return (bwrite(bp));
1482 * Called prior to the locking of any vnodes when we are expecting to
1483 * write. We do not want to starve the buffer cache with too many
1484 * dirty buffers so we block here. By blocking prior to the locking
1485 * of any vnodes we attempt to avoid the situation where a locked vnode
1486 * prevents the various system daemons from flushing related buffers.
1492 if (numdirtybuffers >= hidirtybuffers) {
1493 mtx_lock(&bdirtylock);
1494 while (numdirtybuffers >= hidirtybuffers) {
1496 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
1499 mtx_unlock(&bdirtylock);
1504 * Return true if we have too many dirty buffers.
1507 buf_dirty_count_severe(void)
1510 return(numdirtybuffers >= hidirtybuffers);
1513 static __noinline int
1514 buf_vm_page_count_severe(void)
1517 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1519 return vm_page_count_severe();
1525 * Release a busy buffer and, if requested, free its resources. The
1526 * buffer will be stashed in the appropriate bufqueue[] allowing it
1527 * to be accessed later as a cache entity or reused for other purposes.
1530 brelse(struct buf *bp)
1534 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1535 bp, bp->b_vp, bp->b_flags);
1536 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1537 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1539 if (BUF_LOCKRECURSED(bp)) {
1541 * Do not process, in particular, do not handle the
1542 * B_INVAL/B_RELBUF and do not release to free list.
1548 if (bp->b_flags & B_MANAGED) {
1553 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1554 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1556 * Failed write, redirty. Must clear BIO_ERROR to prevent
1557 * pages from being scrapped. If the error is anything
1558 * other than an I/O error (EIO), assume that retrying
1561 bp->b_ioflags &= ~BIO_ERROR;
1563 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1564 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1566 * Either a failed I/O or we were asked to free or not
1569 bp->b_flags |= B_INVAL;
1570 if (!LIST_EMPTY(&bp->b_dep))
1572 if (bp->b_flags & B_DELWRI)
1574 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1575 if ((bp->b_flags & B_VMIO) == 0) {
1584 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1585 * is called with B_DELWRI set, the underlying pages may wind up
1586 * getting freed causing a previous write (bdwrite()) to get 'lost'
1587 * because pages associated with a B_DELWRI bp are marked clean.
1589 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1590 * if B_DELWRI is set.
1592 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1593 * on pages to return pages to the VM page queues.
1595 if (bp->b_flags & B_DELWRI)
1596 bp->b_flags &= ~B_RELBUF;
1597 else if (buf_vm_page_count_severe()) {
1599 * BKGRDINPROG can only be set with the buf and bufobj
1600 * locks both held. We tolerate a race to clear it here.
1602 if (!(bp->b_vflags & BV_BKGRDINPROG))
1603 bp->b_flags |= B_RELBUF;
1607 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1608 * constituted, not even NFS buffers now. Two flags effect this. If
1609 * B_INVAL, the struct buf is invalidated but the VM object is kept
1610 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1612 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1613 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1614 * buffer is also B_INVAL because it hits the re-dirtying code above.
1616 * Normally we can do this whether a buffer is B_DELWRI or not. If
1617 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1618 * the commit state and we cannot afford to lose the buffer. If the
1619 * buffer has a background write in progress, we need to keep it
1620 * around to prevent it from being reconstituted and starting a second
1623 if ((bp->b_flags & B_VMIO)
1624 && !(bp->b_vp->v_mount != NULL &&
1625 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1626 !vn_isdisk(bp->b_vp, NULL) &&
1627 (bp->b_flags & B_DELWRI))
1636 obj = bp->b_bufobj->bo_object;
1639 * Get the base offset and length of the buffer. Note that
1640 * in the VMIO case if the buffer block size is not
1641 * page-aligned then b_data pointer may not be page-aligned.
1642 * But our b_pages[] array *IS* page aligned.
1644 * block sizes less then DEV_BSIZE (usually 512) are not
1645 * supported due to the page granularity bits (m->valid,
1646 * m->dirty, etc...).
1648 * See man buf(9) for more information
1650 resid = bp->b_bufsize;
1651 foff = bp->b_offset;
1652 for (i = 0; i < bp->b_npages; i++) {
1658 * If we hit a bogus page, fixup *all* the bogus pages
1661 if (m == bogus_page) {
1662 poff = OFF_TO_IDX(bp->b_offset);
1665 VM_OBJECT_RLOCK(obj);
1666 for (j = i; j < bp->b_npages; j++) {
1668 mtmp = bp->b_pages[j];
1669 if (mtmp == bogus_page) {
1670 mtmp = vm_page_lookup(obj, poff + j);
1672 panic("brelse: page missing\n");
1674 bp->b_pages[j] = mtmp;
1677 VM_OBJECT_RUNLOCK(obj);
1679 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1680 BUF_CHECK_MAPPED(bp);
1682 trunc_page((vm_offset_t)bp->b_data),
1683 bp->b_pages, bp->b_npages);
1687 if ((bp->b_flags & B_NOCACHE) ||
1688 (bp->b_ioflags & BIO_ERROR &&
1689 bp->b_iocmd == BIO_READ)) {
1690 int poffset = foff & PAGE_MASK;
1691 int presid = resid > (PAGE_SIZE - poffset) ?
1692 (PAGE_SIZE - poffset) : resid;
1694 KASSERT(presid >= 0, ("brelse: extra page"));
1695 VM_OBJECT_WLOCK(obj);
1696 if (pmap_page_wired_mappings(m) == 0)
1697 vm_page_set_invalid(m, poffset, presid);
1698 VM_OBJECT_WUNLOCK(obj);
1700 printf("avoided corruption bug in bogus_page/brelse code\n");
1702 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1703 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1705 if (bp->b_flags & (B_INVAL | B_RELBUF))
1706 vfs_vmio_release(bp);
1708 } else if (bp->b_flags & B_VMIO) {
1710 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1711 vfs_vmio_release(bp);
1714 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1715 if (bp->b_bufsize != 0)
1717 if (bp->b_vp != NULL)
1722 * If the buffer has junk contents signal it and eventually
1723 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1726 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1727 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1728 bp->b_flags |= B_INVAL;
1729 if (bp->b_flags & B_INVAL) {
1730 if (bp->b_flags & B_DELWRI)
1736 /* buffers with no memory */
1737 if (bp->b_bufsize == 0) {
1738 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1739 if (bp->b_vflags & BV_BKGRDINPROG)
1740 panic("losing buffer 1");
1742 qindex = QUEUE_EMPTYKVA;
1744 qindex = QUEUE_EMPTY;
1745 bp->b_flags |= B_AGE;
1746 /* buffers with junk contents */
1747 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1748 (bp->b_ioflags & BIO_ERROR)) {
1749 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1750 if (bp->b_vflags & BV_BKGRDINPROG)
1751 panic("losing buffer 2");
1752 qindex = QUEUE_CLEAN;
1753 bp->b_flags |= B_AGE;
1754 /* remaining buffers */
1755 } else if (bp->b_flags & B_DELWRI)
1756 qindex = QUEUE_DIRTY;
1758 qindex = QUEUE_CLEAN;
1760 binsfree(bp, qindex);
1762 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1763 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1764 panic("brelse: not dirty");
1770 * Release a buffer back to the appropriate queue but do not try to free
1771 * it. The buffer is expected to be used again soon.
1773 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1774 * biodone() to requeue an async I/O on completion. It is also used when
1775 * known good buffers need to be requeued but we think we may need the data
1778 * XXX we should be able to leave the B_RELBUF hint set on completion.
1781 bqrelse(struct buf *bp)
1785 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1786 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1787 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1789 if (BUF_LOCKRECURSED(bp)) {
1790 /* do not release to free list */
1794 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1796 if (bp->b_flags & B_MANAGED) {
1797 if (bp->b_flags & B_REMFREE)
1802 /* buffers with stale but valid contents */
1803 if (bp->b_flags & B_DELWRI) {
1804 qindex = QUEUE_DIRTY;
1806 if ((bp->b_flags & B_DELWRI) == 0 &&
1807 (bp->b_xflags & BX_VNDIRTY))
1808 panic("bqrelse: not dirty");
1810 * BKGRDINPROG can only be set with the buf and bufobj
1811 * locks both held. We tolerate a race to clear it here.
1813 if (buf_vm_page_count_severe() &&
1814 (bp->b_vflags & BV_BKGRDINPROG) == 0) {
1816 * We are too low on memory, we have to try to free
1817 * the buffer (most importantly: the wired pages
1818 * making up its backing store) *now*.
1823 qindex = QUEUE_CLEAN;
1825 binsfree(bp, qindex);
1832 /* Give pages used by the bp back to the VM system (where possible) */
1834 vfs_vmio_release(struct buf *bp)
1839 if ((bp->b_flags & B_UNMAPPED) == 0) {
1840 BUF_CHECK_MAPPED(bp);
1841 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1843 BUF_CHECK_UNMAPPED(bp);
1844 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
1845 for (i = 0; i < bp->b_npages; i++) {
1847 bp->b_pages[i] = NULL;
1849 * In order to keep page LRU ordering consistent, put
1850 * everything on the inactive queue.
1853 vm_page_unwire(m, 0);
1856 * Might as well free the page if we can and it has
1857 * no valid data. We also free the page if the
1858 * buffer was used for direct I/O
1860 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1861 if (m->wire_count == 0 && !vm_page_busied(m))
1863 } else if (bp->b_flags & B_DIRECT)
1864 vm_page_try_to_free(m);
1865 else if (buf_vm_page_count_severe())
1866 vm_page_try_to_cache(m);
1869 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
1871 if (bp->b_bufsize) {
1876 bp->b_flags &= ~B_VMIO;
1882 * Check to see if a block at a particular lbn is available for a clustered
1886 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1893 /* If the buf isn't in core skip it */
1894 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1897 /* If the buf is busy we don't want to wait for it */
1898 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1901 /* Only cluster with valid clusterable delayed write buffers */
1902 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1903 (B_DELWRI | B_CLUSTEROK))
1906 if (bpa->b_bufsize != size)
1910 * Check to see if it is in the expected place on disk and that the
1911 * block has been mapped.
1913 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1923 * Implement clustered async writes for clearing out B_DELWRI buffers.
1924 * This is much better then the old way of writing only one buffer at
1925 * a time. Note that we may not be presented with the buffers in the
1926 * correct order, so we search for the cluster in both directions.
1929 vfs_bio_awrite(struct buf *bp)
1934 daddr_t lblkno = bp->b_lblkno;
1935 struct vnode *vp = bp->b_vp;
1943 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1945 * right now we support clustered writing only to regular files. If
1946 * we find a clusterable block we could be in the middle of a cluster
1947 * rather then at the beginning.
1949 if ((vp->v_type == VREG) &&
1950 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1951 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1953 size = vp->v_mount->mnt_stat.f_iosize;
1954 maxcl = MAXPHYS / size;
1957 for (i = 1; i < maxcl; i++)
1958 if (vfs_bio_clcheck(vp, size, lblkno + i,
1959 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1962 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1963 if (vfs_bio_clcheck(vp, size, lblkno - j,
1964 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1970 * this is a possible cluster write
1974 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
1980 bp->b_flags |= B_ASYNC;
1982 * default (old) behavior, writing out only one block
1984 * XXX returns b_bufsize instead of b_bcount for nwritten?
1986 nwritten = bp->b_bufsize;
1993 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
1996 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
1997 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
1998 if ((gbflags & GB_UNMAPPED) == 0) {
1999 bp->b_kvabase = (caddr_t)addr;
2000 } else if ((gbflags & GB_KVAALLOC) != 0) {
2001 KASSERT((gbflags & GB_UNMAPPED) != 0,
2002 ("GB_KVAALLOC without GB_UNMAPPED"));
2003 bp->b_kvaalloc = (caddr_t)addr;
2004 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2005 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2007 bp->b_kvasize = maxsize;
2011 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2015 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2022 if (vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr)) {
2024 * Buffer map is too fragmented. Request the caller
2025 * to defragment the map.
2027 atomic_add_int(&bufdefragcnt, 1);
2030 setbufkva(bp, addr, maxsize, gbflags);
2031 atomic_add_long(&bufspace, bp->b_kvasize);
2036 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2037 * locked vnode is supplied.
2040 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2045 int fl, flags, norunbuf;
2047 mtx_assert(&bqclean, MA_OWNED);
2050 flags = VFS_BIO_NEED_BUFSPACE;
2052 } else if (bufspace >= hibufspace) {
2054 flags = VFS_BIO_NEED_BUFSPACE;
2057 flags = VFS_BIO_NEED_ANY;
2060 needsbuffer |= flags;
2061 mtx_unlock(&nblock);
2062 mtx_unlock(&bqclean);
2064 bd_speedup(); /* heeeelp */
2065 if ((gbflags & GB_NOWAIT_BD) != 0)
2070 while (needsbuffer & flags) {
2071 if (vp != NULL && (td->td_pflags & TDP_BUFNEED) == 0) {
2072 mtx_unlock(&nblock);
2074 * getblk() is called with a vnode locked, and
2075 * some majority of the dirty buffers may as
2076 * well belong to the vnode. Flushing the
2077 * buffers there would make a progress that
2078 * cannot be achieved by the buf_daemon, that
2079 * cannot lock the vnode.
2081 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2082 (td->td_pflags & TDP_NORUNNINGBUF);
2083 /* play bufdaemon */
2084 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2085 fl = buf_flush(vp, flushbufqtarget);
2086 td->td_pflags &= norunbuf;
2090 if ((needsbuffer & flags) == 0)
2093 if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2097 mtx_unlock(&nblock);
2101 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2104 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2105 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2106 bp->b_kvasize, bp->b_bufsize, qindex);
2107 mtx_assert(&bqclean, MA_NOTOWNED);
2110 * Note: we no longer distinguish between VMIO and non-VMIO
2113 KASSERT((bp->b_flags & B_DELWRI) == 0,
2114 ("delwri buffer %p found in queue %d", bp, qindex));
2116 if (qindex == QUEUE_CLEAN) {
2117 if (bp->b_flags & B_VMIO) {
2118 bp->b_flags &= ~B_ASYNC;
2119 vfs_vmio_release(bp);
2121 if (bp->b_vp != NULL)
2126 * Get the rest of the buffer freed up. b_kva* is still valid
2127 * after this operation.
2130 if (bp->b_rcred != NOCRED) {
2131 crfree(bp->b_rcred);
2132 bp->b_rcred = NOCRED;
2134 if (bp->b_wcred != NOCRED) {
2135 crfree(bp->b_wcred);
2136 bp->b_wcred = NOCRED;
2138 if (!LIST_EMPTY(&bp->b_dep))
2140 if (bp->b_vflags & BV_BKGRDINPROG)
2141 panic("losing buffer 3");
2142 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2143 bp, bp->b_vp, qindex));
2144 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2145 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2150 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2153 KASSERT((bp->b_flags & B_INFREECNT) == 0,
2154 ("buf %p still counted as free?", bp));
2157 bp->b_blkno = bp->b_lblkno = 0;
2158 bp->b_offset = NOOFFSET;
2164 bp->b_dirtyoff = bp->b_dirtyend = 0;
2165 bp->b_bufobj = NULL;
2166 bp->b_pin_count = 0;
2167 bp->b_fsprivate1 = NULL;
2168 bp->b_fsprivate2 = NULL;
2169 bp->b_fsprivate3 = NULL;
2171 LIST_INIT(&bp->b_dep);
2174 static int flushingbufs;
2177 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2179 struct buf *bp, *nbp;
2180 int nqindex, qindex, pass;
2182 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2186 atomic_add_int(&getnewbufrestarts, 1);
2189 * Setup for scan. If we do not have enough free buffers,
2190 * we setup a degenerate case that immediately fails. Note
2191 * that if we are specially marked process, we are allowed to
2192 * dip into our reserves.
2194 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2195 * for the allocation of the mapped buffer. For unmapped, the
2196 * easiest is to start with EMPTY outright.
2198 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2199 * However, there are a number of cases (defragging, reusing, ...)
2200 * where we cannot backup.
2204 if (!defrag && unmapped) {
2205 nqindex = QUEUE_EMPTY;
2206 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2209 nqindex = QUEUE_EMPTYKVA;
2210 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2214 * If no EMPTYKVA buffers and we are either defragging or
2215 * reusing, locate a CLEAN buffer to free or reuse. If
2216 * bufspace useage is low skip this step so we can allocate a
2219 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2220 nqindex = QUEUE_CLEAN;
2221 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2225 * If we could not find or were not allowed to reuse a CLEAN
2226 * buffer, check to see if it is ok to use an EMPTY buffer.
2227 * We can only use an EMPTY buffer if allocating its KVA would
2228 * not otherwise run us out of buffer space. No KVA is needed
2229 * for the unmapped allocation.
2231 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2233 nqindex = QUEUE_EMPTY;
2234 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2238 * All available buffers might be clean, retry ignoring the
2239 * lobufspace as the last resort.
2241 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2242 nqindex = QUEUE_CLEAN;
2243 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2247 * Run scan, possibly freeing data and/or kva mappings on the fly
2250 while ((bp = nbp) != NULL) {
2254 * Calculate next bp (we can only use it if we do not
2255 * block or do other fancy things).
2257 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2260 nqindex = QUEUE_EMPTYKVA;
2261 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2265 case QUEUE_EMPTYKVA:
2266 nqindex = QUEUE_CLEAN;
2267 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2272 if (metadata && pass == 1) {
2274 nqindex = QUEUE_EMPTY;
2276 &bufqueues[QUEUE_EMPTY]);
2285 * If we are defragging then we need a buffer with
2286 * b_kvasize != 0. XXX this situation should no longer
2287 * occur, if defrag is non-zero the buffer's b_kvasize
2288 * should also be non-zero at this point. XXX
2290 if (defrag && bp->b_kvasize == 0) {
2291 printf("Warning: defrag empty buffer %p\n", bp);
2296 * Start freeing the bp. This is somewhat involved. nbp
2297 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2299 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2302 * BKGRDINPROG can only be set with the buf and bufobj
2303 * locks both held. We tolerate a race to clear it here.
2305 if (bp->b_vflags & BV_BKGRDINPROG) {
2310 KASSERT(bp->b_qindex == qindex,
2311 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2314 mtx_unlock(&bqclean);
2316 * NOTE: nbp is now entirely invalid. We can only restart
2317 * the scan from this point on.
2320 getnewbuf_reuse_bp(bp, qindex);
2321 mtx_assert(&bqclean, MA_NOTOWNED);
2324 * If we are defragging then free the buffer.
2327 bp->b_flags |= B_INVAL;
2335 * Notify any waiters for the buffer lock about
2336 * identity change by freeing the buffer.
2338 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2339 bp->b_flags |= B_INVAL;
2349 * If we are overcomitted then recover the buffer and its
2350 * KVM space. This occurs in rare situations when multiple
2351 * processes are blocked in getnewbuf() or allocbuf().
2353 if (bufspace >= hibufspace)
2355 if (flushingbufs && bp->b_kvasize != 0) {
2356 bp->b_flags |= B_INVAL;
2361 if (bufspace < lobufspace)
2371 * Find and initialize a new buffer header, freeing up existing buffers
2372 * in the bufqueues as necessary. The new buffer is returned locked.
2374 * Important: B_INVAL is not set. If the caller wishes to throw the
2375 * buffer away, the caller must set B_INVAL prior to calling brelse().
2378 * We have insufficient buffer headers
2379 * We have insufficient buffer space
2380 * buffer_arena is too fragmented ( space reservation fails )
2381 * If we have to flush dirty buffers ( but we try to avoid this )
2384 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2388 int defrag, metadata;
2390 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2391 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2392 if (!unmapped_buf_allowed)
2393 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2396 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2402 * We can't afford to block since we might be holding a vnode lock,
2403 * which may prevent system daemons from running. We deal with
2404 * low-memory situations by proactively returning memory and running
2405 * async I/O rather then sync I/O.
2407 atomic_add_int(&getnewbufcalls, 1);
2408 atomic_subtract_int(&getnewbufrestarts, 1);
2410 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2411 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2416 * If we exhausted our list, sleep as appropriate. We may have to
2417 * wakeup various daemons and write out some dirty buffers.
2419 * Generally we are sleeping due to insufficient buffer space.
2422 mtx_assert(&bqclean, MA_OWNED);
2423 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2424 mtx_assert(&bqclean, MA_NOTOWNED);
2425 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2426 mtx_assert(&bqclean, MA_NOTOWNED);
2429 bp->b_flags |= B_UNMAPPED;
2430 bp->b_kvabase = bp->b_data = unmapped_buf;
2431 bp->b_kvasize = maxsize;
2432 atomic_add_long(&bufspace, bp->b_kvasize);
2433 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2434 atomic_add_int(&bufreusecnt, 1);
2436 mtx_assert(&bqclean, MA_NOTOWNED);
2439 * We finally have a valid bp. We aren't quite out of the
2440 * woods, we still have to reserve kva space. In order
2441 * to keep fragmentation sane we only allocate kva in
2444 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2446 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2447 B_KVAALLOC)) == B_UNMAPPED) {
2448 if (allocbufkva(bp, maxsize, gbflags)) {
2450 bp->b_flags |= B_INVAL;
2454 atomic_add_int(&bufreusecnt, 1);
2455 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2456 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2458 * If the reused buffer has KVA allocated,
2459 * reassign b_kvaalloc to b_kvabase.
2461 bp->b_kvabase = bp->b_kvaalloc;
2462 bp->b_flags &= ~B_KVAALLOC;
2463 atomic_subtract_long(&unmapped_bufspace,
2465 atomic_add_int(&bufreusecnt, 1);
2466 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2467 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2470 * The case of reused buffer already have KVA
2471 * mapped, but the request is for unmapped
2472 * buffer with KVA allocated.
2474 bp->b_kvaalloc = bp->b_kvabase;
2475 bp->b_data = bp->b_kvabase = unmapped_buf;
2476 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2477 atomic_add_long(&unmapped_bufspace,
2479 atomic_add_int(&bufreusecnt, 1);
2481 if ((gbflags & GB_UNMAPPED) == 0) {
2482 bp->b_saveaddr = bp->b_kvabase;
2483 bp->b_data = bp->b_saveaddr;
2484 bp->b_flags &= ~B_UNMAPPED;
2485 BUF_CHECK_MAPPED(bp);
2494 * buffer flushing daemon. Buffers are normally flushed by the
2495 * update daemon but if it cannot keep up this process starts to
2496 * take the load in an attempt to prevent getnewbuf() from blocking.
2499 static struct kproc_desc buf_kp = {
2504 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2507 buf_flush(struct vnode *vp, int target)
2511 flushed = flushbufqueues(vp, target, 0);
2514 * Could not find any buffers without rollback
2515 * dependencies, so just write the first one
2516 * in the hopes of eventually making progress.
2518 if (vp != NULL && target > 2)
2520 flushbufqueues(vp, target, 1);
2531 * This process needs to be suspended prior to shutdown sync.
2533 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2537 * This process is allowed to take the buffer cache to the limit
2539 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2543 mtx_unlock(&bdlock);
2545 kproc_suspend_check(bufdaemonproc);
2546 lodirty = lodirtybuffers;
2547 if (bd_speedupreq) {
2548 lodirty = numdirtybuffers / 2;
2552 * Do the flush. Limit the amount of in-transit I/O we
2553 * allow to build up, otherwise we would completely saturate
2556 while (numdirtybuffers > lodirty) {
2557 if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
2559 kern_yield(PRI_USER);
2563 * Only clear bd_request if we have reached our low water
2564 * mark. The buf_daemon normally waits 1 second and
2565 * then incrementally flushes any dirty buffers that have
2566 * built up, within reason.
2568 * If we were unable to hit our low water mark and couldn't
2569 * find any flushable buffers, we sleep for a short period
2570 * to avoid endless loops on unlockable buffers.
2573 if (numdirtybuffers <= lodirtybuffers) {
2575 * We reached our low water mark, reset the
2576 * request and sleep until we are needed again.
2577 * The sleep is just so the suspend code works.
2581 * Do an extra wakeup in case dirty threshold
2582 * changed via sysctl and the explicit transition
2583 * out of shortfall was missed.
2586 if (runningbufspace <= lorunningspace)
2588 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2591 * We couldn't find any flushable dirty buffers but
2592 * still have too many dirty buffers, we
2593 * have to sleep and try again. (rare)
2595 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2603 * Try to flush a buffer in the dirty queue. We must be careful to
2604 * free up B_INVAL buffers instead of write them, which NFS is
2605 * particularly sensitive to.
2607 static int flushwithdeps = 0;
2608 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2609 0, "Number of buffers flushed with dependecies that require rollbacks");
2612 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
2614 struct buf *sentinel;
2623 queue = QUEUE_DIRTY;
2625 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2626 sentinel->b_qindex = QUEUE_SENTINEL;
2628 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2629 while (flushed != target) {
2630 bp = TAILQ_NEXT(sentinel, b_freelist);
2632 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2633 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2638 * Skip sentinels inserted by other invocations of the
2639 * flushbufqueues(), taking care to not reorder them.
2641 if (bp->b_qindex == QUEUE_SENTINEL)
2644 * Only flush the buffers that belong to the
2645 * vnode locked by the curthread.
2647 if (lvp != NULL && bp->b_vp != lvp)
2649 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2651 if (bp->b_pin_count > 0) {
2656 * BKGRDINPROG can only be set with the buf and bufobj
2657 * locks both held. We tolerate a race to clear it here.
2659 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2660 (bp->b_flags & B_DELWRI) == 0) {
2664 if (bp->b_flags & B_INVAL) {
2666 mtx_unlock(&bqdirty);
2673 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2674 if (flushdeps == 0) {
2682 * We must hold the lock on a vnode before writing
2683 * one of its buffers. Otherwise we may confuse, or
2684 * in the case of a snapshot vnode, deadlock the
2687 * The lock order here is the reverse of the normal
2688 * of vnode followed by buf lock. This is ok because
2689 * the NOWAIT will prevent deadlock.
2692 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2696 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_CANRECURSE) == 0) {
2697 mtx_unlock(&bqdirty);
2698 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2699 bp, bp->b_vp, bp->b_flags);
2700 if (curproc == bufdaemonproc)
2707 vn_finished_write(mp);
2709 flushwithdeps += hasdeps;
2713 * Sleeping on runningbufspace while holding
2714 * vnode lock leads to deadlock.
2716 if (curproc == bufdaemonproc &&
2717 runningbufspace > hirunningspace)
2718 waitrunningbufspace();
2722 vn_finished_write(mp);
2725 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2726 mtx_unlock(&bqdirty);
2727 free(sentinel, M_TEMP);
2732 * Check to see if a block is currently memory resident.
2735 incore(struct bufobj *bo, daddr_t blkno)
2740 bp = gbincore(bo, blkno);
2746 * Returns true if no I/O is needed to access the
2747 * associated VM object. This is like incore except
2748 * it also hunts around in the VM system for the data.
2752 inmem(struct vnode * vp, daddr_t blkno)
2755 vm_offset_t toff, tinc, size;
2759 ASSERT_VOP_LOCKED(vp, "inmem");
2761 if (incore(&vp->v_bufobj, blkno))
2763 if (vp->v_mount == NULL)
2770 if (size > vp->v_mount->mnt_stat.f_iosize)
2771 size = vp->v_mount->mnt_stat.f_iosize;
2772 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2774 VM_OBJECT_RLOCK(obj);
2775 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2776 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2780 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2781 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2782 if (vm_page_is_valid(m,
2783 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2786 VM_OBJECT_RUNLOCK(obj);
2790 VM_OBJECT_RUNLOCK(obj);
2795 * Set the dirty range for a buffer based on the status of the dirty
2796 * bits in the pages comprising the buffer. The range is limited
2797 * to the size of the buffer.
2799 * Tell the VM system that the pages associated with this buffer
2800 * are clean. This is used for delayed writes where the data is
2801 * going to go to disk eventually without additional VM intevention.
2803 * Note that while we only really need to clean through to b_bcount, we
2804 * just go ahead and clean through to b_bufsize.
2807 vfs_clean_pages_dirty_buf(struct buf *bp)
2809 vm_ooffset_t foff, noff, eoff;
2813 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2816 foff = bp->b_offset;
2817 KASSERT(bp->b_offset != NOOFFSET,
2818 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2820 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2821 vfs_drain_busy_pages(bp);
2822 vfs_setdirty_locked_object(bp);
2823 for (i = 0; i < bp->b_npages; i++) {
2824 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2826 if (eoff > bp->b_offset + bp->b_bufsize)
2827 eoff = bp->b_offset + bp->b_bufsize;
2829 vfs_page_set_validclean(bp, foff, m);
2830 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2833 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2837 vfs_setdirty_locked_object(struct buf *bp)
2842 object = bp->b_bufobj->bo_object;
2843 VM_OBJECT_ASSERT_WLOCKED(object);
2846 * We qualify the scan for modified pages on whether the
2847 * object has been flushed yet.
2849 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2850 vm_offset_t boffset;
2851 vm_offset_t eoffset;
2854 * test the pages to see if they have been modified directly
2855 * by users through the VM system.
2857 for (i = 0; i < bp->b_npages; i++)
2858 vm_page_test_dirty(bp->b_pages[i]);
2861 * Calculate the encompassing dirty range, boffset and eoffset,
2862 * (eoffset - boffset) bytes.
2865 for (i = 0; i < bp->b_npages; i++) {
2866 if (bp->b_pages[i]->dirty)
2869 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2871 for (i = bp->b_npages - 1; i >= 0; --i) {
2872 if (bp->b_pages[i]->dirty) {
2876 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2879 * Fit it to the buffer.
2882 if (eoffset > bp->b_bcount)
2883 eoffset = bp->b_bcount;
2886 * If we have a good dirty range, merge with the existing
2890 if (boffset < eoffset) {
2891 if (bp->b_dirtyoff > boffset)
2892 bp->b_dirtyoff = boffset;
2893 if (bp->b_dirtyend < eoffset)
2894 bp->b_dirtyend = eoffset;
2900 * Allocate the KVA mapping for an existing buffer. It handles the
2901 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2902 * KVA which is not mapped (B_KVAALLOC).
2905 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2907 struct buf *scratch_bp;
2908 int bsize, maxsize, need_mapping, need_kva;
2911 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2912 (gbflags & GB_UNMAPPED) == 0;
2913 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2914 (gbflags & GB_KVAALLOC) != 0;
2915 if (!need_mapping && !need_kva)
2918 BUF_CHECK_UNMAPPED(bp);
2920 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2922 * Buffer is not mapped, but the KVA was already
2923 * reserved at the time of the instantiation. Use the
2926 bp->b_flags &= ~B_KVAALLOC;
2927 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2928 bp->b_kvabase = bp->b_kvaalloc;
2929 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2934 * Calculate the amount of the address space we would reserve
2935 * if the buffer was mapped.
2937 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2938 offset = blkno * bsize;
2939 maxsize = size + (offset & PAGE_MASK);
2940 maxsize = imax(maxsize, bsize);
2943 if (allocbufkva(bp, maxsize, gbflags)) {
2945 * Request defragmentation. getnewbuf() returns us the
2946 * allocated space by the scratch buffer KVA.
2948 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2949 (GB_UNMAPPED | GB_KVAALLOC));
2950 if (scratch_bp == NULL) {
2951 if ((gbflags & GB_NOWAIT_BD) != 0) {
2953 * XXXKIB: defragmentation cannot
2954 * succeed, not sure what else to do.
2956 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
2958 atomic_add_int(&mappingrestarts, 1);
2961 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
2962 ("scratch bp !B_KVAALLOC %p", scratch_bp));
2963 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
2964 scratch_bp->b_kvasize, gbflags);
2966 /* Get rid of the scratch buffer. */
2967 scratch_bp->b_kvasize = 0;
2968 scratch_bp->b_flags |= B_INVAL;
2969 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
2976 bp->b_saveaddr = bp->b_kvabase;
2977 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
2978 bp->b_flags &= ~B_UNMAPPED;
2979 BUF_CHECK_MAPPED(bp);
2986 * Get a block given a specified block and offset into a file/device.
2987 * The buffers B_DONE bit will be cleared on return, making it almost
2988 * ready for an I/O initiation. B_INVAL may or may not be set on
2989 * return. The caller should clear B_INVAL prior to initiating a
2992 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2993 * an existing buffer.
2995 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2996 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2997 * and then cleared based on the backing VM. If the previous buffer is
2998 * non-0-sized but invalid, B_CACHE will be cleared.
3000 * If getblk() must create a new buffer, the new buffer is returned with
3001 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3002 * case it is returned with B_INVAL clear and B_CACHE set based on the
3005 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3006 * B_CACHE bit is clear.
3008 * What this means, basically, is that the caller should use B_CACHE to
3009 * determine whether the buffer is fully valid or not and should clear
3010 * B_INVAL prior to issuing a read. If the caller intends to validate
3011 * the buffer by loading its data area with something, the caller needs
3012 * to clear B_INVAL. If the caller does this without issuing an I/O,
3013 * the caller should set B_CACHE ( as an optimization ), else the caller
3014 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3015 * a write attempt or if it was a successfull read. If the caller
3016 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3017 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3020 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3025 int bsize, error, maxsize, vmio;
3028 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3029 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3030 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3031 ASSERT_VOP_LOCKED(vp, "getblk");
3032 if (size > MAXBSIZE)
3033 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
3034 if (!unmapped_buf_allowed)
3035 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3040 bp = gbincore(bo, blkno);
3044 * Buffer is in-core. If the buffer is not busy nor managed,
3045 * it must be on a queue.
3047 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3049 if (flags & GB_LOCK_NOWAIT)
3050 lockflags |= LK_NOWAIT;
3052 error = BUF_TIMELOCK(bp, lockflags,
3053 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3056 * If we slept and got the lock we have to restart in case
3057 * the buffer changed identities.
3059 if (error == ENOLCK)
3061 /* We timed out or were interrupted. */
3064 /* If recursed, assume caller knows the rules. */
3065 else if (BUF_LOCKRECURSED(bp))
3069 * The buffer is locked. B_CACHE is cleared if the buffer is
3070 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3071 * and for a VMIO buffer B_CACHE is adjusted according to the
3074 if (bp->b_flags & B_INVAL)
3075 bp->b_flags &= ~B_CACHE;
3076 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3077 bp->b_flags |= B_CACHE;
3078 if (bp->b_flags & B_MANAGED)
3079 MPASS(bp->b_qindex == QUEUE_NONE);
3084 * check for size inconsistencies for non-VMIO case.
3086 if (bp->b_bcount != size) {
3087 if ((bp->b_flags & B_VMIO) == 0 ||
3088 (size > bp->b_kvasize)) {
3089 if (bp->b_flags & B_DELWRI) {
3091 * If buffer is pinned and caller does
3092 * not want sleep waiting for it to be
3093 * unpinned, bail out
3095 if (bp->b_pin_count > 0) {
3096 if (flags & GB_LOCK_NOWAIT) {
3103 bp->b_flags |= B_NOCACHE;
3106 if (LIST_EMPTY(&bp->b_dep)) {
3107 bp->b_flags |= B_RELBUF;
3110 bp->b_flags |= B_NOCACHE;
3119 * Handle the case of unmapped buffer which should
3120 * become mapped, or the buffer for which KVA
3121 * reservation is requested.
3123 bp_unmapped_get_kva(bp, blkno, size, flags);
3126 * If the size is inconsistant in the VMIO case, we can resize
3127 * the buffer. This might lead to B_CACHE getting set or
3128 * cleared. If the size has not changed, B_CACHE remains
3129 * unchanged from its previous state.
3131 if (bp->b_bcount != size)
3134 KASSERT(bp->b_offset != NOOFFSET,
3135 ("getblk: no buffer offset"));
3138 * A buffer with B_DELWRI set and B_CACHE clear must
3139 * be committed before we can return the buffer in
3140 * order to prevent the caller from issuing a read
3141 * ( due to B_CACHE not being set ) and overwriting
3144 * Most callers, including NFS and FFS, need this to
3145 * operate properly either because they assume they
3146 * can issue a read if B_CACHE is not set, or because
3147 * ( for example ) an uncached B_DELWRI might loop due
3148 * to softupdates re-dirtying the buffer. In the latter
3149 * case, B_CACHE is set after the first write completes,
3150 * preventing further loops.
3151 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3152 * above while extending the buffer, we cannot allow the
3153 * buffer to remain with B_CACHE set after the write
3154 * completes or it will represent a corrupt state. To
3155 * deal with this we set B_NOCACHE to scrap the buffer
3158 * We might be able to do something fancy, like setting
3159 * B_CACHE in bwrite() except if B_DELWRI is already set,
3160 * so the below call doesn't set B_CACHE, but that gets real
3161 * confusing. This is much easier.
3164 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3165 bp->b_flags |= B_NOCACHE;
3169 bp->b_flags &= ~B_DONE;
3172 * Buffer is not in-core, create new buffer. The buffer
3173 * returned by getnewbuf() is locked. Note that the returned
3174 * buffer is also considered valid (not marked B_INVAL).
3178 * If the user does not want us to create the buffer, bail out
3181 if (flags & GB_NOCREAT)
3183 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3186 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3187 offset = blkno * bsize;
3188 vmio = vp->v_object != NULL;
3190 maxsize = size + (offset & PAGE_MASK);
3193 /* Do not allow non-VMIO notmapped buffers. */
3194 flags &= ~GB_UNMAPPED;
3196 maxsize = imax(maxsize, bsize);
3198 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3200 if (slpflag || slptimeo)
3206 * This code is used to make sure that a buffer is not
3207 * created while the getnewbuf routine is blocked.
3208 * This can be a problem whether the vnode is locked or not.
3209 * If the buffer is created out from under us, we have to
3210 * throw away the one we just created.
3212 * Note: this must occur before we associate the buffer
3213 * with the vp especially considering limitations in
3214 * the splay tree implementation when dealing with duplicate
3218 if (gbincore(bo, blkno)) {
3220 bp->b_flags |= B_INVAL;
3226 * Insert the buffer into the hash, so that it can
3227 * be found by incore.
3229 bp->b_blkno = bp->b_lblkno = blkno;
3230 bp->b_offset = offset;
3235 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3236 * buffer size starts out as 0, B_CACHE will be set by
3237 * allocbuf() for the VMIO case prior to it testing the
3238 * backing store for validity.
3242 bp->b_flags |= B_VMIO;
3243 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3244 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3245 bp, vp->v_object, bp->b_bufobj->bo_object));
3247 bp->b_flags &= ~B_VMIO;
3248 KASSERT(bp->b_bufobj->bo_object == NULL,
3249 ("ARGH! has b_bufobj->bo_object %p %p\n",
3250 bp, bp->b_bufobj->bo_object));
3251 BUF_CHECK_MAPPED(bp);
3255 bp->b_flags &= ~B_DONE;
3257 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3258 BUF_ASSERT_HELD(bp);
3260 KASSERT(bp->b_bufobj == bo,
3261 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3266 * Get an empty, disassociated buffer of given size. The buffer is initially
3270 geteblk(int size, int flags)
3275 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3276 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3277 if ((flags & GB_NOWAIT_BD) &&
3278 (curthread->td_pflags & TDP_BUFNEED) != 0)
3282 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3283 BUF_ASSERT_HELD(bp);
3289 * This code constitutes the buffer memory from either anonymous system
3290 * memory (in the case of non-VMIO operations) or from an associated
3291 * VM object (in the case of VMIO operations). This code is able to
3292 * resize a buffer up or down.
3294 * Note that this code is tricky, and has many complications to resolve
3295 * deadlock or inconsistant data situations. Tread lightly!!!
3296 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3297 * the caller. Calling this code willy nilly can result in the loss of data.
3299 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3300 * B_CACHE for the non-VMIO case.
3304 allocbuf(struct buf *bp, int size)
3306 int newbsize, mbsize;
3309 BUF_ASSERT_HELD(bp);
3311 if (bp->b_kvasize < size)
3312 panic("allocbuf: buffer too small");
3314 if ((bp->b_flags & B_VMIO) == 0) {
3318 * Just get anonymous memory from the kernel. Don't
3319 * mess with B_CACHE.
3321 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3322 if (bp->b_flags & B_MALLOC)
3325 newbsize = round_page(size);
3327 if (newbsize < bp->b_bufsize) {
3329 * malloced buffers are not shrunk
3331 if (bp->b_flags & B_MALLOC) {
3333 bp->b_bcount = size;
3335 free(bp->b_data, M_BIOBUF);
3336 if (bp->b_bufsize) {
3337 atomic_subtract_long(
3343 bp->b_saveaddr = bp->b_kvabase;
3344 bp->b_data = bp->b_saveaddr;
3346 bp->b_flags &= ~B_MALLOC;
3350 vm_hold_free_pages(bp, newbsize);
3351 } else if (newbsize > bp->b_bufsize) {
3353 * We only use malloced memory on the first allocation.
3354 * and revert to page-allocated memory when the buffer
3358 * There is a potential smp race here that could lead
3359 * to bufmallocspace slightly passing the max. It
3360 * is probably extremely rare and not worth worrying
3363 if ( (bufmallocspace < maxbufmallocspace) &&
3364 (bp->b_bufsize == 0) &&
3365 (mbsize <= PAGE_SIZE/2)) {
3367 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3368 bp->b_bufsize = mbsize;
3369 bp->b_bcount = size;
3370 bp->b_flags |= B_MALLOC;
3371 atomic_add_long(&bufmallocspace, mbsize);
3377 * If the buffer is growing on its other-than-first allocation,
3378 * then we revert to the page-allocation scheme.
3380 if (bp->b_flags & B_MALLOC) {
3381 origbuf = bp->b_data;
3382 origbufsize = bp->b_bufsize;
3383 bp->b_data = bp->b_kvabase;
3384 if (bp->b_bufsize) {
3385 atomic_subtract_long(&bufmallocspace,
3390 bp->b_flags &= ~B_MALLOC;
3391 newbsize = round_page(newbsize);
3395 (vm_offset_t) bp->b_data + bp->b_bufsize,
3396 (vm_offset_t) bp->b_data + newbsize);
3398 bcopy(origbuf, bp->b_data, origbufsize);
3399 free(origbuf, M_BIOBUF);
3405 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3406 desiredpages = (size == 0) ? 0 :
3407 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3409 if (bp->b_flags & B_MALLOC)
3410 panic("allocbuf: VMIO buffer can't be malloced");
3412 * Set B_CACHE initially if buffer is 0 length or will become
3415 if (size == 0 || bp->b_bufsize == 0)
3416 bp->b_flags |= B_CACHE;
3418 if (newbsize < bp->b_bufsize) {
3420 * DEV_BSIZE aligned new buffer size is less then the
3421 * DEV_BSIZE aligned existing buffer size. Figure out
3422 * if we have to remove any pages.
3424 if (desiredpages < bp->b_npages) {
3427 if ((bp->b_flags & B_UNMAPPED) == 0) {
3428 BUF_CHECK_MAPPED(bp);
3429 pmap_qremove((vm_offset_t)trunc_page(
3430 (vm_offset_t)bp->b_data) +
3431 (desiredpages << PAGE_SHIFT),
3432 (bp->b_npages - desiredpages));
3434 BUF_CHECK_UNMAPPED(bp);
3435 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3436 for (i = desiredpages; i < bp->b_npages; i++) {
3438 * the page is not freed here -- it
3439 * is the responsibility of
3440 * vnode_pager_setsize
3443 KASSERT(m != bogus_page,
3444 ("allocbuf: bogus page found"));
3445 while (vm_page_sleep_if_busy(m,
3449 bp->b_pages[i] = NULL;
3451 vm_page_unwire(m, 0);
3454 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3455 bp->b_npages = desiredpages;
3457 } else if (size > bp->b_bcount) {
3459 * We are growing the buffer, possibly in a
3460 * byte-granular fashion.
3467 * Step 1, bring in the VM pages from the object,
3468 * allocating them if necessary. We must clear
3469 * B_CACHE if these pages are not valid for the
3470 * range covered by the buffer.
3473 obj = bp->b_bufobj->bo_object;
3475 VM_OBJECT_WLOCK(obj);
3476 while (bp->b_npages < desiredpages) {
3480 * We must allocate system pages since blocking
3481 * here could interfere with paging I/O, no
3482 * matter which process we are.
3484 * Only exclusive busy can be tested here.
3485 * Blocking on shared busy might lead to
3486 * deadlocks once allocbuf() is called after
3487 * pages are vfs_busy_pages().
3489 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3490 bp->b_npages, VM_ALLOC_NOBUSY |
3491 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3492 VM_ALLOC_IGN_SBUSY |
3493 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3495 bp->b_flags &= ~B_CACHE;
3496 bp->b_pages[bp->b_npages] = m;
3501 * Step 2. We've loaded the pages into the buffer,
3502 * we have to figure out if we can still have B_CACHE
3503 * set. Note that B_CACHE is set according to the
3504 * byte-granular range ( bcount and size ), new the
3505 * aligned range ( newbsize ).
3507 * The VM test is against m->valid, which is DEV_BSIZE
3508 * aligned. Needless to say, the validity of the data
3509 * needs to also be DEV_BSIZE aligned. Note that this
3510 * fails with NFS if the server or some other client
3511 * extends the file's EOF. If our buffer is resized,
3512 * B_CACHE may remain set! XXX
3515 toff = bp->b_bcount;
3516 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3518 while ((bp->b_flags & B_CACHE) && toff < size) {
3521 if (tinc > (size - toff))
3524 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3537 VM_OBJECT_WUNLOCK(obj);
3540 * Step 3, fixup the KVM pmap.
3542 if ((bp->b_flags & B_UNMAPPED) == 0)
3545 BUF_CHECK_UNMAPPED(bp);
3548 if (newbsize < bp->b_bufsize)
3550 bp->b_bufsize = newbsize; /* actual buffer allocation */
3551 bp->b_bcount = size; /* requested buffer size */
3555 extern int inflight_transient_maps;
3558 biodone(struct bio *bp)
3561 void (*done)(struct bio *);
3562 vm_offset_t start, end;
3565 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3567 bp->bio_flags |= BIO_DONE;
3568 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3569 start = trunc_page((vm_offset_t)bp->bio_data);
3570 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3576 done = bp->bio_done;
3583 pmap_qremove(start, OFF_TO_IDX(end - start));
3584 vmem_free(transient_arena, start, end - start);
3585 atomic_add_int(&inflight_transient_maps, -1);
3590 * Wait for a BIO to finish.
3592 * XXX: resort to a timeout for now. The optimal locking (if any) for this
3593 * case is not yet clear.
3596 biowait(struct bio *bp, const char *wchan)
3600 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3602 while ((bp->bio_flags & BIO_DONE) == 0)
3603 msleep(bp, mtxp, PRIBIO, wchan, hz / 10);
3605 if (bp->bio_error != 0)
3606 return (bp->bio_error);
3607 if (!(bp->bio_flags & BIO_ERROR))
3613 biofinish(struct bio *bp, struct devstat *stat, int error)
3617 bp->bio_error = error;
3618 bp->bio_flags |= BIO_ERROR;
3621 devstat_end_transaction_bio(stat, bp);
3628 * Wait for buffer I/O completion, returning error status. The buffer
3629 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3630 * error and cleared.
3633 bufwait(struct buf *bp)
3635 if (bp->b_iocmd == BIO_READ)
3636 bwait(bp, PRIBIO, "biord");
3638 bwait(bp, PRIBIO, "biowr");
3639 if (bp->b_flags & B_EINTR) {
3640 bp->b_flags &= ~B_EINTR;
3643 if (bp->b_ioflags & BIO_ERROR) {
3644 return (bp->b_error ? bp->b_error : EIO);
3651 * Call back function from struct bio back up to struct buf.
3654 bufdonebio(struct bio *bip)
3658 bp = bip->bio_caller2;
3659 bp->b_resid = bp->b_bcount - bip->bio_completed;
3660 bp->b_resid = bip->bio_resid; /* XXX: remove */
3661 bp->b_ioflags = bip->bio_flags;
3662 bp->b_error = bip->bio_error;
3664 bp->b_ioflags |= BIO_ERROR;
3670 dev_strategy(struct cdev *dev, struct buf *bp)
3675 KASSERT(dev->si_refcount > 0,
3676 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3677 devtoname(dev), dev));
3679 csw = dev_refthread(dev, &ref);
3680 dev_strategy_csw(dev, csw, bp);
3681 dev_relthread(dev, ref);
3685 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3689 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3691 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3692 dev->si_threadcount > 0,
3693 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3696 bp->b_error = ENXIO;
3697 bp->b_ioflags = BIO_ERROR;
3705 /* Try again later */
3706 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3708 bip->bio_cmd = bp->b_iocmd;
3709 bip->bio_offset = bp->b_iooffset;
3710 bip->bio_length = bp->b_bcount;
3711 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3713 bip->bio_done = bufdonebio;
3714 bip->bio_caller2 = bp;
3716 (*csw->d_strategy)(bip);
3722 * Finish I/O on a buffer, optionally calling a completion function.
3723 * This is usually called from an interrupt so process blocking is
3726 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3727 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3728 * assuming B_INVAL is clear.
3730 * For the VMIO case, we set B_CACHE if the op was a read and no
3731 * read error occured, or if the op was a write. B_CACHE is never
3732 * set if the buffer is invalid or otherwise uncacheable.
3734 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3735 * initiator to leave B_INVAL set to brelse the buffer out of existance
3736 * in the biodone routine.
3739 bufdone(struct buf *bp)
3741 struct bufobj *dropobj;
3742 void (*biodone)(struct buf *);
3744 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3747 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3748 BUF_ASSERT_HELD(bp);
3750 runningbufwakeup(bp);
3751 if (bp->b_iocmd == BIO_WRITE)
3752 dropobj = bp->b_bufobj;
3753 /* call optional completion function if requested */
3754 if (bp->b_iodone != NULL) {
3755 biodone = bp->b_iodone;
3756 bp->b_iodone = NULL;
3759 bufobj_wdrop(dropobj);
3766 bufobj_wdrop(dropobj);
3770 bufdone_finish(struct buf *bp)
3772 BUF_ASSERT_HELD(bp);
3774 if (!LIST_EMPTY(&bp->b_dep))
3777 if (bp->b_flags & B_VMIO) {
3782 int bogus, i, iosize;
3784 obj = bp->b_bufobj->bo_object;
3785 KASSERT(obj->paging_in_progress >= bp->b_npages,
3786 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3787 obj->paging_in_progress, bp->b_npages));
3790 KASSERT(vp->v_holdcnt > 0,
3791 ("biodone_finish: vnode %p has zero hold count", vp));
3792 KASSERT(vp->v_object != NULL,
3793 ("biodone_finish: vnode %p has no vm_object", vp));
3795 foff = bp->b_offset;
3796 KASSERT(bp->b_offset != NOOFFSET,
3797 ("biodone_finish: bp %p has no buffer offset", bp));
3800 * Set B_CACHE if the op was a normal read and no error
3801 * occured. B_CACHE is set for writes in the b*write()
3804 iosize = bp->b_bcount - bp->b_resid;
3805 if (bp->b_iocmd == BIO_READ &&
3806 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3807 !(bp->b_ioflags & BIO_ERROR)) {
3808 bp->b_flags |= B_CACHE;
3811 VM_OBJECT_WLOCK(obj);
3812 for (i = 0; i < bp->b_npages; i++) {
3816 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3821 * cleanup bogus pages, restoring the originals
3824 if (m == bogus_page) {
3825 bogus = bogusflag = 1;
3826 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3828 panic("biodone: page disappeared!");
3831 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3832 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3833 (intmax_t)foff, (uintmax_t)m->pindex));
3836 * In the write case, the valid and clean bits are
3837 * already changed correctly ( see bdwrite() ), so we
3838 * only need to do this here in the read case.
3840 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3841 KASSERT((m->dirty & vm_page_bits(foff &
3842 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3843 " page %p has unexpected dirty bits", m));
3844 vfs_page_set_valid(bp, foff, m);
3848 vm_object_pip_subtract(obj, 1);
3849 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3852 vm_object_pip_wakeupn(obj, 0);
3853 VM_OBJECT_WUNLOCK(obj);
3854 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3855 BUF_CHECK_MAPPED(bp);
3856 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3857 bp->b_pages, bp->b_npages);
3862 * For asynchronous completions, release the buffer now. The brelse
3863 * will do a wakeup there if necessary - so no need to do a wakeup
3864 * here in the async case. The sync case always needs to do a wakeup.
3867 if (bp->b_flags & B_ASYNC) {
3868 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3877 * This routine is called in lieu of iodone in the case of
3878 * incomplete I/O. This keeps the busy status for pages
3882 vfs_unbusy_pages(struct buf *bp)
3888 runningbufwakeup(bp);
3889 if (!(bp->b_flags & B_VMIO))
3892 obj = bp->b_bufobj->bo_object;
3893 VM_OBJECT_WLOCK(obj);
3894 for (i = 0; i < bp->b_npages; i++) {
3896 if (m == bogus_page) {
3897 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3899 panic("vfs_unbusy_pages: page missing\n");
3901 if ((bp->b_flags & B_UNMAPPED) == 0) {
3902 BUF_CHECK_MAPPED(bp);
3903 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3904 bp->b_pages, bp->b_npages);
3906 BUF_CHECK_UNMAPPED(bp);
3908 vm_object_pip_subtract(obj, 1);
3911 vm_object_pip_wakeupn(obj, 0);
3912 VM_OBJECT_WUNLOCK(obj);
3916 * vfs_page_set_valid:
3918 * Set the valid bits in a page based on the supplied offset. The
3919 * range is restricted to the buffer's size.
3921 * This routine is typically called after a read completes.
3924 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3929 * Compute the end offset, eoff, such that [off, eoff) does not span a
3930 * page boundary and eoff is not greater than the end of the buffer.
3931 * The end of the buffer, in this case, is our file EOF, not the
3932 * allocation size of the buffer.
3934 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3935 if (eoff > bp->b_offset + bp->b_bcount)
3936 eoff = bp->b_offset + bp->b_bcount;
3939 * Set valid range. This is typically the entire buffer and thus the
3943 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3947 * vfs_page_set_validclean:
3949 * Set the valid bits and clear the dirty bits in a page based on the
3950 * supplied offset. The range is restricted to the buffer's size.
3953 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3955 vm_ooffset_t soff, eoff;
3958 * Start and end offsets in buffer. eoff - soff may not cross a
3959 * page boundry or cross the end of the buffer. The end of the
3960 * buffer, in this case, is our file EOF, not the allocation size
3964 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3965 if (eoff > bp->b_offset + bp->b_bcount)
3966 eoff = bp->b_offset + bp->b_bcount;
3969 * Set valid range. This is typically the entire buffer and thus the
3973 vm_page_set_validclean(
3975 (vm_offset_t) (soff & PAGE_MASK),
3976 (vm_offset_t) (eoff - soff)
3982 * Ensure that all buffer pages are not exclusive busied. If any page is
3983 * exclusive busy, drain it.
3986 vfs_drain_busy_pages(struct buf *bp)
3991 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
3993 for (i = 0; i < bp->b_npages; i++) {
3995 if (vm_page_xbusied(m)) {
3996 for (; last_busied < i; last_busied++)
3997 vm_page_sbusy(bp->b_pages[last_busied]);
3998 while (vm_page_xbusied(m)) {
4000 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4001 vm_page_busy_sleep(m, "vbpage");
4002 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4006 for (i = 0; i < last_busied; i++)
4007 vm_page_sunbusy(bp->b_pages[i]);
4011 * This routine is called before a device strategy routine.
4012 * It is used to tell the VM system that paging I/O is in
4013 * progress, and treat the pages associated with the buffer
4014 * almost as being exclusive busy. Also the object paging_in_progress
4015 * flag is handled to make sure that the object doesn't become
4018 * Since I/O has not been initiated yet, certain buffer flags
4019 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4020 * and should be ignored.
4023 vfs_busy_pages(struct buf *bp, int clear_modify)
4030 if (!(bp->b_flags & B_VMIO))
4033 obj = bp->b_bufobj->bo_object;
4034 foff = bp->b_offset;
4035 KASSERT(bp->b_offset != NOOFFSET,
4036 ("vfs_busy_pages: no buffer offset"));
4037 VM_OBJECT_WLOCK(obj);
4038 vfs_drain_busy_pages(bp);
4039 if (bp->b_bufsize != 0)
4040 vfs_setdirty_locked_object(bp);
4042 for (i = 0; i < bp->b_npages; i++) {
4045 if ((bp->b_flags & B_CLUSTER) == 0) {
4046 vm_object_pip_add(obj, 1);
4050 * When readying a buffer for a read ( i.e
4051 * clear_modify == 0 ), it is important to do
4052 * bogus_page replacement for valid pages in
4053 * partially instantiated buffers. Partially
4054 * instantiated buffers can, in turn, occur when
4055 * reconstituting a buffer from its VM backing store
4056 * base. We only have to do this if B_CACHE is
4057 * clear ( which causes the I/O to occur in the
4058 * first place ). The replacement prevents the read
4059 * I/O from overwriting potentially dirty VM-backed
4060 * pages. XXX bogus page replacement is, uh, bogus.
4061 * It may not work properly with small-block devices.
4062 * We need to find a better way.
4065 pmap_remove_write(m);
4066 vfs_page_set_validclean(bp, foff, m);
4067 } else if (m->valid == VM_PAGE_BITS_ALL &&
4068 (bp->b_flags & B_CACHE) == 0) {
4069 bp->b_pages[i] = bogus_page;
4072 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4074 VM_OBJECT_WUNLOCK(obj);
4075 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4076 BUF_CHECK_MAPPED(bp);
4077 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4078 bp->b_pages, bp->b_npages);
4083 * vfs_bio_set_valid:
4085 * Set the range within the buffer to valid. The range is
4086 * relative to the beginning of the buffer, b_offset. Note that
4087 * b_offset itself may be offset from the beginning of the first
4091 vfs_bio_set_valid(struct buf *bp, int base, int size)
4096 if (!(bp->b_flags & B_VMIO))
4100 * Fixup base to be relative to beginning of first page.
4101 * Set initial n to be the maximum number of bytes in the
4102 * first page that can be validated.
4104 base += (bp->b_offset & PAGE_MASK);
4105 n = PAGE_SIZE - (base & PAGE_MASK);
4107 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4108 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4112 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4117 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4123 * If the specified buffer is a non-VMIO buffer, clear the entire
4124 * buffer. If the specified buffer is a VMIO buffer, clear and
4125 * validate only the previously invalid portions of the buffer.
4126 * This routine essentially fakes an I/O, so we need to clear
4127 * BIO_ERROR and B_INVAL.
4129 * Note that while we only theoretically need to clear through b_bcount,
4130 * we go ahead and clear through b_bufsize.
4133 vfs_bio_clrbuf(struct buf *bp)
4135 int i, j, mask, sa, ea, slide;
4137 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4141 bp->b_flags &= ~B_INVAL;
4142 bp->b_ioflags &= ~BIO_ERROR;
4143 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4144 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4145 (bp->b_offset & PAGE_MASK) == 0) {
4146 if (bp->b_pages[0] == bogus_page)
4148 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4149 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4150 if ((bp->b_pages[0]->valid & mask) == mask)
4152 if ((bp->b_pages[0]->valid & mask) == 0) {
4153 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4154 bp->b_pages[0]->valid |= mask;
4158 sa = bp->b_offset & PAGE_MASK;
4160 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4161 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4162 ea = slide & PAGE_MASK;
4165 if (bp->b_pages[i] == bogus_page)
4168 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4169 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4170 if ((bp->b_pages[i]->valid & mask) == mask)
4172 if ((bp->b_pages[i]->valid & mask) == 0)
4173 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4175 for (; sa < ea; sa += DEV_BSIZE, j++) {
4176 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4177 pmap_zero_page_area(bp->b_pages[i],
4182 bp->b_pages[i]->valid |= mask;
4185 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4190 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4195 if ((bp->b_flags & B_UNMAPPED) == 0) {
4196 BUF_CHECK_MAPPED(bp);
4197 bzero(bp->b_data + base, size);
4199 BUF_CHECK_UNMAPPED(bp);
4200 n = PAGE_SIZE - (base & PAGE_MASK);
4201 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4205 pmap_zero_page_area(m, base & PAGE_MASK, n);
4214 * vm_hold_load_pages and vm_hold_free_pages get pages into
4215 * a buffers address space. The pages are anonymous and are
4216 * not associated with a file object.
4219 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4225 BUF_CHECK_MAPPED(bp);
4227 to = round_page(to);
4228 from = round_page(from);
4229 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4231 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4234 * note: must allocate system pages since blocking here
4235 * could interfere with paging I/O, no matter which
4238 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4239 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4244 pmap_qenter(pg, &p, 1);
4245 bp->b_pages[index] = p;
4247 bp->b_npages = index;
4250 /* Return pages associated with this buf to the vm system */
4252 vm_hold_free_pages(struct buf *bp, int newbsize)
4256 int index, newnpages;
4258 BUF_CHECK_MAPPED(bp);
4260 from = round_page((vm_offset_t)bp->b_data + newbsize);
4261 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4262 if (bp->b_npages > newnpages)
4263 pmap_qremove(from, bp->b_npages - newnpages);
4264 for (index = newnpages; index < bp->b_npages; index++) {
4265 p = bp->b_pages[index];
4266 bp->b_pages[index] = NULL;
4267 if (vm_page_sbusied(p))
4268 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4269 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4272 atomic_subtract_int(&cnt.v_wire_count, 1);
4274 bp->b_npages = newnpages;
4278 * Map an IO request into kernel virtual address space.
4280 * All requests are (re)mapped into kernel VA space.
4281 * Notice that we use b_bufsize for the size of the buffer
4282 * to be mapped. b_bcount might be modified by the driver.
4284 * Note that even if the caller determines that the address space should
4285 * be valid, a race or a smaller-file mapped into a larger space may
4286 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4287 * check the return value.
4290 vmapbuf(struct buf *bp, int mapbuf)
4296 if (bp->b_bufsize < 0)
4298 prot = VM_PROT_READ;
4299 if (bp->b_iocmd == BIO_READ)
4300 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4301 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4302 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4303 btoc(MAXPHYS))) < 0)
4305 bp->b_npages = pidx;
4306 if (mapbuf || !unmapped_buf_allowed) {
4307 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4308 kva = bp->b_saveaddr;
4309 bp->b_saveaddr = bp->b_data;
4310 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4311 bp->b_flags &= ~B_UNMAPPED;
4313 bp->b_flags |= B_UNMAPPED;
4314 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4315 bp->b_saveaddr = bp->b_data;
4316 bp->b_data = unmapped_buf;
4322 * Free the io map PTEs associated with this IO operation.
4323 * We also invalidate the TLB entries and restore the original b_addr.
4326 vunmapbuf(struct buf *bp)
4330 npages = bp->b_npages;
4331 if (bp->b_flags & B_UNMAPPED)
4332 bp->b_flags &= ~B_UNMAPPED;
4334 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4335 vm_page_unhold_pages(bp->b_pages, npages);
4337 bp->b_data = bp->b_saveaddr;
4341 bdone(struct buf *bp)
4345 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4347 bp->b_flags |= B_DONE;
4353 bwait(struct buf *bp, u_char pri, const char *wchan)
4357 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4359 while ((bp->b_flags & B_DONE) == 0)
4360 msleep(bp, mtxp, pri, wchan, 0);
4365 bufsync(struct bufobj *bo, int waitfor)
4368 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4372 bufstrategy(struct bufobj *bo, struct buf *bp)
4378 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4379 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4380 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4381 i = VOP_STRATEGY(vp, bp);
4382 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4386 bufobj_wrefl(struct bufobj *bo)
4389 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4390 ASSERT_BO_WLOCKED(bo);
4395 bufobj_wref(struct bufobj *bo)
4398 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4405 bufobj_wdrop(struct bufobj *bo)
4408 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4410 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4411 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4412 bo->bo_flag &= ~BO_WWAIT;
4413 wakeup(&bo->bo_numoutput);
4419 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4423 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4424 ASSERT_BO_WLOCKED(bo);
4426 while (bo->bo_numoutput) {
4427 bo->bo_flag |= BO_WWAIT;
4428 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4429 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4437 bpin(struct buf *bp)
4441 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4448 bunpin(struct buf *bp)
4452 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4454 if (--bp->b_pin_count == 0)
4460 bunpin_wait(struct buf *bp)
4464 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4466 while (bp->b_pin_count > 0)
4467 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4472 * Set bio_data or bio_ma for struct bio from the struct buf.
4475 bdata2bio(struct buf *bp, struct bio *bip)
4478 if ((bp->b_flags & B_UNMAPPED) != 0) {
4479 KASSERT(unmapped_buf_allowed, ("unmapped"));
4480 bip->bio_ma = bp->b_pages;
4481 bip->bio_ma_n = bp->b_npages;
4482 bip->bio_data = unmapped_buf;
4483 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4484 bip->bio_flags |= BIO_UNMAPPED;
4485 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4486 PAGE_SIZE == bp->b_npages,
4487 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4488 (long long)bip->bio_length, bip->bio_ma_n));
4490 bip->bio_data = bp->b_data;
4495 #include "opt_ddb.h"
4497 #include <ddb/ddb.h>
4499 /* DDB command to show buffer data */
4500 DB_SHOW_COMMAND(buffer, db_show_buffer)
4503 struct buf *bp = (struct buf *)addr;
4506 db_printf("usage: show buffer <addr>\n");
4510 db_printf("buf at %p\n", bp);
4511 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4512 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4513 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4515 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4516 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4518 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4519 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4520 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4523 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4524 for (i = 0; i < bp->b_npages; i++) {
4527 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4528 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4529 if ((i + 1) < bp->b_npages)
4535 BUF_LOCKPRINTINFO(bp);
4538 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4543 for (i = 0; i < nbuf; i++) {
4545 if (BUF_ISLOCKED(bp)) {
4546 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4552 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4558 db_printf("usage: show vnodebufs <addr>\n");
4561 vp = (struct vnode *)addr;
4562 db_printf("Clean buffers:\n");
4563 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4564 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4567 db_printf("Dirty buffers:\n");
4568 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4569 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4574 DB_COMMAND(countfreebufs, db_coundfreebufs)
4577 int i, used = 0, nfree = 0;
4580 db_printf("usage: countfreebufs\n");
4584 for (i = 0; i < nbuf; i++) {
4586 if ((bp->b_flags & B_INFREECNT) != 0)
4592 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4594 db_printf("numfreebuffers is %d\n", numfreebuffers);