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"
82 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
84 struct bio_ops bioops; /* I/O operation notification */
86 struct buf_ops buf_ops_bio = {
87 .bop_name = "buf_ops_bio",
88 .bop_write = bufwrite,
89 .bop_strategy = bufstrategy,
91 .bop_bdflush = bufbdflush,
95 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
96 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c.
98 struct buf *buf; /* buffer header pool */
101 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
102 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 rwlock_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 volatile 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));
357 * Return the appropriate queue lock based on the index.
359 static inline struct mtx *
363 if (qindex == QUEUE_DIRTY)
364 return (struct mtx *)(&bqdirty);
365 return (struct mtx *)(&bqclean);
371 * Wakeup any bwillwrite() waiters.
376 mtx_lock(&bdirtylock);
381 mtx_unlock(&bdirtylock);
387 * Decrement the numdirtybuffers count by one and wakeup any
388 * threads blocked in bwillwrite().
394 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
395 (lodirtybuffers + hidirtybuffers) / 2)
402 * Increment the numdirtybuffers count by one and wakeup the buf
410 * Only do the wakeup once as we cross the boundary. The
411 * buf daemon will keep running until the condition clears.
413 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
414 (lodirtybuffers + hidirtybuffers) / 2)
421 * Called when buffer space is potentially available for recovery.
422 * getnewbuf() will block on this flag when it is unable to free
423 * sufficient buffer space. Buffer space becomes recoverable when
424 * bp's get placed back in the queues.
433 * If someone is waiting for BUF space, wake them up. Even
434 * though we haven't freed the kva space yet, the waiting
435 * process will be able to now.
441 if ((on & VFS_BIO_NEED_BUFSPACE) == 0)
444 if (atomic_cmpset_rel_int(&needsbuffer, on,
445 on & ~VFS_BIO_NEED_BUFSPACE))
449 wakeup(__DEVOLATILE(void *, &needsbuffer));
456 * Wake up processes that are waiting on asynchronous writes to fall
457 * below lorunningspace.
463 mtx_lock(&rbreqlock);
466 wakeup(&runningbufreq);
468 mtx_unlock(&rbreqlock);
474 * Decrement the outstanding write count according.
477 runningbufwakeup(struct buf *bp)
481 bspace = bp->b_runningbufspace;
484 space = atomic_fetchadd_long(&runningbufspace, -bspace);
485 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
487 bp->b_runningbufspace = 0;
489 * Only acquire the lock and wakeup on the transition from exceeding
490 * the threshold to falling below it.
492 if (space < lorunningspace)
494 if (space - bspace > lorunningspace)
502 * Called when a buffer has been added to one of the free queues to
503 * account for the buffer and to wakeup anyone waiting for free buffers.
504 * This typically occurs when large amounts of metadata are being handled
505 * by the buffer cache ( else buffer space runs out first, usually ).
508 bufcountadd(struct buf *bp)
510 int mask, need_wakeup, old, on;
512 KASSERT((bp->b_flags & B_INFREECNT) == 0,
513 ("buf %p already counted as free", bp));
514 bp->b_flags |= B_INFREECNT;
515 old = atomic_fetchadd_int(&numfreebuffers, 1);
516 KASSERT(old >= 0 && old < nbuf,
517 ("numfreebuffers climbed to %d", old + 1));
518 mask = VFS_BIO_NEED_ANY;
519 if (numfreebuffers >= hifreebuffers)
520 mask |= VFS_BIO_NEED_FREE;
528 if (atomic_cmpset_rel_int(&needsbuffer, on, on & ~mask))
532 wakeup(__DEVOLATILE(void *, &needsbuffer));
539 * Decrement the numfreebuffers count as needed.
542 bufcountsub(struct buf *bp)
547 * Fixup numfreebuffers count. If the buffer is invalid or not
548 * delayed-write, the buffer was free and we must decrement
551 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
552 KASSERT((bp->b_flags & B_INFREECNT) != 0,
553 ("buf %p not counted in numfreebuffers", bp));
554 bp->b_flags &= ~B_INFREECNT;
555 old = atomic_fetchadd_int(&numfreebuffers, -1);
556 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
561 * waitrunningbufspace()
563 * runningbufspace is a measure of the amount of I/O currently
564 * running. This routine is used in async-write situations to
565 * prevent creating huge backups of pending writes to a device.
566 * Only asynchronous writes are governed by this function.
568 * This does NOT turn an async write into a sync write. It waits
569 * for earlier writes to complete and generally returns before the
570 * caller's write has reached the device.
573 waitrunningbufspace(void)
576 mtx_lock(&rbreqlock);
577 while (runningbufspace > hirunningspace) {
579 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
581 mtx_unlock(&rbreqlock);
586 * vfs_buf_test_cache:
588 * Called when a buffer is extended. This function clears the B_CACHE
589 * bit if the newly extended portion of the buffer does not contain
594 vfs_buf_test_cache(struct buf *bp,
595 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
599 VM_OBJECT_ASSERT_LOCKED(m->object);
600 if (bp->b_flags & B_CACHE) {
601 int base = (foff + off) & PAGE_MASK;
602 if (vm_page_is_valid(m, base, size) == 0)
603 bp->b_flags &= ~B_CACHE;
607 /* Wake up the buffer daemon if necessary */
613 if (bd_request == 0) {
621 * bd_speedup - speedup the buffer cache flushing code
630 if (bd_speedupreq == 0 || bd_request == 0)
640 #define NSWBUF_MIN 16
644 #define TRANSIENT_DENOM 5
646 #define TRANSIENT_DENOM 10
650 * Calculating buffer cache scaling values and reserve space for buffer
651 * headers. This is called during low level kernel initialization and
652 * may be called more then once. We CANNOT write to the memory area
653 * being reserved at this time.
656 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
659 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
662 * physmem_est is in pages. Convert it to kilobytes (assumes
663 * PAGE_SIZE is >= 1K)
665 physmem_est = physmem_est * (PAGE_SIZE / 1024);
668 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
669 * For the first 64MB of ram nominally allocate sufficient buffers to
670 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
671 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
672 * the buffer cache we limit the eventual kva reservation to
675 * factor represents the 1/4 x ram conversion.
678 int factor = 4 * BKVASIZE / 1024;
681 if (physmem_est > 4096)
682 nbuf += min((physmem_est - 4096) / factor,
684 if (physmem_est > 65536)
685 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
686 32 * 1024 * 1024 / (factor * 5));
688 if (maxbcache && nbuf > maxbcache / BKVASIZE)
689 nbuf = maxbcache / BKVASIZE;
694 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
695 maxbuf = (LONG_MAX / 3) / BKVASIZE;
698 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
704 * Ideal allocation size for the transient bio submap if 10%
705 * of the maximal space buffer map. This roughly corresponds
706 * to the amount of the buffer mapped for typical UFS load.
708 * Clip the buffer map to reserve space for the transient
709 * BIOs, if its extent is bigger than 90% (80% on i386) of the
710 * maximum buffer map extent on the platform.
712 * The fall-back to the maxbuf in case of maxbcache unset,
713 * allows to not trim the buffer KVA for the architectures
714 * with ample KVA space.
716 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
717 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
718 buf_sz = (long)nbuf * BKVASIZE;
719 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
720 (TRANSIENT_DENOM - 1)) {
722 * There is more KVA than memory. Do not
723 * adjust buffer map size, and assign the rest
724 * of maxbuf to transient map.
726 biotmap_sz = maxbuf_sz - buf_sz;
729 * Buffer map spans all KVA we could afford on
730 * this platform. Give 10% (20% on i386) of
731 * the buffer map to the transient bio map.
733 biotmap_sz = buf_sz / TRANSIENT_DENOM;
734 buf_sz -= biotmap_sz;
736 if (biotmap_sz / INT_MAX > MAXPHYS)
737 bio_transient_maxcnt = INT_MAX;
739 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
741 * Artifically limit to 1024 simultaneous in-flight I/Os
742 * using the transient mapping.
744 if (bio_transient_maxcnt > 1024)
745 bio_transient_maxcnt = 1024;
747 nbuf = buf_sz / BKVASIZE;
751 * swbufs are used as temporary holders for I/O, such as paging I/O.
752 * We have no less then 16 and no more then 256.
754 nswbuf = min(nbuf / 4, 256);
755 TUNABLE_INT_FETCH("kern.nswbuf", &nswbuf);
756 if (nswbuf < NSWBUF_MIN)
760 * Reserve space for the buffer cache buffers
763 v = (caddr_t)(swbuf + nswbuf);
765 v = (caddr_t)(buf + nbuf);
770 /* Initialize the buffer subsystem. Called before use of any buffers. */
777 CTASSERT(MAXBCACHEBUF >= MAXBSIZE);
778 mtx_init(&bqclean, "bufq clean lock", NULL, MTX_DEF);
779 mtx_init(&bqdirty, "bufq dirty lock", NULL, MTX_DEF);
780 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
781 rw_init(&nblock, "needsbuffer lock");
782 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
783 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
785 /* next, make a null set of free lists */
786 for (i = 0; i < BUFFER_QUEUES; i++)
787 TAILQ_INIT(&bufqueues[i]);
789 /* finally, initialize each buffer header and stick on empty q */
790 for (i = 0; i < nbuf; i++) {
792 bzero(bp, sizeof *bp);
793 bp->b_flags = B_INVAL | B_INFREECNT;
794 bp->b_rcred = NOCRED;
795 bp->b_wcred = NOCRED;
796 bp->b_qindex = QUEUE_EMPTY;
798 LIST_INIT(&bp->b_dep);
800 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
802 bq_len[QUEUE_EMPTY]++;
807 * maxbufspace is the absolute maximum amount of buffer space we are
808 * allowed to reserve in KVM and in real terms. The absolute maximum
809 * is nominally used by buf_daemon. hibufspace is the nominal maximum
810 * used by most other processes. The differential is required to
811 * ensure that buf_daemon is able to run when other processes might
812 * be blocked waiting for buffer space.
814 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
815 * this may result in KVM fragmentation which is not handled optimally
818 maxbufspace = (long)nbuf * BKVASIZE;
819 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBCACHEBUF * 10);
820 lobufspace = hibufspace - MAXBCACHEBUF;
823 * Note: The 16 MiB upper limit for hirunningspace was chosen
824 * arbitrarily and may need further tuning. It corresponds to
825 * 128 outstanding write IO requests (if IO size is 128 KiB),
826 * which fits with many RAID controllers' tagged queuing limits.
827 * The lower 1 MiB limit is the historical upper limit for
830 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBCACHEBUF),
831 16 * 1024 * 1024), 1024 * 1024);
832 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBCACHEBUF);
835 * Limit the amount of malloc memory since it is wired permanently into
836 * the kernel space. Even though this is accounted for in the buffer
837 * allocation, we don't want the malloced region to grow uncontrolled.
838 * The malloc scheme improves memory utilization significantly on average
839 * (small) directories.
841 maxbufmallocspace = hibufspace / 20;
844 * Reduce the chance of a deadlock occuring by limiting the number
845 * of delayed-write dirty buffers we allow to stack up.
847 hidirtybuffers = nbuf / 4 + 20;
848 dirtybufthresh = hidirtybuffers * 9 / 10;
851 * To support extreme low-memory systems, make sure hidirtybuffers cannot
852 * eat up all available buffer space. This occurs when our minimum cannot
853 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
854 * BKVASIZE'd buffers.
856 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
857 hidirtybuffers >>= 1;
859 lodirtybuffers = hidirtybuffers / 2;
862 * Try to keep the number of free buffers in the specified range,
863 * and give special processes (e.g. like buf_daemon) access to an
866 lofreebuffers = nbuf / 18 + 5;
867 hifreebuffers = 2 * lofreebuffers;
868 numfreebuffers = nbuf;
870 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
871 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
872 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
877 vfs_buf_check_mapped(struct buf *bp)
880 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
881 ("mapped buf %p %x", bp, bp->b_flags));
882 KASSERT(bp->b_kvabase != unmapped_buf,
883 ("mapped buf: b_kvabase was not updated %p", bp));
884 KASSERT(bp->b_data != unmapped_buf,
885 ("mapped buf: b_data was not updated %p", bp));
889 vfs_buf_check_unmapped(struct buf *bp)
892 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
893 ("unmapped buf %p %x", bp, bp->b_flags));
894 KASSERT(bp->b_kvabase == unmapped_buf,
895 ("unmapped buf: corrupted b_kvabase %p", bp));
896 KASSERT(bp->b_data == unmapped_buf,
897 ("unmapped buf: corrupted b_data %p", bp));
900 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
901 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
903 #define BUF_CHECK_MAPPED(bp) do {} while (0)
904 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
908 bpmap_qenter(struct buf *bp)
911 BUF_CHECK_MAPPED(bp);
914 * bp->b_data is relative to bp->b_offset, but
915 * bp->b_offset may be offset into the first page.
917 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
918 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
919 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
920 (vm_offset_t)(bp->b_offset & PAGE_MASK));
924 * bfreekva() - free the kva allocation for a buffer.
926 * Since this call frees up buffer space, we call bufspacewakeup().
929 bfreekva(struct buf *bp)
932 if (bp->b_kvasize == 0)
935 atomic_add_int(&buffreekvacnt, 1);
936 atomic_subtract_long(&bufspace, bp->b_kvasize);
937 if ((bp->b_flags & B_UNMAPPED) == 0) {
938 BUF_CHECK_MAPPED(bp);
939 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase,
942 BUF_CHECK_UNMAPPED(bp);
943 if ((bp->b_flags & B_KVAALLOC) != 0) {
944 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvaalloc,
947 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
948 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
957 * Insert the buffer into the appropriate free list.
960 binsfree(struct buf *bp, int qindex)
962 struct mtx *olock, *nlock;
964 BUF_ASSERT_XLOCKED(bp);
966 olock = bqlock(bp->b_qindex);
967 nlock = bqlock(qindex);
969 /* Handle delayed bremfree() processing. */
970 if (bp->b_flags & B_REMFREE)
973 if (bp->b_qindex != QUEUE_NONE)
974 panic("binsfree: free buffer onto another queue???");
976 bp->b_qindex = qindex;
977 if (olock != nlock) {
981 if (bp->b_flags & B_AGE)
982 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
984 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
986 bq_len[bp->b_qindex]++;
991 * Something we can maybe free or reuse.
993 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
996 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1003 * Mark the buffer for removal from the appropriate free list.
1007 bremfree(struct buf *bp)
1010 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1011 KASSERT((bp->b_flags & B_REMFREE) == 0,
1012 ("bremfree: buffer %p already marked for delayed removal.", bp));
1013 KASSERT(bp->b_qindex != QUEUE_NONE,
1014 ("bremfree: buffer %p not on a queue.", bp));
1015 BUF_ASSERT_XLOCKED(bp);
1017 bp->b_flags |= B_REMFREE;
1024 * Force an immediate removal from a free list. Used only in nfs when
1025 * it abuses the b_freelist pointer.
1028 bremfreef(struct buf *bp)
1032 qlock = bqlock(bp->b_qindex);
1041 * Removes a buffer from the free list, must be called with the
1042 * correct qlock held.
1045 bremfreel(struct buf *bp)
1048 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1049 bp, bp->b_vp, bp->b_flags);
1050 KASSERT(bp->b_qindex != QUEUE_NONE,
1051 ("bremfreel: buffer %p not on a queue.", bp));
1052 BUF_ASSERT_XLOCKED(bp);
1053 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1055 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1057 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1059 bq_len[bp->b_qindex]--;
1061 bp->b_qindex = QUEUE_NONE;
1063 * If this was a delayed bremfree() we only need to remove the buffer
1064 * from the queue and return the stats are already done.
1066 if (bp->b_flags & B_REMFREE) {
1067 bp->b_flags &= ~B_REMFREE;
1074 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1075 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1076 * the buffer is valid and we do not have to do anything.
1079 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1080 int cnt, struct ucred * cred)
1085 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1086 if (inmem(vp, *rablkno))
1088 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1090 if ((rabp->b_flags & B_CACHE) == 0) {
1091 if (!TD_IS_IDLETHREAD(curthread))
1092 curthread->td_ru.ru_inblock++;
1093 rabp->b_flags |= B_ASYNC;
1094 rabp->b_flags &= ~B_INVAL;
1095 rabp->b_ioflags &= ~BIO_ERROR;
1096 rabp->b_iocmd = BIO_READ;
1097 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1098 rabp->b_rcred = crhold(cred);
1099 vfs_busy_pages(rabp, 0);
1101 rabp->b_iooffset = dbtob(rabp->b_blkno);
1110 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1112 * Get a buffer with the specified data. Look in the cache first. We
1113 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1114 * is set, the buffer is valid and we do not have to do anything, see
1115 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1118 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1119 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1122 int rv = 0, readwait = 0;
1124 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1126 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1128 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1132 /* if not found in cache, do some I/O */
1133 if ((bp->b_flags & B_CACHE) == 0) {
1134 if (!TD_IS_IDLETHREAD(curthread))
1135 curthread->td_ru.ru_inblock++;
1136 bp->b_iocmd = BIO_READ;
1137 bp->b_flags &= ~B_INVAL;
1138 bp->b_ioflags &= ~BIO_ERROR;
1139 if (bp->b_rcred == NOCRED && cred != NOCRED)
1140 bp->b_rcred = crhold(cred);
1141 vfs_busy_pages(bp, 0);
1142 bp->b_iooffset = dbtob(bp->b_blkno);
1147 breada(vp, rablkno, rabsize, cnt, cred);
1156 * Write, release buffer on completion. (Done by iodone
1157 * if async). Do not bother writing anything if the buffer
1160 * Note that we set B_CACHE here, indicating that buffer is
1161 * fully valid and thus cacheable. This is true even of NFS
1162 * now so we set it generally. This could be set either here
1163 * or in biodone() since the I/O is synchronous. We put it
1167 bufwrite(struct buf *bp)
1174 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1175 if (bp->b_flags & B_INVAL) {
1180 if (bp->b_flags & B_BARRIER)
1183 oldflags = bp->b_flags;
1185 BUF_ASSERT_HELD(bp);
1187 if (bp->b_pin_count > 0)
1190 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1191 ("FFS background buffer should not get here %p", bp));
1195 vp_md = vp->v_vflag & VV_MD;
1200 * Mark the buffer clean. Increment the bufobj write count
1201 * before bundirty() call, to prevent other thread from seeing
1202 * empty dirty list and zero counter for writes in progress,
1203 * falsely indicating that the bufobj is clean.
1205 bufobj_wref(bp->b_bufobj);
1208 bp->b_flags &= ~B_DONE;
1209 bp->b_ioflags &= ~BIO_ERROR;
1210 bp->b_flags |= B_CACHE;
1211 bp->b_iocmd = BIO_WRITE;
1213 vfs_busy_pages(bp, 1);
1216 * Normal bwrites pipeline writes
1218 bp->b_runningbufspace = bp->b_bufsize;
1219 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1221 if (!TD_IS_IDLETHREAD(curthread))
1222 curthread->td_ru.ru_oublock++;
1223 if (oldflags & B_ASYNC)
1225 bp->b_iooffset = dbtob(bp->b_blkno);
1228 if ((oldflags & B_ASYNC) == 0) {
1229 int rtval = bufwait(bp);
1232 } else if (space > hirunningspace) {
1234 * don't allow the async write to saturate the I/O
1235 * system. We will not deadlock here because
1236 * we are blocking waiting for I/O that is already in-progress
1237 * to complete. We do not block here if it is the update
1238 * or syncer daemon trying to clean up as that can lead
1241 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1242 waitrunningbufspace();
1249 bufbdflush(struct bufobj *bo, struct buf *bp)
1253 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1254 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1256 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1259 * Try to find a buffer to flush.
1261 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1262 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1264 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1267 panic("bdwrite: found ourselves");
1269 /* Don't countdeps with the bo lock held. */
1270 if (buf_countdeps(nbp, 0)) {
1275 if (nbp->b_flags & B_CLUSTEROK) {
1276 vfs_bio_awrite(nbp);
1281 dirtybufferflushes++;
1290 * Delayed write. (Buffer is marked dirty). Do not bother writing
1291 * anything if the buffer is marked invalid.
1293 * Note that since the buffer must be completely valid, we can safely
1294 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1295 * biodone() in order to prevent getblk from writing the buffer
1296 * out synchronously.
1299 bdwrite(struct buf *bp)
1301 struct thread *td = curthread;
1305 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1306 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1307 KASSERT((bp->b_flags & B_BARRIER) == 0,
1308 ("Barrier request in delayed write %p", bp));
1309 BUF_ASSERT_HELD(bp);
1311 if (bp->b_flags & B_INVAL) {
1317 * If we have too many dirty buffers, don't create any more.
1318 * If we are wildly over our limit, then force a complete
1319 * cleanup. Otherwise, just keep the situation from getting
1320 * out of control. Note that we have to avoid a recursive
1321 * disaster and not try to clean up after our own cleanup!
1325 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1326 td->td_pflags |= TDP_INBDFLUSH;
1328 td->td_pflags &= ~TDP_INBDFLUSH;
1334 * Set B_CACHE, indicating that the buffer is fully valid. This is
1335 * true even of NFS now.
1337 bp->b_flags |= B_CACHE;
1340 * This bmap keeps the system from needing to do the bmap later,
1341 * perhaps when the system is attempting to do a sync. Since it
1342 * is likely that the indirect block -- or whatever other datastructure
1343 * that the filesystem needs is still in memory now, it is a good
1344 * thing to do this. Note also, that if the pageout daemon is
1345 * requesting a sync -- there might not be enough memory to do
1346 * the bmap then... So, this is important to do.
1348 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1349 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1353 * Set the *dirty* buffer range based upon the VM system dirty
1356 * Mark the buffer pages as clean. We need to do this here to
1357 * satisfy the vnode_pager and the pageout daemon, so that it
1358 * thinks that the pages have been "cleaned". Note that since
1359 * the pages are in a delayed write buffer -- the VFS layer
1360 * "will" see that the pages get written out on the next sync,
1361 * or perhaps the cluster will be completed.
1363 vfs_clean_pages_dirty_buf(bp);
1367 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1368 * due to the softdep code.
1375 * Turn buffer into delayed write request. We must clear BIO_READ and
1376 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1377 * itself to properly update it in the dirty/clean lists. We mark it
1378 * B_DONE to ensure that any asynchronization of the buffer properly
1379 * clears B_DONE ( else a panic will occur later ).
1381 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1382 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1383 * should only be called if the buffer is known-good.
1385 * Since the buffer is not on a queue, we do not update the numfreebuffers
1388 * The buffer must be on QUEUE_NONE.
1391 bdirty(struct buf *bp)
1394 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1395 bp, bp->b_vp, bp->b_flags);
1396 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1397 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1398 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1399 BUF_ASSERT_HELD(bp);
1400 bp->b_flags &= ~(B_RELBUF);
1401 bp->b_iocmd = BIO_WRITE;
1403 if ((bp->b_flags & B_DELWRI) == 0) {
1404 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1413 * Clear B_DELWRI for buffer.
1415 * Since the buffer is not on a queue, we do not update the numfreebuffers
1418 * The buffer must be on QUEUE_NONE.
1422 bundirty(struct buf *bp)
1425 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1426 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1427 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1428 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1429 BUF_ASSERT_HELD(bp);
1431 if (bp->b_flags & B_DELWRI) {
1432 bp->b_flags &= ~B_DELWRI;
1437 * Since it is now being written, we can clear its deferred write flag.
1439 bp->b_flags &= ~B_DEFERRED;
1445 * Asynchronous write. Start output on a buffer, but do not wait for
1446 * it to complete. The buffer is released when the output completes.
1448 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1449 * B_INVAL buffers. Not us.
1452 bawrite(struct buf *bp)
1455 bp->b_flags |= B_ASYNC;
1462 * Asynchronous barrier write. Start output on a buffer, but do not
1463 * wait for it to complete. Place a write barrier after this write so
1464 * that this buffer and all buffers written before it are committed to
1465 * the disk before any buffers written after this write are committed
1466 * to the disk. The buffer is released when the output completes.
1469 babarrierwrite(struct buf *bp)
1472 bp->b_flags |= B_ASYNC | B_BARRIER;
1479 * Synchronous barrier write. Start output on a buffer and wait for
1480 * it to complete. Place a write barrier after this write so that
1481 * this buffer and all buffers written before it are committed to
1482 * the disk before any buffers written after this write are committed
1483 * to the disk. The buffer is released when the output completes.
1486 bbarrierwrite(struct buf *bp)
1489 bp->b_flags |= B_BARRIER;
1490 return (bwrite(bp));
1496 * Called prior to the locking of any vnodes when we are expecting to
1497 * write. We do not want to starve the buffer cache with too many
1498 * dirty buffers so we block here. By blocking prior to the locking
1499 * of any vnodes we attempt to avoid the situation where a locked vnode
1500 * prevents the various system daemons from flushing related buffers.
1506 if (numdirtybuffers >= hidirtybuffers) {
1507 mtx_lock(&bdirtylock);
1508 while (numdirtybuffers >= hidirtybuffers) {
1510 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
1513 mtx_unlock(&bdirtylock);
1518 * Return true if we have too many dirty buffers.
1521 buf_dirty_count_severe(void)
1524 return(numdirtybuffers >= hidirtybuffers);
1527 static __noinline int
1528 buf_vm_page_count_severe(void)
1531 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1533 return vm_page_count_severe();
1539 * Release a busy buffer and, if requested, free its resources. The
1540 * buffer will be stashed in the appropriate bufqueue[] allowing it
1541 * to be accessed later as a cache entity or reused for other purposes.
1544 brelse(struct buf *bp)
1548 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1549 bp, bp->b_vp, bp->b_flags);
1550 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1551 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1553 if (BUF_LOCKRECURSED(bp)) {
1555 * Do not process, in particular, do not handle the
1556 * B_INVAL/B_RELBUF and do not release to free list.
1562 if (bp->b_flags & B_MANAGED) {
1567 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1568 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1570 * Failed write, redirty. Must clear BIO_ERROR to prevent
1571 * pages from being scrapped. If the error is anything
1572 * other than an I/O error (EIO), assume that retrying
1575 bp->b_ioflags &= ~BIO_ERROR;
1577 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1578 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1580 * Either a failed I/O or we were asked to free or not
1583 bp->b_flags |= B_INVAL;
1584 if (!LIST_EMPTY(&bp->b_dep))
1586 if (bp->b_flags & B_DELWRI)
1588 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1589 if ((bp->b_flags & B_VMIO) == 0) {
1598 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1599 * is called with B_DELWRI set, the underlying pages may wind up
1600 * getting freed causing a previous write (bdwrite()) to get 'lost'
1601 * because pages associated with a B_DELWRI bp are marked clean.
1603 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1604 * if B_DELWRI is set.
1606 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1607 * on pages to return pages to the VM page queues.
1609 if (bp->b_flags & B_DELWRI)
1610 bp->b_flags &= ~B_RELBUF;
1611 else if (buf_vm_page_count_severe()) {
1613 * BKGRDINPROG can only be set with the buf and bufobj
1614 * locks both held. We tolerate a race to clear it here.
1616 if (!(bp->b_vflags & BV_BKGRDINPROG))
1617 bp->b_flags |= B_RELBUF;
1621 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1622 * constituted, not even NFS buffers now. Two flags effect this. If
1623 * B_INVAL, the struct buf is invalidated but the VM object is kept
1624 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1626 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1627 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1628 * buffer is also B_INVAL because it hits the re-dirtying code above.
1630 * Normally we can do this whether a buffer is B_DELWRI or not. If
1631 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1632 * the commit state and we cannot afford to lose the buffer. If the
1633 * buffer has a background write in progress, we need to keep it
1634 * around to prevent it from being reconstituted and starting a second
1637 if ((bp->b_flags & B_VMIO)
1638 && !(bp->b_vp->v_mount != NULL &&
1639 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1640 !vn_isdisk(bp->b_vp, NULL) &&
1641 (bp->b_flags & B_DELWRI))
1650 obj = bp->b_bufobj->bo_object;
1653 * Get the base offset and length of the buffer. Note that
1654 * in the VMIO case if the buffer block size is not
1655 * page-aligned then b_data pointer may not be page-aligned.
1656 * But our b_pages[] array *IS* page aligned.
1658 * block sizes less then DEV_BSIZE (usually 512) are not
1659 * supported due to the page granularity bits (m->valid,
1660 * m->dirty, etc...).
1662 * See man buf(9) for more information
1664 resid = bp->b_bufsize;
1665 foff = bp->b_offset;
1666 for (i = 0; i < bp->b_npages; i++) {
1672 * If we hit a bogus page, fixup *all* the bogus pages
1675 if (m == bogus_page) {
1676 poff = OFF_TO_IDX(bp->b_offset);
1679 VM_OBJECT_RLOCK(obj);
1680 for (j = i; j < bp->b_npages; j++) {
1682 mtmp = bp->b_pages[j];
1683 if (mtmp == bogus_page) {
1684 mtmp = vm_page_lookup(obj, poff + j);
1686 panic("brelse: page missing\n");
1688 bp->b_pages[j] = mtmp;
1691 VM_OBJECT_RUNLOCK(obj);
1693 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1694 BUF_CHECK_MAPPED(bp);
1696 trunc_page((vm_offset_t)bp->b_data),
1697 bp->b_pages, bp->b_npages);
1701 if ((bp->b_flags & B_NOCACHE) ||
1702 (bp->b_ioflags & BIO_ERROR &&
1703 bp->b_iocmd == BIO_READ)) {
1704 int poffset = foff & PAGE_MASK;
1705 int presid = resid > (PAGE_SIZE - poffset) ?
1706 (PAGE_SIZE - poffset) : resid;
1708 KASSERT(presid >= 0, ("brelse: extra page"));
1709 VM_OBJECT_WLOCK(obj);
1710 while (vm_page_xbusied(m)) {
1712 VM_OBJECT_WUNLOCK(obj);
1713 vm_page_busy_sleep(m, "mbncsh");
1714 VM_OBJECT_WLOCK(obj);
1716 if (pmap_page_wired_mappings(m) == 0)
1717 vm_page_set_invalid(m, poffset, presid);
1718 VM_OBJECT_WUNLOCK(obj);
1720 printf("avoided corruption bug in bogus_page/brelse code\n");
1722 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1723 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1725 if (bp->b_flags & (B_INVAL | B_RELBUF))
1726 vfs_vmio_release(bp);
1728 } else if (bp->b_flags & B_VMIO) {
1730 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1731 vfs_vmio_release(bp);
1734 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1735 if (bp->b_bufsize != 0)
1737 if (bp->b_vp != NULL)
1742 * If the buffer has junk contents signal it and eventually
1743 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1746 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1747 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1748 bp->b_flags |= B_INVAL;
1749 if (bp->b_flags & B_INVAL) {
1750 if (bp->b_flags & B_DELWRI)
1756 /* buffers with no memory */
1757 if (bp->b_bufsize == 0) {
1758 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1759 if (bp->b_vflags & BV_BKGRDINPROG)
1760 panic("losing buffer 1");
1762 qindex = QUEUE_EMPTYKVA;
1764 qindex = QUEUE_EMPTY;
1765 bp->b_flags |= B_AGE;
1766 /* buffers with junk contents */
1767 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1768 (bp->b_ioflags & BIO_ERROR)) {
1769 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1770 if (bp->b_vflags & BV_BKGRDINPROG)
1771 panic("losing buffer 2");
1772 qindex = QUEUE_CLEAN;
1773 bp->b_flags |= B_AGE;
1774 /* remaining buffers */
1775 } else if (bp->b_flags & B_DELWRI)
1776 qindex = QUEUE_DIRTY;
1778 qindex = QUEUE_CLEAN;
1780 binsfree(bp, qindex);
1782 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1783 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1784 panic("brelse: not dirty");
1790 * Release a buffer back to the appropriate queue but do not try to free
1791 * it. The buffer is expected to be used again soon.
1793 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1794 * biodone() to requeue an async I/O on completion. It is also used when
1795 * known good buffers need to be requeued but we think we may need the data
1798 * XXX we should be able to leave the B_RELBUF hint set on completion.
1801 bqrelse(struct buf *bp)
1805 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1806 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1807 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1809 if (BUF_LOCKRECURSED(bp)) {
1810 /* do not release to free list */
1814 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1816 if (bp->b_flags & B_MANAGED) {
1817 if (bp->b_flags & B_REMFREE)
1822 /* buffers with stale but valid contents */
1823 if (bp->b_flags & B_DELWRI) {
1824 qindex = QUEUE_DIRTY;
1826 if ((bp->b_flags & B_DELWRI) == 0 &&
1827 (bp->b_xflags & BX_VNDIRTY))
1828 panic("bqrelse: not dirty");
1830 * BKGRDINPROG can only be set with the buf and bufobj
1831 * locks both held. We tolerate a race to clear it here.
1833 if (buf_vm_page_count_severe() &&
1834 (bp->b_vflags & BV_BKGRDINPROG) == 0) {
1836 * We are too low on memory, we have to try to free
1837 * the buffer (most importantly: the wired pages
1838 * making up its backing store) *now*.
1843 qindex = QUEUE_CLEAN;
1845 binsfree(bp, qindex);
1852 /* Give pages used by the bp back to the VM system (where possible) */
1854 vfs_vmio_release(struct buf *bp)
1860 if ((bp->b_flags & B_UNMAPPED) == 0) {
1861 BUF_CHECK_MAPPED(bp);
1862 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1864 BUF_CHECK_UNMAPPED(bp);
1865 obj = bp->b_bufobj->bo_object;
1867 VM_OBJECT_WLOCK(obj);
1868 for (i = 0; i < bp->b_npages; i++) {
1870 bp->b_pages[i] = NULL;
1872 * In order to keep page LRU ordering consistent, put
1873 * everything on the inactive queue.
1876 vm_page_unwire(m, 0);
1879 * Might as well free the page if we can and it has
1880 * no valid data. We also free the page if the
1881 * buffer was used for direct I/O
1883 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1884 if (m->wire_count == 0 && !vm_page_busied(m))
1886 } else if (bp->b_flags & B_DIRECT)
1887 vm_page_try_to_free(m);
1888 else if (buf_vm_page_count_severe())
1889 vm_page_try_to_cache(m);
1893 VM_OBJECT_WUNLOCK(obj);
1895 if (bp->b_bufsize) {
1900 bp->b_flags &= ~B_VMIO;
1906 * Check to see if a block at a particular lbn is available for a clustered
1910 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1917 /* If the buf isn't in core skip it */
1918 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1921 /* If the buf is busy we don't want to wait for it */
1922 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1925 /* Only cluster with valid clusterable delayed write buffers */
1926 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1927 (B_DELWRI | B_CLUSTEROK))
1930 if (bpa->b_bufsize != size)
1934 * Check to see if it is in the expected place on disk and that the
1935 * block has been mapped.
1937 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1947 * Implement clustered async writes for clearing out B_DELWRI buffers.
1948 * This is much better then the old way of writing only one buffer at
1949 * a time. Note that we may not be presented with the buffers in the
1950 * correct order, so we search for the cluster in both directions.
1953 vfs_bio_awrite(struct buf *bp)
1958 daddr_t lblkno = bp->b_lblkno;
1959 struct vnode *vp = bp->b_vp;
1967 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1969 * right now we support clustered writing only to regular files. If
1970 * we find a clusterable block we could be in the middle of a cluster
1971 * rather then at the beginning.
1973 if ((vp->v_type == VREG) &&
1974 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1975 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1977 size = vp->v_mount->mnt_stat.f_iosize;
1978 maxcl = MAXPHYS / size;
1981 for (i = 1; i < maxcl; i++)
1982 if (vfs_bio_clcheck(vp, size, lblkno + i,
1983 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1986 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
1987 if (vfs_bio_clcheck(vp, size, lblkno - j,
1988 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
1994 * this is a possible cluster write
1998 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2004 bp->b_flags |= B_ASYNC;
2006 * default (old) behavior, writing out only one block
2008 * XXX returns b_bufsize instead of b_bcount for nwritten?
2010 nwritten = bp->b_bufsize;
2017 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
2020 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2021 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
2022 if ((gbflags & GB_UNMAPPED) == 0) {
2023 bp->b_kvabase = (caddr_t)addr;
2024 } else if ((gbflags & GB_KVAALLOC) != 0) {
2025 KASSERT((gbflags & GB_UNMAPPED) != 0,
2026 ("GB_KVAALLOC without GB_UNMAPPED"));
2027 bp->b_kvaalloc = (caddr_t)addr;
2028 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2029 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2031 bp->b_kvasize = maxsize;
2035 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2039 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2046 if (vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr)) {
2048 * Buffer map is too fragmented. Request the caller
2049 * to defragment the map.
2051 atomic_add_int(&bufdefragcnt, 1);
2054 setbufkva(bp, addr, maxsize, gbflags);
2055 atomic_add_long(&bufspace, bp->b_kvasize);
2060 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2061 * locked vnode is supplied.
2064 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2069 int error, fl, flags, norunbuf;
2071 mtx_assert(&bqclean, MA_OWNED);
2074 flags = VFS_BIO_NEED_BUFSPACE;
2076 } else if (bufspace >= hibufspace) {
2078 flags = VFS_BIO_NEED_BUFSPACE;
2081 flags = VFS_BIO_NEED_ANY;
2083 atomic_set_int(&needsbuffer, flags);
2084 mtx_unlock(&bqclean);
2086 bd_speedup(); /* heeeelp */
2087 if ((gbflags & GB_NOWAIT_BD) != 0)
2092 while ((needsbuffer & flags) != 0) {
2093 if (vp != NULL && vp->v_type != VCHR &&
2094 (td->td_pflags & TDP_BUFNEED) == 0) {
2095 rw_wunlock(&nblock);
2097 * getblk() is called with a vnode locked, and
2098 * some majority of the dirty buffers may as
2099 * well belong to the vnode. Flushing the
2100 * buffers there would make a progress that
2101 * cannot be achieved by the buf_daemon, that
2102 * cannot lock the vnode.
2104 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2105 (td->td_pflags & TDP_NORUNNINGBUF);
2108 * Play bufdaemon. The getnewbuf() function
2109 * may be called while the thread owns lock
2110 * for another dirty buffer for the same
2111 * vnode, which makes it impossible to use
2112 * VOP_FSYNC() there, due to the buffer lock
2115 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2116 fl = buf_flush(vp, flushbufqtarget);
2117 td->td_pflags &= norunbuf;
2121 if ((needsbuffer & flags) == 0)
2124 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
2125 (PRIBIO + 4) | slpflag, waitmsg, slptimeo);
2129 rw_wunlock(&nblock);
2133 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2136 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2137 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2138 bp->b_kvasize, bp->b_bufsize, qindex);
2139 mtx_assert(&bqclean, MA_NOTOWNED);
2142 * Note: we no longer distinguish between VMIO and non-VMIO
2145 KASSERT((bp->b_flags & B_DELWRI) == 0,
2146 ("delwri buffer %p found in queue %d", bp, qindex));
2148 if (qindex == QUEUE_CLEAN) {
2149 if (bp->b_flags & B_VMIO) {
2150 bp->b_flags &= ~B_ASYNC;
2151 vfs_vmio_release(bp);
2153 if (bp->b_vp != NULL)
2158 * Get the rest of the buffer freed up. b_kva* is still valid
2159 * after this operation.
2162 if (bp->b_rcred != NOCRED) {
2163 crfree(bp->b_rcred);
2164 bp->b_rcred = NOCRED;
2166 if (bp->b_wcred != NOCRED) {
2167 crfree(bp->b_wcred);
2168 bp->b_wcred = NOCRED;
2170 if (!LIST_EMPTY(&bp->b_dep))
2172 if (bp->b_vflags & BV_BKGRDINPROG)
2173 panic("losing buffer 3");
2174 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2175 bp, bp->b_vp, qindex));
2176 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2177 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2182 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2185 KASSERT((bp->b_flags & B_INFREECNT) == 0,
2186 ("buf %p still counted as free?", bp));
2189 bp->b_blkno = bp->b_lblkno = 0;
2190 bp->b_offset = NOOFFSET;
2196 bp->b_dirtyoff = bp->b_dirtyend = 0;
2197 bp->b_bufobj = NULL;
2198 bp->b_pin_count = 0;
2199 bp->b_fsprivate1 = NULL;
2200 bp->b_fsprivate2 = NULL;
2201 bp->b_fsprivate3 = NULL;
2203 LIST_INIT(&bp->b_dep);
2206 static int flushingbufs;
2209 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2211 struct buf *bp, *nbp;
2212 int nqindex, qindex, pass;
2214 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2218 atomic_add_int(&getnewbufrestarts, 1);
2221 * Setup for scan. If we do not have enough free buffers,
2222 * we setup a degenerate case that immediately fails. Note
2223 * that if we are specially marked process, we are allowed to
2224 * dip into our reserves.
2226 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2227 * for the allocation of the mapped buffer. For unmapped, the
2228 * easiest is to start with EMPTY outright.
2230 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2231 * However, there are a number of cases (defragging, reusing, ...)
2232 * where we cannot backup.
2236 if (!defrag && unmapped) {
2237 nqindex = QUEUE_EMPTY;
2238 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2241 nqindex = QUEUE_EMPTYKVA;
2242 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2246 * If no EMPTYKVA buffers and we are either defragging or
2247 * reusing, locate a CLEAN buffer to free or reuse. If
2248 * bufspace useage is low skip this step so we can allocate a
2251 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2252 nqindex = QUEUE_CLEAN;
2253 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2257 * If we could not find or were not allowed to reuse a CLEAN
2258 * buffer, check to see if it is ok to use an EMPTY buffer.
2259 * We can only use an EMPTY buffer if allocating its KVA would
2260 * not otherwise run us out of buffer space. No KVA is needed
2261 * for the unmapped allocation.
2263 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2265 nqindex = QUEUE_EMPTY;
2266 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2270 * All available buffers might be clean, retry ignoring the
2271 * lobufspace as the last resort.
2273 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2274 nqindex = QUEUE_CLEAN;
2275 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2279 * Run scan, possibly freeing data and/or kva mappings on the fly
2282 while ((bp = nbp) != NULL) {
2286 * Calculate next bp (we can only use it if we do not
2287 * block or do other fancy things).
2289 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2292 nqindex = QUEUE_EMPTYKVA;
2293 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2297 case QUEUE_EMPTYKVA:
2298 nqindex = QUEUE_CLEAN;
2299 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2304 if (metadata && pass == 1) {
2306 nqindex = QUEUE_EMPTY;
2308 &bufqueues[QUEUE_EMPTY]);
2317 * If we are defragging then we need a buffer with
2318 * b_kvasize != 0. XXX this situation should no longer
2319 * occur, if defrag is non-zero the buffer's b_kvasize
2320 * should also be non-zero at this point. XXX
2322 if (defrag && bp->b_kvasize == 0) {
2323 printf("Warning: defrag empty buffer %p\n", bp);
2328 * Start freeing the bp. This is somewhat involved. nbp
2329 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2331 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2334 * BKGRDINPROG can only be set with the buf and bufobj
2335 * locks both held. We tolerate a race to clear it here.
2337 if (bp->b_vflags & BV_BKGRDINPROG) {
2342 KASSERT(bp->b_qindex == qindex,
2343 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2346 mtx_unlock(&bqclean);
2348 * NOTE: nbp is now entirely invalid. We can only restart
2349 * the scan from this point on.
2352 getnewbuf_reuse_bp(bp, qindex);
2353 mtx_assert(&bqclean, MA_NOTOWNED);
2356 * If we are defragging then free the buffer.
2359 bp->b_flags |= B_INVAL;
2367 * Notify any waiters for the buffer lock about
2368 * identity change by freeing the buffer.
2370 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2371 bp->b_flags |= B_INVAL;
2381 * If we are overcomitted then recover the buffer and its
2382 * KVM space. This occurs in rare situations when multiple
2383 * processes are blocked in getnewbuf() or allocbuf().
2385 if (bufspace >= hibufspace)
2387 if (flushingbufs && bp->b_kvasize != 0) {
2388 bp->b_flags |= B_INVAL;
2393 if (bufspace < lobufspace)
2403 * Find and initialize a new buffer header, freeing up existing buffers
2404 * in the bufqueues as necessary. The new buffer is returned locked.
2406 * Important: B_INVAL is not set. If the caller wishes to throw the
2407 * buffer away, the caller must set B_INVAL prior to calling brelse().
2410 * We have insufficient buffer headers
2411 * We have insufficient buffer space
2412 * buffer_arena is too fragmented ( space reservation fails )
2413 * If we have to flush dirty buffers ( but we try to avoid this )
2416 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2420 int defrag, metadata;
2422 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2423 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2424 if (!unmapped_buf_allowed)
2425 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2428 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2434 * We can't afford to block since we might be holding a vnode lock,
2435 * which may prevent system daemons from running. We deal with
2436 * low-memory situations by proactively returning memory and running
2437 * async I/O rather then sync I/O.
2439 atomic_add_int(&getnewbufcalls, 1);
2440 atomic_subtract_int(&getnewbufrestarts, 1);
2442 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2443 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2448 * If we exhausted our list, sleep as appropriate. We may have to
2449 * wakeup various daemons and write out some dirty buffers.
2451 * Generally we are sleeping due to insufficient buffer space.
2454 mtx_assert(&bqclean, MA_OWNED);
2455 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2456 mtx_assert(&bqclean, MA_NOTOWNED);
2457 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2458 mtx_assert(&bqclean, MA_NOTOWNED);
2461 bp->b_flags |= B_UNMAPPED;
2462 bp->b_kvabase = bp->b_data = unmapped_buf;
2463 bp->b_kvasize = maxsize;
2464 atomic_add_long(&bufspace, bp->b_kvasize);
2465 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2466 atomic_add_int(&bufreusecnt, 1);
2468 mtx_assert(&bqclean, MA_NOTOWNED);
2471 * We finally have a valid bp. We aren't quite out of the
2472 * woods, we still have to reserve kva space. In order
2473 * to keep fragmentation sane we only allocate kva in
2476 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2478 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2479 B_KVAALLOC)) == B_UNMAPPED) {
2480 if (allocbufkva(bp, maxsize, gbflags)) {
2482 bp->b_flags |= B_INVAL;
2486 atomic_add_int(&bufreusecnt, 1);
2487 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2488 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2490 * If the reused buffer has KVA allocated,
2491 * reassign b_kvaalloc to b_kvabase.
2493 bp->b_kvabase = bp->b_kvaalloc;
2494 bp->b_flags &= ~B_KVAALLOC;
2495 atomic_subtract_long(&unmapped_bufspace,
2497 atomic_add_int(&bufreusecnt, 1);
2498 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2499 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2502 * The case of reused buffer already have KVA
2503 * mapped, but the request is for unmapped
2504 * buffer with KVA allocated.
2506 bp->b_kvaalloc = bp->b_kvabase;
2507 bp->b_data = bp->b_kvabase = unmapped_buf;
2508 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2509 atomic_add_long(&unmapped_bufspace,
2511 atomic_add_int(&bufreusecnt, 1);
2513 if ((gbflags & GB_UNMAPPED) == 0) {
2514 bp->b_saveaddr = bp->b_kvabase;
2515 bp->b_data = bp->b_saveaddr;
2516 bp->b_flags &= ~B_UNMAPPED;
2517 BUF_CHECK_MAPPED(bp);
2526 * buffer flushing daemon. Buffers are normally flushed by the
2527 * update daemon but if it cannot keep up this process starts to
2528 * take the load in an attempt to prevent getnewbuf() from blocking.
2531 static struct kproc_desc buf_kp = {
2536 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2539 buf_flush(struct vnode *vp, int target)
2543 flushed = flushbufqueues(vp, target, 0);
2546 * Could not find any buffers without rollback
2547 * dependencies, so just write the first one
2548 * in the hopes of eventually making progress.
2550 if (vp != NULL && target > 2)
2552 flushbufqueues(vp, target, 1);
2563 * This process needs to be suspended prior to shutdown sync.
2565 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2569 * This process is allowed to take the buffer cache to the limit
2571 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2575 mtx_unlock(&bdlock);
2577 kproc_suspend_check(bufdaemonproc);
2578 lodirty = lodirtybuffers;
2579 if (bd_speedupreq) {
2580 lodirty = numdirtybuffers / 2;
2584 * Do the flush. Limit the amount of in-transit I/O we
2585 * allow to build up, otherwise we would completely saturate
2588 while (numdirtybuffers > lodirty) {
2589 if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
2591 kern_yield(PRI_USER);
2595 * Only clear bd_request if we have reached our low water
2596 * mark. The buf_daemon normally waits 1 second and
2597 * then incrementally flushes any dirty buffers that have
2598 * built up, within reason.
2600 * If we were unable to hit our low water mark and couldn't
2601 * find any flushable buffers, we sleep for a short period
2602 * to avoid endless loops on unlockable buffers.
2605 if (numdirtybuffers <= lodirtybuffers) {
2607 * We reached our low water mark, reset the
2608 * request and sleep until we are needed again.
2609 * The sleep is just so the suspend code works.
2613 * Do an extra wakeup in case dirty threshold
2614 * changed via sysctl and the explicit transition
2615 * out of shortfall was missed.
2618 if (runningbufspace <= lorunningspace)
2620 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2623 * We couldn't find any flushable dirty buffers but
2624 * still have too many dirty buffers, we
2625 * have to sleep and try again. (rare)
2627 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2635 * Try to flush a buffer in the dirty queue. We must be careful to
2636 * free up B_INVAL buffers instead of write them, which NFS is
2637 * particularly sensitive to.
2639 static int flushwithdeps = 0;
2640 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2641 0, "Number of buffers flushed with dependecies that require rollbacks");
2644 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
2646 struct buf *sentinel;
2657 queue = QUEUE_DIRTY;
2659 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2660 sentinel->b_qindex = QUEUE_SENTINEL;
2662 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2663 mtx_unlock(&bqdirty);
2664 while (flushed != target) {
2667 bp = TAILQ_NEXT(sentinel, b_freelist);
2669 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2670 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2673 mtx_unlock(&bqdirty);
2677 * Skip sentinels inserted by other invocations of the
2678 * flushbufqueues(), taking care to not reorder them.
2680 * Only flush the buffers that belong to the
2681 * vnode locked by the curthread.
2683 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
2685 mtx_unlock(&bqdirty);
2688 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
2689 mtx_unlock(&bqdirty);
2692 if (bp->b_pin_count > 0) {
2697 * BKGRDINPROG can only be set with the buf and bufobj
2698 * locks both held. We tolerate a race to clear it here.
2700 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2701 (bp->b_flags & B_DELWRI) == 0) {
2705 if (bp->b_flags & B_INVAL) {
2712 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2713 if (flushdeps == 0) {
2721 * We must hold the lock on a vnode before writing
2722 * one of its buffers. Otherwise we may confuse, or
2723 * in the case of a snapshot vnode, deadlock the
2726 * The lock order here is the reverse of the normal
2727 * of vnode followed by buf lock. This is ok because
2728 * the NOWAIT will prevent deadlock.
2731 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2737 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
2739 ASSERT_VOP_LOCKED(vp, "getbuf");
2741 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
2742 vn_lock(vp, LK_TRYUPGRADE);
2745 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2746 bp, bp->b_vp, bp->b_flags);
2747 if (curproc == bufdaemonproc) {
2754 vn_finished_write(mp);
2757 flushwithdeps += hasdeps;
2761 * Sleeping on runningbufspace while holding
2762 * vnode lock leads to deadlock.
2764 if (curproc == bufdaemonproc &&
2765 runningbufspace > hirunningspace)
2766 waitrunningbufspace();
2769 vn_finished_write(mp);
2773 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2774 mtx_unlock(&bqdirty);
2775 free(sentinel, M_TEMP);
2780 * Check to see if a block is currently memory resident.
2783 incore(struct bufobj *bo, daddr_t blkno)
2788 bp = gbincore(bo, blkno);
2794 * Returns true if no I/O is needed to access the
2795 * associated VM object. This is like incore except
2796 * it also hunts around in the VM system for the data.
2800 inmem(struct vnode * vp, daddr_t blkno)
2803 vm_offset_t toff, tinc, size;
2807 ASSERT_VOP_LOCKED(vp, "inmem");
2809 if (incore(&vp->v_bufobj, blkno))
2811 if (vp->v_mount == NULL)
2818 if (size > vp->v_mount->mnt_stat.f_iosize)
2819 size = vp->v_mount->mnt_stat.f_iosize;
2820 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2822 VM_OBJECT_RLOCK(obj);
2823 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2824 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2828 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2829 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2830 if (vm_page_is_valid(m,
2831 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2834 VM_OBJECT_RUNLOCK(obj);
2838 VM_OBJECT_RUNLOCK(obj);
2843 * Set the dirty range for a buffer based on the status of the dirty
2844 * bits in the pages comprising the buffer. The range is limited
2845 * to the size of the buffer.
2847 * Tell the VM system that the pages associated with this buffer
2848 * are clean. This is used for delayed writes where the data is
2849 * going to go to disk eventually without additional VM intevention.
2851 * Note that while we only really need to clean through to b_bcount, we
2852 * just go ahead and clean through to b_bufsize.
2855 vfs_clean_pages_dirty_buf(struct buf *bp)
2857 vm_ooffset_t foff, noff, eoff;
2861 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2864 foff = bp->b_offset;
2865 KASSERT(bp->b_offset != NOOFFSET,
2866 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2868 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2869 vfs_drain_busy_pages(bp);
2870 vfs_setdirty_locked_object(bp);
2871 for (i = 0; i < bp->b_npages; i++) {
2872 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2874 if (eoff > bp->b_offset + bp->b_bufsize)
2875 eoff = bp->b_offset + bp->b_bufsize;
2877 vfs_page_set_validclean(bp, foff, m);
2878 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2881 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2885 vfs_setdirty_locked_object(struct buf *bp)
2890 object = bp->b_bufobj->bo_object;
2891 VM_OBJECT_ASSERT_WLOCKED(object);
2894 * We qualify the scan for modified pages on whether the
2895 * object has been flushed yet.
2897 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2898 vm_offset_t boffset;
2899 vm_offset_t eoffset;
2902 * test the pages to see if they have been modified directly
2903 * by users through the VM system.
2905 for (i = 0; i < bp->b_npages; i++)
2906 vm_page_test_dirty(bp->b_pages[i]);
2909 * Calculate the encompassing dirty range, boffset and eoffset,
2910 * (eoffset - boffset) bytes.
2913 for (i = 0; i < bp->b_npages; i++) {
2914 if (bp->b_pages[i]->dirty)
2917 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2919 for (i = bp->b_npages - 1; i >= 0; --i) {
2920 if (bp->b_pages[i]->dirty) {
2924 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2927 * Fit it to the buffer.
2930 if (eoffset > bp->b_bcount)
2931 eoffset = bp->b_bcount;
2934 * If we have a good dirty range, merge with the existing
2938 if (boffset < eoffset) {
2939 if (bp->b_dirtyoff > boffset)
2940 bp->b_dirtyoff = boffset;
2941 if (bp->b_dirtyend < eoffset)
2942 bp->b_dirtyend = eoffset;
2948 * Allocate the KVA mapping for an existing buffer. It handles the
2949 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2950 * KVA which is not mapped (B_KVAALLOC).
2953 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2955 struct buf *scratch_bp;
2956 int bsize, maxsize, need_mapping, need_kva;
2959 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2960 (gbflags & GB_UNMAPPED) == 0;
2961 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2962 (gbflags & GB_KVAALLOC) != 0;
2963 if (!need_mapping && !need_kva)
2966 BUF_CHECK_UNMAPPED(bp);
2968 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2970 * Buffer is not mapped, but the KVA was already
2971 * reserved at the time of the instantiation. Use the
2974 bp->b_flags &= ~B_KVAALLOC;
2975 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2976 bp->b_kvabase = bp->b_kvaalloc;
2977 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2982 * Calculate the amount of the address space we would reserve
2983 * if the buffer was mapped.
2985 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2986 offset = blkno * bsize;
2987 maxsize = size + (offset & PAGE_MASK);
2988 maxsize = imax(maxsize, bsize);
2991 if (allocbufkva(bp, maxsize, gbflags)) {
2993 * Request defragmentation. getnewbuf() returns us the
2994 * allocated space by the scratch buffer KVA.
2996 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2997 (GB_UNMAPPED | GB_KVAALLOC));
2998 if (scratch_bp == NULL) {
2999 if ((gbflags & GB_NOWAIT_BD) != 0) {
3001 * XXXKIB: defragmentation cannot
3002 * succeed, not sure what else to do.
3004 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
3006 atomic_add_int(&mappingrestarts, 1);
3009 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
3010 ("scratch bp !B_KVAALLOC %p", scratch_bp));
3011 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
3012 scratch_bp->b_kvasize, gbflags);
3014 /* Get rid of the scratch buffer. */
3015 scratch_bp->b_kvasize = 0;
3016 scratch_bp->b_flags |= B_INVAL;
3017 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
3024 bp->b_saveaddr = bp->b_kvabase;
3025 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
3026 bp->b_flags &= ~B_UNMAPPED;
3027 BUF_CHECK_MAPPED(bp);
3034 * Get a block given a specified block and offset into a file/device.
3035 * The buffers B_DONE bit will be cleared on return, making it almost
3036 * ready for an I/O initiation. B_INVAL may or may not be set on
3037 * return. The caller should clear B_INVAL prior to initiating a
3040 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3041 * an existing buffer.
3043 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3044 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3045 * and then cleared based on the backing VM. If the previous buffer is
3046 * non-0-sized but invalid, B_CACHE will be cleared.
3048 * If getblk() must create a new buffer, the new buffer is returned with
3049 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3050 * case it is returned with B_INVAL clear and B_CACHE set based on the
3053 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3054 * B_CACHE bit is clear.
3056 * What this means, basically, is that the caller should use B_CACHE to
3057 * determine whether the buffer is fully valid or not and should clear
3058 * B_INVAL prior to issuing a read. If the caller intends to validate
3059 * the buffer by loading its data area with something, the caller needs
3060 * to clear B_INVAL. If the caller does this without issuing an I/O,
3061 * the caller should set B_CACHE ( as an optimization ), else the caller
3062 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3063 * a write attempt or if it was a successfull read. If the caller
3064 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3065 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3068 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3073 int bsize, error, maxsize, vmio;
3076 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3077 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3078 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3079 ASSERT_VOP_LOCKED(vp, "getblk");
3080 if (size > MAXBCACHEBUF)
3081 panic("getblk: size(%d) > MAXBCACHEBUF(%d)\n", size,
3083 if (!unmapped_buf_allowed)
3084 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3089 bp = gbincore(bo, blkno);
3093 * Buffer is in-core. If the buffer is not busy nor managed,
3094 * it must be on a queue.
3096 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3098 if (flags & GB_LOCK_NOWAIT)
3099 lockflags |= LK_NOWAIT;
3101 error = BUF_TIMELOCK(bp, lockflags,
3102 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3105 * If we slept and got the lock we have to restart in case
3106 * the buffer changed identities.
3108 if (error == ENOLCK)
3110 /* We timed out or were interrupted. */
3113 /* If recursed, assume caller knows the rules. */
3114 else if (BUF_LOCKRECURSED(bp))
3118 * The buffer is locked. B_CACHE is cleared if the buffer is
3119 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3120 * and for a VMIO buffer B_CACHE is adjusted according to the
3123 if (bp->b_flags & B_INVAL)
3124 bp->b_flags &= ~B_CACHE;
3125 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3126 bp->b_flags |= B_CACHE;
3127 if (bp->b_flags & B_MANAGED)
3128 MPASS(bp->b_qindex == QUEUE_NONE);
3133 * check for size inconsistencies for non-VMIO case.
3135 if (bp->b_bcount != size) {
3136 if ((bp->b_flags & B_VMIO) == 0 ||
3137 (size > bp->b_kvasize)) {
3138 if (bp->b_flags & B_DELWRI) {
3140 * If buffer is pinned and caller does
3141 * not want sleep waiting for it to be
3142 * unpinned, bail out
3144 if (bp->b_pin_count > 0) {
3145 if (flags & GB_LOCK_NOWAIT) {
3152 bp->b_flags |= B_NOCACHE;
3155 if (LIST_EMPTY(&bp->b_dep)) {
3156 bp->b_flags |= B_RELBUF;
3159 bp->b_flags |= B_NOCACHE;
3168 * Handle the case of unmapped buffer which should
3169 * become mapped, or the buffer for which KVA
3170 * reservation is requested.
3172 bp_unmapped_get_kva(bp, blkno, size, flags);
3175 * If the size is inconsistant in the VMIO case, we can resize
3176 * the buffer. This might lead to B_CACHE getting set or
3177 * cleared. If the size has not changed, B_CACHE remains
3178 * unchanged from its previous state.
3180 if (bp->b_bcount != size)
3183 KASSERT(bp->b_offset != NOOFFSET,
3184 ("getblk: no buffer offset"));
3187 * A buffer with B_DELWRI set and B_CACHE clear must
3188 * be committed before we can return the buffer in
3189 * order to prevent the caller from issuing a read
3190 * ( due to B_CACHE not being set ) and overwriting
3193 * Most callers, including NFS and FFS, need this to
3194 * operate properly either because they assume they
3195 * can issue a read if B_CACHE is not set, or because
3196 * ( for example ) an uncached B_DELWRI might loop due
3197 * to softupdates re-dirtying the buffer. In the latter
3198 * case, B_CACHE is set after the first write completes,
3199 * preventing further loops.
3200 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3201 * above while extending the buffer, we cannot allow the
3202 * buffer to remain with B_CACHE set after the write
3203 * completes or it will represent a corrupt state. To
3204 * deal with this we set B_NOCACHE to scrap the buffer
3207 * We might be able to do something fancy, like setting
3208 * B_CACHE in bwrite() except if B_DELWRI is already set,
3209 * so the below call doesn't set B_CACHE, but that gets real
3210 * confusing. This is much easier.
3213 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3214 bp->b_flags |= B_NOCACHE;
3218 bp->b_flags &= ~B_DONE;
3221 * Buffer is not in-core, create new buffer. The buffer
3222 * returned by getnewbuf() is locked. Note that the returned
3223 * buffer is also considered valid (not marked B_INVAL).
3227 * If the user does not want us to create the buffer, bail out
3230 if (flags & GB_NOCREAT)
3232 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3235 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3236 offset = blkno * bsize;
3237 vmio = vp->v_object != NULL;
3239 maxsize = size + (offset & PAGE_MASK);
3242 /* Do not allow non-VMIO notmapped buffers. */
3243 flags &= ~GB_UNMAPPED;
3245 maxsize = imax(maxsize, bsize);
3247 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3249 if (slpflag || slptimeo)
3255 * This code is used to make sure that a buffer is not
3256 * created while the getnewbuf routine is blocked.
3257 * This can be a problem whether the vnode is locked or not.
3258 * If the buffer is created out from under us, we have to
3259 * throw away the one we just created.
3261 * Note: this must occur before we associate the buffer
3262 * with the vp especially considering limitations in
3263 * the splay tree implementation when dealing with duplicate
3267 if (gbincore(bo, blkno)) {
3269 bp->b_flags |= B_INVAL;
3275 * Insert the buffer into the hash, so that it can
3276 * be found by incore.
3278 bp->b_blkno = bp->b_lblkno = blkno;
3279 bp->b_offset = offset;
3284 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3285 * buffer size starts out as 0, B_CACHE will be set by
3286 * allocbuf() for the VMIO case prior to it testing the
3287 * backing store for validity.
3291 bp->b_flags |= B_VMIO;
3292 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3293 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3294 bp, vp->v_object, bp->b_bufobj->bo_object));
3296 bp->b_flags &= ~B_VMIO;
3297 KASSERT(bp->b_bufobj->bo_object == NULL,
3298 ("ARGH! has b_bufobj->bo_object %p %p\n",
3299 bp, bp->b_bufobj->bo_object));
3300 BUF_CHECK_MAPPED(bp);
3304 bp->b_flags &= ~B_DONE;
3306 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3307 BUF_ASSERT_HELD(bp);
3309 KASSERT(bp->b_bufobj == bo,
3310 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3315 * Get an empty, disassociated buffer of given size. The buffer is initially
3319 geteblk(int size, int flags)
3324 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3325 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3326 if ((flags & GB_NOWAIT_BD) &&
3327 (curthread->td_pflags & TDP_BUFNEED) != 0)
3331 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3332 BUF_ASSERT_HELD(bp);
3338 * This code constitutes the buffer memory from either anonymous system
3339 * memory (in the case of non-VMIO operations) or from an associated
3340 * VM object (in the case of VMIO operations). This code is able to
3341 * resize a buffer up or down.
3343 * Note that this code is tricky, and has many complications to resolve
3344 * deadlock or inconsistant data situations. Tread lightly!!!
3345 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3346 * the caller. Calling this code willy nilly can result in the loss of data.
3348 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3349 * B_CACHE for the non-VMIO case.
3353 allocbuf(struct buf *bp, int size)
3355 int newbsize, mbsize;
3358 BUF_ASSERT_HELD(bp);
3360 if (bp->b_kvasize < size)
3361 panic("allocbuf: buffer too small");
3363 if ((bp->b_flags & B_VMIO) == 0) {
3367 * Just get anonymous memory from the kernel. Don't
3368 * mess with B_CACHE.
3370 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3371 if (bp->b_flags & B_MALLOC)
3374 newbsize = round_page(size);
3376 if (newbsize < bp->b_bufsize) {
3378 * malloced buffers are not shrunk
3380 if (bp->b_flags & B_MALLOC) {
3382 bp->b_bcount = size;
3384 free(bp->b_data, M_BIOBUF);
3385 if (bp->b_bufsize) {
3386 atomic_subtract_long(
3392 bp->b_saveaddr = bp->b_kvabase;
3393 bp->b_data = bp->b_saveaddr;
3395 bp->b_flags &= ~B_MALLOC;
3399 vm_hold_free_pages(bp, newbsize);
3400 } else if (newbsize > bp->b_bufsize) {
3402 * We only use malloced memory on the first allocation.
3403 * and revert to page-allocated memory when the buffer
3407 * There is a potential smp race here that could lead
3408 * to bufmallocspace slightly passing the max. It
3409 * is probably extremely rare and not worth worrying
3412 if ( (bufmallocspace < maxbufmallocspace) &&
3413 (bp->b_bufsize == 0) &&
3414 (mbsize <= PAGE_SIZE/2)) {
3416 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3417 bp->b_bufsize = mbsize;
3418 bp->b_bcount = size;
3419 bp->b_flags |= B_MALLOC;
3420 atomic_add_long(&bufmallocspace, mbsize);
3426 * If the buffer is growing on its other-than-first allocation,
3427 * then we revert to the page-allocation scheme.
3429 if (bp->b_flags & B_MALLOC) {
3430 origbuf = bp->b_data;
3431 origbufsize = bp->b_bufsize;
3432 bp->b_data = bp->b_kvabase;
3433 if (bp->b_bufsize) {
3434 atomic_subtract_long(&bufmallocspace,
3439 bp->b_flags &= ~B_MALLOC;
3440 newbsize = round_page(newbsize);
3444 (vm_offset_t) bp->b_data + bp->b_bufsize,
3445 (vm_offset_t) bp->b_data + newbsize);
3447 bcopy(origbuf, bp->b_data, origbufsize);
3448 free(origbuf, M_BIOBUF);
3454 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3455 desiredpages = (size == 0) ? 0 :
3456 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3458 if (bp->b_flags & B_MALLOC)
3459 panic("allocbuf: VMIO buffer can't be malloced");
3461 * Set B_CACHE initially if buffer is 0 length or will become
3464 if (size == 0 || bp->b_bufsize == 0)
3465 bp->b_flags |= B_CACHE;
3467 if (newbsize < bp->b_bufsize) {
3469 * DEV_BSIZE aligned new buffer size is less then the
3470 * DEV_BSIZE aligned existing buffer size. Figure out
3471 * if we have to remove any pages.
3473 if (desiredpages < bp->b_npages) {
3476 if ((bp->b_flags & B_UNMAPPED) == 0) {
3477 BUF_CHECK_MAPPED(bp);
3478 pmap_qremove((vm_offset_t)trunc_page(
3479 (vm_offset_t)bp->b_data) +
3480 (desiredpages << PAGE_SHIFT),
3481 (bp->b_npages - desiredpages));
3483 BUF_CHECK_UNMAPPED(bp);
3484 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3485 for (i = desiredpages; i < bp->b_npages; i++) {
3487 * the page is not freed here -- it
3488 * is the responsibility of
3489 * vnode_pager_setsize
3492 KASSERT(m != bogus_page,
3493 ("allocbuf: bogus page found"));
3494 while (vm_page_sleep_if_busy(m,
3498 bp->b_pages[i] = NULL;
3500 vm_page_unwire(m, 0);
3503 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3504 bp->b_npages = desiredpages;
3506 } else if (size > bp->b_bcount) {
3508 * We are growing the buffer, possibly in a
3509 * byte-granular fashion.
3516 * Step 1, bring in the VM pages from the object,
3517 * allocating them if necessary. We must clear
3518 * B_CACHE if these pages are not valid for the
3519 * range covered by the buffer.
3522 obj = bp->b_bufobj->bo_object;
3524 VM_OBJECT_WLOCK(obj);
3525 while (bp->b_npages < desiredpages) {
3529 * We must allocate system pages since blocking
3530 * here could interfere with paging I/O, no
3531 * matter which process we are.
3533 * Only exclusive busy can be tested here.
3534 * Blocking on shared busy might lead to
3535 * deadlocks once allocbuf() is called after
3536 * pages are vfs_busy_pages().
3538 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3539 bp->b_npages, VM_ALLOC_NOBUSY |
3540 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3541 VM_ALLOC_IGN_SBUSY |
3542 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3544 bp->b_flags &= ~B_CACHE;
3545 bp->b_pages[bp->b_npages] = m;
3550 * Step 2. We've loaded the pages into the buffer,
3551 * we have to figure out if we can still have B_CACHE
3552 * set. Note that B_CACHE is set according to the
3553 * byte-granular range ( bcount and size ), new the
3554 * aligned range ( newbsize ).
3556 * The VM test is against m->valid, which is DEV_BSIZE
3557 * aligned. Needless to say, the validity of the data
3558 * needs to also be DEV_BSIZE aligned. Note that this
3559 * fails with NFS if the server or some other client
3560 * extends the file's EOF. If our buffer is resized,
3561 * B_CACHE may remain set! XXX
3564 toff = bp->b_bcount;
3565 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3567 while ((bp->b_flags & B_CACHE) && toff < size) {
3570 if (tinc > (size - toff))
3573 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3586 VM_OBJECT_WUNLOCK(obj);
3589 * Step 3, fixup the KVM pmap.
3591 if ((bp->b_flags & B_UNMAPPED) == 0)
3594 BUF_CHECK_UNMAPPED(bp);
3597 if (newbsize < bp->b_bufsize)
3599 bp->b_bufsize = newbsize; /* actual buffer allocation */
3600 bp->b_bcount = size; /* requested buffer size */
3604 extern int inflight_transient_maps;
3607 biodone(struct bio *bp)
3610 void (*done)(struct bio *);
3611 vm_offset_t start, end;
3613 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3614 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3615 bp->bio_flags |= BIO_UNMAPPED;
3616 start = trunc_page((vm_offset_t)bp->bio_data);
3617 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3618 pmap_qremove(start, OFF_TO_IDX(end - start));
3619 vmem_free(transient_arena, start, end - start);
3620 atomic_add_int(&inflight_transient_maps, -1);
3622 done = bp->bio_done;
3624 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3626 bp->bio_flags |= BIO_DONE;
3630 bp->bio_flags |= BIO_DONE;
3636 * Wait for a BIO to finish.
3639 biowait(struct bio *bp, const char *wchan)
3643 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3645 while ((bp->bio_flags & BIO_DONE) == 0)
3646 msleep(bp, mtxp, PRIBIO, wchan, 0);
3648 if (bp->bio_error != 0)
3649 return (bp->bio_error);
3650 if (!(bp->bio_flags & BIO_ERROR))
3656 biofinish(struct bio *bp, struct devstat *stat, int error)
3660 bp->bio_error = error;
3661 bp->bio_flags |= BIO_ERROR;
3664 devstat_end_transaction_bio(stat, bp);
3671 * Wait for buffer I/O completion, returning error status. The buffer
3672 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3673 * error and cleared.
3676 bufwait(struct buf *bp)
3678 if (bp->b_iocmd == BIO_READ)
3679 bwait(bp, PRIBIO, "biord");
3681 bwait(bp, PRIBIO, "biowr");
3682 if (bp->b_flags & B_EINTR) {
3683 bp->b_flags &= ~B_EINTR;
3686 if (bp->b_ioflags & BIO_ERROR) {
3687 return (bp->b_error ? bp->b_error : EIO);
3694 * Call back function from struct bio back up to struct buf.
3697 bufdonebio(struct bio *bip)
3701 bp = bip->bio_caller2;
3702 bp->b_resid = bp->b_bcount - bip->bio_completed;
3703 bp->b_resid = bip->bio_resid; /* XXX: remove */
3704 bp->b_ioflags = bip->bio_flags;
3705 bp->b_error = bip->bio_error;
3707 bp->b_ioflags |= BIO_ERROR;
3713 dev_strategy(struct cdev *dev, struct buf *bp)
3718 KASSERT(dev->si_refcount > 0,
3719 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3720 devtoname(dev), dev));
3722 csw = dev_refthread(dev, &ref);
3723 dev_strategy_csw(dev, csw, bp);
3724 dev_relthread(dev, ref);
3728 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3732 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3734 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3735 dev->si_threadcount > 0,
3736 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3739 bp->b_error = ENXIO;
3740 bp->b_ioflags = BIO_ERROR;
3748 /* Try again later */
3749 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3751 bip->bio_cmd = bp->b_iocmd;
3752 bip->bio_offset = bp->b_iooffset;
3753 bip->bio_length = bp->b_bcount;
3754 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3756 bip->bio_done = bufdonebio;
3757 bip->bio_caller2 = bp;
3759 (*csw->d_strategy)(bip);
3765 * Finish I/O on a buffer, optionally calling a completion function.
3766 * This is usually called from an interrupt so process blocking is
3769 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3770 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3771 * assuming B_INVAL is clear.
3773 * For the VMIO case, we set B_CACHE if the op was a read and no
3774 * read error occured, or if the op was a write. B_CACHE is never
3775 * set if the buffer is invalid or otherwise uncacheable.
3777 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3778 * initiator to leave B_INVAL set to brelse the buffer out of existance
3779 * in the biodone routine.
3782 bufdone(struct buf *bp)
3784 struct bufobj *dropobj;
3785 void (*biodone)(struct buf *);
3787 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3790 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3791 BUF_ASSERT_HELD(bp);
3793 runningbufwakeup(bp);
3794 if (bp->b_iocmd == BIO_WRITE)
3795 dropobj = bp->b_bufobj;
3796 /* call optional completion function if requested */
3797 if (bp->b_iodone != NULL) {
3798 biodone = bp->b_iodone;
3799 bp->b_iodone = NULL;
3802 bufobj_wdrop(dropobj);
3809 bufobj_wdrop(dropobj);
3813 bufdone_finish(struct buf *bp)
3815 BUF_ASSERT_HELD(bp);
3817 if (!LIST_EMPTY(&bp->b_dep))
3820 if (bp->b_flags & B_VMIO) {
3825 int bogus, i, iosize;
3827 obj = bp->b_bufobj->bo_object;
3828 KASSERT(obj->paging_in_progress >= bp->b_npages,
3829 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3830 obj->paging_in_progress, bp->b_npages));
3833 KASSERT(vp->v_holdcnt > 0,
3834 ("biodone_finish: vnode %p has zero hold count", vp));
3835 KASSERT(vp->v_object != NULL,
3836 ("biodone_finish: vnode %p has no vm_object", vp));
3838 foff = bp->b_offset;
3839 KASSERT(bp->b_offset != NOOFFSET,
3840 ("biodone_finish: bp %p has no buffer offset", bp));
3843 * Set B_CACHE if the op was a normal read and no error
3844 * occured. B_CACHE is set for writes in the b*write()
3847 iosize = bp->b_bcount - bp->b_resid;
3848 if (bp->b_iocmd == BIO_READ &&
3849 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3850 !(bp->b_ioflags & BIO_ERROR)) {
3851 bp->b_flags |= B_CACHE;
3854 VM_OBJECT_WLOCK(obj);
3855 for (i = 0; i < bp->b_npages; i++) {
3859 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3864 * cleanup bogus pages, restoring the originals
3867 if (m == bogus_page) {
3868 bogus = bogusflag = 1;
3869 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3871 panic("biodone: page disappeared!");
3874 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3875 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3876 (intmax_t)foff, (uintmax_t)m->pindex));
3879 * In the write case, the valid and clean bits are
3880 * already changed correctly ( see bdwrite() ), so we
3881 * only need to do this here in the read case.
3883 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3884 KASSERT((m->dirty & vm_page_bits(foff &
3885 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3886 " page %p has unexpected dirty bits", m));
3887 vfs_page_set_valid(bp, foff, m);
3891 vm_object_pip_subtract(obj, 1);
3892 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3895 vm_object_pip_wakeupn(obj, 0);
3896 VM_OBJECT_WUNLOCK(obj);
3897 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3898 BUF_CHECK_MAPPED(bp);
3899 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3900 bp->b_pages, bp->b_npages);
3905 * For asynchronous completions, release the buffer now. The brelse
3906 * will do a wakeup there if necessary - so no need to do a wakeup
3907 * here in the async case. The sync case always needs to do a wakeup.
3910 if (bp->b_flags & B_ASYNC) {
3911 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3920 * This routine is called in lieu of iodone in the case of
3921 * incomplete I/O. This keeps the busy status for pages
3925 vfs_unbusy_pages(struct buf *bp)
3931 runningbufwakeup(bp);
3932 if (!(bp->b_flags & B_VMIO))
3935 obj = bp->b_bufobj->bo_object;
3936 VM_OBJECT_WLOCK(obj);
3937 for (i = 0; i < bp->b_npages; i++) {
3939 if (m == bogus_page) {
3940 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3942 panic("vfs_unbusy_pages: page missing\n");
3944 if ((bp->b_flags & B_UNMAPPED) == 0) {
3945 BUF_CHECK_MAPPED(bp);
3946 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3947 bp->b_pages, bp->b_npages);
3949 BUF_CHECK_UNMAPPED(bp);
3951 vm_object_pip_subtract(obj, 1);
3954 vm_object_pip_wakeupn(obj, 0);
3955 VM_OBJECT_WUNLOCK(obj);
3959 * vfs_page_set_valid:
3961 * Set the valid bits in a page based on the supplied offset. The
3962 * range is restricted to the buffer's size.
3964 * This routine is typically called after a read completes.
3967 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3972 * Compute the end offset, eoff, such that [off, eoff) does not span a
3973 * page boundary and eoff is not greater than the end of the buffer.
3974 * The end of the buffer, in this case, is our file EOF, not the
3975 * allocation size of the buffer.
3977 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3978 if (eoff > bp->b_offset + bp->b_bcount)
3979 eoff = bp->b_offset + bp->b_bcount;
3982 * Set valid range. This is typically the entire buffer and thus the
3986 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3990 * vfs_page_set_validclean:
3992 * Set the valid bits and clear the dirty bits in a page based on the
3993 * supplied offset. The range is restricted to the buffer's size.
3996 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3998 vm_ooffset_t soff, eoff;
4001 * Start and end offsets in buffer. eoff - soff may not cross a
4002 * page boundry or cross the end of the buffer. The end of the
4003 * buffer, in this case, is our file EOF, not the allocation size
4007 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4008 if (eoff > bp->b_offset + bp->b_bcount)
4009 eoff = bp->b_offset + bp->b_bcount;
4012 * Set valid range. This is typically the entire buffer and thus the
4016 vm_page_set_validclean(
4018 (vm_offset_t) (soff & PAGE_MASK),
4019 (vm_offset_t) (eoff - soff)
4025 * Ensure that all buffer pages are not exclusive busied. If any page is
4026 * exclusive busy, drain it.
4029 vfs_drain_busy_pages(struct buf *bp)
4034 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4036 for (i = 0; i < bp->b_npages; i++) {
4038 if (vm_page_xbusied(m)) {
4039 for (; last_busied < i; last_busied++)
4040 vm_page_sbusy(bp->b_pages[last_busied]);
4041 while (vm_page_xbusied(m)) {
4043 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4044 vm_page_busy_sleep(m, "vbpage");
4045 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4049 for (i = 0; i < last_busied; i++)
4050 vm_page_sunbusy(bp->b_pages[i]);
4054 * This routine is called before a device strategy routine.
4055 * It is used to tell the VM system that paging I/O is in
4056 * progress, and treat the pages associated with the buffer
4057 * almost as being exclusive busy. Also the object paging_in_progress
4058 * flag is handled to make sure that the object doesn't become
4061 * Since I/O has not been initiated yet, certain buffer flags
4062 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4063 * and should be ignored.
4066 vfs_busy_pages(struct buf *bp, int clear_modify)
4073 if (!(bp->b_flags & B_VMIO))
4076 obj = bp->b_bufobj->bo_object;
4077 foff = bp->b_offset;
4078 KASSERT(bp->b_offset != NOOFFSET,
4079 ("vfs_busy_pages: no buffer offset"));
4080 VM_OBJECT_WLOCK(obj);
4081 vfs_drain_busy_pages(bp);
4082 if (bp->b_bufsize != 0)
4083 vfs_setdirty_locked_object(bp);
4085 for (i = 0; i < bp->b_npages; i++) {
4088 if ((bp->b_flags & B_CLUSTER) == 0) {
4089 vm_object_pip_add(obj, 1);
4093 * When readying a buffer for a read ( i.e
4094 * clear_modify == 0 ), it is important to do
4095 * bogus_page replacement for valid pages in
4096 * partially instantiated buffers. Partially
4097 * instantiated buffers can, in turn, occur when
4098 * reconstituting a buffer from its VM backing store
4099 * base. We only have to do this if B_CACHE is
4100 * clear ( which causes the I/O to occur in the
4101 * first place ). The replacement prevents the read
4102 * I/O from overwriting potentially dirty VM-backed
4103 * pages. XXX bogus page replacement is, uh, bogus.
4104 * It may not work properly with small-block devices.
4105 * We need to find a better way.
4108 pmap_remove_write(m);
4109 vfs_page_set_validclean(bp, foff, m);
4110 } else if (m->valid == VM_PAGE_BITS_ALL &&
4111 (bp->b_flags & B_CACHE) == 0) {
4112 bp->b_pages[i] = bogus_page;
4115 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4117 VM_OBJECT_WUNLOCK(obj);
4118 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4119 BUF_CHECK_MAPPED(bp);
4120 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4121 bp->b_pages, bp->b_npages);
4126 * vfs_bio_set_valid:
4128 * Set the range within the buffer to valid. The range is
4129 * relative to the beginning of the buffer, b_offset. Note that
4130 * b_offset itself may be offset from the beginning of the first
4134 vfs_bio_set_valid(struct buf *bp, int base, int size)
4139 if (!(bp->b_flags & B_VMIO))
4143 * Fixup base to be relative to beginning of first page.
4144 * Set initial n to be the maximum number of bytes in the
4145 * first page that can be validated.
4147 base += (bp->b_offset & PAGE_MASK);
4148 n = PAGE_SIZE - (base & PAGE_MASK);
4150 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4151 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4155 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4160 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4166 * If the specified buffer is a non-VMIO buffer, clear the entire
4167 * buffer. If the specified buffer is a VMIO buffer, clear and
4168 * validate only the previously invalid portions of the buffer.
4169 * This routine essentially fakes an I/O, so we need to clear
4170 * BIO_ERROR and B_INVAL.
4172 * Note that while we only theoretically need to clear through b_bcount,
4173 * we go ahead and clear through b_bufsize.
4176 vfs_bio_clrbuf(struct buf *bp)
4178 int i, j, mask, sa, ea, slide;
4180 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4184 bp->b_flags &= ~B_INVAL;
4185 bp->b_ioflags &= ~BIO_ERROR;
4186 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4187 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4188 (bp->b_offset & PAGE_MASK) == 0) {
4189 if (bp->b_pages[0] == bogus_page)
4191 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4192 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4193 if ((bp->b_pages[0]->valid & mask) == mask)
4195 if ((bp->b_pages[0]->valid & mask) == 0) {
4196 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4197 bp->b_pages[0]->valid |= mask;
4201 sa = bp->b_offset & PAGE_MASK;
4203 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4204 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4205 ea = slide & PAGE_MASK;
4208 if (bp->b_pages[i] == bogus_page)
4211 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4212 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4213 if ((bp->b_pages[i]->valid & mask) == mask)
4215 if ((bp->b_pages[i]->valid & mask) == 0)
4216 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4218 for (; sa < ea; sa += DEV_BSIZE, j++) {
4219 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4220 pmap_zero_page_area(bp->b_pages[i],
4225 bp->b_pages[i]->valid |= mask;
4228 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4233 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4238 if ((bp->b_flags & B_UNMAPPED) == 0) {
4239 BUF_CHECK_MAPPED(bp);
4240 bzero(bp->b_data + base, size);
4242 BUF_CHECK_UNMAPPED(bp);
4243 n = PAGE_SIZE - (base & PAGE_MASK);
4244 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4248 pmap_zero_page_area(m, base & PAGE_MASK, n);
4257 * vm_hold_load_pages and vm_hold_free_pages get pages into
4258 * a buffers address space. The pages are anonymous and are
4259 * not associated with a file object.
4262 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4268 BUF_CHECK_MAPPED(bp);
4270 to = round_page(to);
4271 from = round_page(from);
4272 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4274 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4277 * note: must allocate system pages since blocking here
4278 * could interfere with paging I/O, no matter which
4281 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4282 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4287 pmap_qenter(pg, &p, 1);
4288 bp->b_pages[index] = p;
4290 bp->b_npages = index;
4293 /* Return pages associated with this buf to the vm system */
4295 vm_hold_free_pages(struct buf *bp, int newbsize)
4299 int index, newnpages;
4301 BUF_CHECK_MAPPED(bp);
4303 from = round_page((vm_offset_t)bp->b_data + newbsize);
4304 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4305 if (bp->b_npages > newnpages)
4306 pmap_qremove(from, bp->b_npages - newnpages);
4307 for (index = newnpages; index < bp->b_npages; index++) {
4308 p = bp->b_pages[index];
4309 bp->b_pages[index] = NULL;
4310 if (vm_page_sbusied(p))
4311 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4312 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4315 atomic_subtract_int(&cnt.v_wire_count, 1);
4317 bp->b_npages = newnpages;
4321 * Map an IO request into kernel virtual address space.
4323 * All requests are (re)mapped into kernel VA space.
4324 * Notice that we use b_bufsize for the size of the buffer
4325 * to be mapped. b_bcount might be modified by the driver.
4327 * Note that even if the caller determines that the address space should
4328 * be valid, a race or a smaller-file mapped into a larger space may
4329 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4330 * check the return value.
4333 vmapbuf(struct buf *bp, int mapbuf)
4339 if (bp->b_bufsize < 0)
4341 prot = VM_PROT_READ;
4342 if (bp->b_iocmd == BIO_READ)
4343 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4344 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4345 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4346 btoc(MAXPHYS))) < 0)
4348 bp->b_npages = pidx;
4349 if (mapbuf || !unmapped_buf_allowed) {
4350 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4351 kva = bp->b_saveaddr;
4352 bp->b_saveaddr = bp->b_data;
4353 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4354 bp->b_flags &= ~B_UNMAPPED;
4356 bp->b_flags |= B_UNMAPPED;
4357 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4358 bp->b_saveaddr = bp->b_data;
4359 bp->b_data = unmapped_buf;
4365 * Free the io map PTEs associated with this IO operation.
4366 * We also invalidate the TLB entries and restore the original b_addr.
4369 vunmapbuf(struct buf *bp)
4373 npages = bp->b_npages;
4374 if (bp->b_flags & B_UNMAPPED)
4375 bp->b_flags &= ~B_UNMAPPED;
4377 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4378 vm_page_unhold_pages(bp->b_pages, npages);
4380 bp->b_data = bp->b_saveaddr;
4384 bdone(struct buf *bp)
4388 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4390 bp->b_flags |= B_DONE;
4396 bwait(struct buf *bp, u_char pri, const char *wchan)
4400 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4402 while ((bp->b_flags & B_DONE) == 0)
4403 msleep(bp, mtxp, pri, wchan, 0);
4408 bufsync(struct bufobj *bo, int waitfor)
4411 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4415 bufstrategy(struct bufobj *bo, struct buf *bp)
4421 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4422 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4423 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4424 i = VOP_STRATEGY(vp, bp);
4425 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4429 bufobj_wrefl(struct bufobj *bo)
4432 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4433 ASSERT_BO_WLOCKED(bo);
4438 bufobj_wref(struct bufobj *bo)
4441 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4448 bufobj_wdrop(struct bufobj *bo)
4451 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4453 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4454 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4455 bo->bo_flag &= ~BO_WWAIT;
4456 wakeup(&bo->bo_numoutput);
4462 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4466 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4467 ASSERT_BO_WLOCKED(bo);
4469 while (bo->bo_numoutput) {
4470 bo->bo_flag |= BO_WWAIT;
4471 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4472 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4480 bpin(struct buf *bp)
4484 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4491 bunpin(struct buf *bp)
4495 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4497 if (--bp->b_pin_count == 0)
4503 bunpin_wait(struct buf *bp)
4507 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4509 while (bp->b_pin_count > 0)
4510 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4515 * Set bio_data or bio_ma for struct bio from the struct buf.
4518 bdata2bio(struct buf *bp, struct bio *bip)
4521 if ((bp->b_flags & B_UNMAPPED) != 0) {
4522 KASSERT(unmapped_buf_allowed, ("unmapped"));
4523 bip->bio_ma = bp->b_pages;
4524 bip->bio_ma_n = bp->b_npages;
4525 bip->bio_data = unmapped_buf;
4526 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4527 bip->bio_flags |= BIO_UNMAPPED;
4528 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4529 PAGE_SIZE == bp->b_npages,
4530 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4531 (long long)bip->bio_length, bip->bio_ma_n));
4533 bip->bio_data = bp->b_data;
4538 #include "opt_ddb.h"
4540 #include <ddb/ddb.h>
4542 /* DDB command to show buffer data */
4543 DB_SHOW_COMMAND(buffer, db_show_buffer)
4546 struct buf *bp = (struct buf *)addr;
4549 db_printf("usage: show buffer <addr>\n");
4553 db_printf("buf at %p\n", bp);
4554 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4555 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4556 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4558 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4559 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4561 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4562 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4563 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4566 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4567 for (i = 0; i < bp->b_npages; i++) {
4570 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4571 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4572 if ((i + 1) < bp->b_npages)
4578 BUF_LOCKPRINTINFO(bp);
4581 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4586 for (i = 0; i < nbuf; i++) {
4588 if (BUF_ISLOCKED(bp)) {
4589 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4595 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4601 db_printf("usage: show vnodebufs <addr>\n");
4604 vp = (struct vnode *)addr;
4605 db_printf("Clean buffers:\n");
4606 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4607 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4610 db_printf("Dirty buffers:\n");
4611 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4612 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4617 DB_COMMAND(countfreebufs, db_coundfreebufs)
4620 int i, used = 0, nfree = 0;
4623 db_printf("usage: countfreebufs\n");
4627 for (i = 0; i < nbuf; i++) {
4629 if ((bp->b_flags & B_INFREECNT) != 0)
4635 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4637 db_printf("numfreebuffers is %d\n", numfreebuffers);