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(int);
117 static int flushbufqueues(int, int);
118 static void buf_daemon(void);
119 static void bremfreel(struct buf *bp);
120 static __inline void bd_wakeup(void);
121 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
122 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
123 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
124 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
127 int vmiodirenable = TRUE;
128 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
129 "Use the VM system for directory writes");
130 long runningbufspace;
131 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
132 "Amount of presently outstanding async buffer io");
133 static long bufspace;
134 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
135 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
136 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
137 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
139 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
140 "Virtual memory used for buffers");
142 static long unmapped_bufspace;
143 SYSCTL_LONG(_vfs, OID_AUTO, unmapped_bufspace, CTLFLAG_RD,
144 &unmapped_bufspace, 0,
145 "Amount of unmapped buffers, inclusive in the bufspace");
146 static long maxbufspace;
147 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
148 "Maximum allowed value of bufspace (including buf_daemon)");
149 static long bufmallocspace;
150 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
151 "Amount of malloced memory for buffers");
152 static long maxbufmallocspace;
153 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
154 "Maximum amount of malloced memory for buffers");
155 static long lobufspace;
156 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
157 "Minimum amount of buffers we want to have");
159 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
160 "Maximum allowed value of bufspace (excluding buf_daemon)");
161 static int bufreusecnt;
162 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
163 "Number of times we have reused a buffer");
164 static int buffreekvacnt;
165 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
166 "Number of times we have freed the KVA space from some buffer");
167 static int bufdefragcnt;
168 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
169 "Number of times we have had to repeat buffer allocation to defragment");
170 static long lorunningspace;
171 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
172 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
173 "Minimum preferred space used for in-progress I/O");
174 static long hirunningspace;
175 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
176 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
177 "Maximum amount of space to use for in-progress I/O");
178 int dirtybufferflushes;
179 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
180 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
182 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
183 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
184 int altbufferflushes;
185 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
186 0, "Number of fsync flushes to limit dirty buffers");
187 static int recursiveflushes;
188 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
189 0, "Number of flushes skipped due to being recursive");
190 static int numdirtybuffers;
191 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
192 "Number of buffers that are dirty (has unwritten changes) at the moment");
193 static int lodirtybuffers;
194 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
195 "How many buffers we want to have free before bufdaemon can sleep");
196 static int hidirtybuffers;
197 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
198 "When the number of dirty buffers is considered severe");
200 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
201 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
202 static int numfreebuffers;
203 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
204 "Number of free buffers");
205 static int lofreebuffers;
206 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
208 static int hifreebuffers;
209 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
210 "XXX Complicatedly unused");
211 static int getnewbufcalls;
212 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
213 "Number of calls to getnewbuf");
214 static int getnewbufrestarts;
215 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
216 "Number of times getnewbuf has had to restart a buffer aquisition");
217 static int mappingrestarts;
218 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
219 "Number of times getblk has had to restart a buffer mapping for "
221 static int flushbufqtarget = 100;
222 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
223 "Amount of work to do in flushbufqueues when helping bufdaemon");
224 static long notbufdflushes;
225 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 0,
226 "Number of dirty buffer flushes done by the bufdaemon helpers");
227 static long barrierwrites;
228 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
229 "Number of barrier writes");
230 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
231 &unmapped_buf_allowed, 0,
232 "Permit the use of the unmapped i/o");
235 * Lock for the non-dirty bufqueues
237 static struct mtx_padalign bqclean;
240 * Lock for the dirty queue.
242 static struct mtx_padalign bqdirty;
245 * This lock synchronizes access to bd_request.
247 static struct mtx_padalign bdlock;
250 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
251 * waitrunningbufspace().
253 static struct mtx_padalign rbreqlock;
256 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
258 static struct rwlock_padalign nblock;
261 * Lock that protects bdirtywait.
263 static struct mtx_padalign bdirtylock;
266 * Wakeup point for bufdaemon, as well as indicator of whether it is already
267 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
270 static int bd_request;
273 * Request for the buf daemon to write more buffers than is indicated by
274 * lodirtybuf. This may be necessary to push out excess dependencies or
275 * defragment the address space where a simple count of the number of dirty
276 * buffers is insufficient to characterize the demand for flushing them.
278 static int bd_speedupreq;
281 * bogus page -- for I/O to/from partially complete buffers
282 * this is a temporary solution to the problem, but it is not
283 * really that bad. it would be better to split the buffer
284 * for input in the case of buffers partially already in memory,
285 * but the code is intricate enough already.
287 vm_page_t bogus_page;
290 * Synchronization (sleep/wakeup) variable for active buffer space requests.
291 * Set when wait starts, cleared prior to wakeup().
292 * Used in runningbufwakeup() and waitrunningbufspace().
294 static int runningbufreq;
297 * Synchronization (sleep/wakeup) variable for buffer requests.
298 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
300 * Used in numdirtywakeup(), bufspacewakeup(), bufcountadd(), bwillwrite(),
301 * getnewbuf(), and getblk().
303 static volatile int needsbuffer;
306 * Synchronization for bwillwrite() waiters.
308 static int bdirtywait;
311 * Definitions for the buffer free lists.
313 #define BUFFER_QUEUES 5 /* number of free buffer queues */
315 #define QUEUE_NONE 0 /* on no queue */
316 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */
317 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
318 #define QUEUE_EMPTYKVA 3 /* empty buffer headers w/KVA assignment */
319 #define QUEUE_EMPTY 4 /* empty buffer headers */
320 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
322 /* Queues for free buffers with various properties */
323 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
325 static int bq_len[BUFFER_QUEUES];
329 * Single global constant for BUF_WMESG, to avoid getting multiple references.
330 * buf_wmesg is referred from macros.
332 const char *buf_wmesg = BUF_WMESG;
334 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
335 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
336 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
339 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
344 value = *(long *)arg1;
345 error = sysctl_handle_long(oidp, &value, 0, req);
346 if (error != 0 || req->newptr == NULL)
348 mtx_lock(&rbreqlock);
349 if (arg1 == &hirunningspace) {
350 if (value < lorunningspace)
353 hirunningspace = value;
355 KASSERT(arg1 == &lorunningspace,
356 ("%s: unknown arg1", __func__));
357 if (value > hirunningspace)
360 lorunningspace = value;
362 mtx_unlock(&rbreqlock);
366 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
367 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
369 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
374 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
375 return (sysctl_handle_long(oidp, arg1, arg2, req));
376 lvalue = *(long *)arg1;
377 if (lvalue > INT_MAX)
378 /* On overflow, still write out a long to trigger ENOMEM. */
379 return (sysctl_handle_long(oidp, &lvalue, 0, req));
381 return (sysctl_handle_int(oidp, &ivalue, 0, req));
388 * Return the appropriate queue lock based on the index.
390 static inline struct mtx *
394 if (qindex == QUEUE_DIRTY)
395 return (struct mtx *)(&bqdirty);
396 return (struct mtx *)(&bqclean);
402 * Wakeup any bwillwrite() waiters.
407 mtx_lock(&bdirtylock);
412 mtx_unlock(&bdirtylock);
418 * Decrement the numdirtybuffers count by one and wakeup any
419 * threads blocked in bwillwrite().
425 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
426 (lodirtybuffers + hidirtybuffers) / 2)
433 * Increment the numdirtybuffers count by one and wakeup the buf
441 * Only do the wakeup once as we cross the boundary. The
442 * buf daemon will keep running until the condition clears.
444 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
445 (lodirtybuffers + hidirtybuffers) / 2)
452 * Called when buffer space is potentially available for recovery.
453 * getnewbuf() will block on this flag when it is unable to free
454 * sufficient buffer space. Buffer space becomes recoverable when
455 * bp's get placed back in the queues.
464 * If someone is waiting for BUF space, wake them up. Even
465 * though we haven't freed the kva space yet, the waiting
466 * process will be able to now.
472 if ((on & VFS_BIO_NEED_BUFSPACE) == 0)
475 if (atomic_cmpset_rel_int(&needsbuffer, on,
476 on & ~VFS_BIO_NEED_BUFSPACE))
480 wakeup(__DEVOLATILE(void *, &needsbuffer));
487 * Wake up processes that are waiting on asynchronous writes to fall
488 * below lorunningspace.
494 mtx_lock(&rbreqlock);
497 wakeup(&runningbufreq);
499 mtx_unlock(&rbreqlock);
505 * Decrement the outstanding write count according.
508 runningbufwakeup(struct buf *bp)
512 bspace = bp->b_runningbufspace;
515 space = atomic_fetchadd_long(&runningbufspace, -bspace);
516 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
518 bp->b_runningbufspace = 0;
520 * Only acquire the lock and wakeup on the transition from exceeding
521 * the threshold to falling below it.
523 if (space < lorunningspace)
525 if (space - bspace > lorunningspace)
533 * Called when a buffer has been added to one of the free queues to
534 * account for the buffer and to wakeup anyone waiting for free buffers.
535 * This typically occurs when large amounts of metadata are being handled
536 * by the buffer cache ( else buffer space runs out first, usually ).
539 bufcountadd(struct buf *bp)
541 int mask, need_wakeup, old, on;
543 KASSERT((bp->b_flags & B_INFREECNT) == 0,
544 ("buf %p already counted as free", bp));
545 bp->b_flags |= B_INFREECNT;
546 old = atomic_fetchadd_int(&numfreebuffers, 1);
547 KASSERT(old >= 0 && old < nbuf,
548 ("numfreebuffers climbed to %d", old + 1));
549 mask = VFS_BIO_NEED_ANY;
550 if (numfreebuffers >= hifreebuffers)
551 mask |= VFS_BIO_NEED_FREE;
559 if (atomic_cmpset_rel_int(&needsbuffer, on, on & ~mask))
563 wakeup(__DEVOLATILE(void *, &needsbuffer));
570 * Decrement the numfreebuffers count as needed.
573 bufcountsub(struct buf *bp)
578 * Fixup numfreebuffers count. If the buffer is invalid or not
579 * delayed-write, the buffer was free and we must decrement
582 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
583 KASSERT((bp->b_flags & B_INFREECNT) != 0,
584 ("buf %p not counted in numfreebuffers", bp));
585 bp->b_flags &= ~B_INFREECNT;
586 old = atomic_fetchadd_int(&numfreebuffers, -1);
587 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
592 * waitrunningbufspace()
594 * runningbufspace is a measure of the amount of I/O currently
595 * running. This routine is used in async-write situations to
596 * prevent creating huge backups of pending writes to a device.
597 * Only asynchronous writes are governed by this function.
599 * This does NOT turn an async write into a sync write. It waits
600 * for earlier writes to complete and generally returns before the
601 * caller's write has reached the device.
604 waitrunningbufspace(void)
607 mtx_lock(&rbreqlock);
608 while (runningbufspace > hirunningspace) {
610 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
612 mtx_unlock(&rbreqlock);
617 * vfs_buf_test_cache:
619 * Called when a buffer is extended. This function clears the B_CACHE
620 * bit if the newly extended portion of the buffer does not contain
625 vfs_buf_test_cache(struct buf *bp,
626 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
630 VM_OBJECT_ASSERT_LOCKED(m->object);
631 if (bp->b_flags & B_CACHE) {
632 int base = (foff + off) & PAGE_MASK;
633 if (vm_page_is_valid(m, base, size) == 0)
634 bp->b_flags &= ~B_CACHE;
638 /* Wake up the buffer daemon if necessary */
644 if (bd_request == 0) {
652 * bd_speedup - speedup the buffer cache flushing code
661 if (bd_speedupreq == 0 || bd_request == 0)
671 #define NSWBUF_MIN 16
675 #define TRANSIENT_DENOM 5
677 #define TRANSIENT_DENOM 10
681 * Calculating buffer cache scaling values and reserve space for buffer
682 * headers. This is called during low level kernel initialization and
683 * may be called more then once. We CANNOT write to the memory area
684 * being reserved at this time.
687 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
690 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
693 * physmem_est is in pages. Convert it to kilobytes (assumes
694 * PAGE_SIZE is >= 1K)
696 physmem_est = physmem_est * (PAGE_SIZE / 1024);
699 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
700 * For the first 64MB of ram nominally allocate sufficient buffers to
701 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
702 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
703 * the buffer cache we limit the eventual kva reservation to
706 * factor represents the 1/4 x ram conversion.
709 int factor = 4 * BKVASIZE / 1024;
712 if (physmem_est > 4096)
713 nbuf += min((physmem_est - 4096) / factor,
715 if (physmem_est > 65536)
716 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
717 32 * 1024 * 1024 / (factor * 5));
719 if (maxbcache && nbuf > maxbcache / BKVASIZE)
720 nbuf = maxbcache / BKVASIZE;
725 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
726 maxbuf = (LONG_MAX / 3) / BKVASIZE;
729 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
735 * Ideal allocation size for the transient bio submap is 10%
736 * of the maximal space buffer map. This roughly corresponds
737 * to the amount of the buffer mapped for typical UFS load.
739 * Clip the buffer map to reserve space for the transient
740 * BIOs, if its extent is bigger than 90% (80% on i386) of the
741 * maximum buffer map extent on the platform.
743 * The fall-back to the maxbuf in case of maxbcache unset,
744 * allows to not trim the buffer KVA for the architectures
745 * with ample KVA space.
747 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
748 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
749 buf_sz = (long)nbuf * BKVASIZE;
750 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
751 (TRANSIENT_DENOM - 1)) {
753 * There is more KVA than memory. Do not
754 * adjust buffer map size, and assign the rest
755 * of maxbuf to transient map.
757 biotmap_sz = maxbuf_sz - buf_sz;
760 * Buffer map spans all KVA we could afford on
761 * this platform. Give 10% (20% on i386) of
762 * the buffer map to the transient bio map.
764 biotmap_sz = buf_sz / TRANSIENT_DENOM;
765 buf_sz -= biotmap_sz;
767 if (biotmap_sz / INT_MAX > MAXPHYS)
768 bio_transient_maxcnt = INT_MAX;
770 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
772 * Artifically limit to 1024 simultaneous in-flight I/Os
773 * using the transient mapping.
775 if (bio_transient_maxcnt > 1024)
776 bio_transient_maxcnt = 1024;
778 nbuf = buf_sz / BKVASIZE;
782 * swbufs are used as temporary holders for I/O, such as paging I/O.
783 * We have no less then 16 and no more then 256.
785 nswbuf = min(nbuf / 4, 256);
786 TUNABLE_INT_FETCH("kern.nswbuf", &nswbuf);
787 if (nswbuf < NSWBUF_MIN)
791 * Reserve space for the buffer cache buffers
794 v = (caddr_t)(swbuf + nswbuf);
796 v = (caddr_t)(buf + nbuf);
801 /* Initialize the buffer subsystem. Called before use of any buffers. */
808 CTASSERT(MAXBCACHEBUF >= MAXBSIZE);
809 mtx_init(&bqclean, "bufq clean lock", NULL, MTX_DEF);
810 mtx_init(&bqdirty, "bufq dirty lock", NULL, MTX_DEF);
811 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
812 rw_init(&nblock, "needsbuffer lock");
813 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
814 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
816 /* next, make a null set of free lists */
817 for (i = 0; i < BUFFER_QUEUES; i++)
818 TAILQ_INIT(&bufqueues[i]);
820 /* finally, initialize each buffer header and stick on empty q */
821 for (i = 0; i < nbuf; i++) {
823 bzero(bp, sizeof *bp);
824 bp->b_flags = B_INVAL | B_INFREECNT;
825 bp->b_rcred = NOCRED;
826 bp->b_wcred = NOCRED;
827 bp->b_qindex = QUEUE_EMPTY;
829 LIST_INIT(&bp->b_dep);
831 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
833 bq_len[QUEUE_EMPTY]++;
838 * maxbufspace is the absolute maximum amount of buffer space we are
839 * allowed to reserve in KVM and in real terms. The absolute maximum
840 * is nominally used by buf_daemon. hibufspace is the nominal maximum
841 * used by most other processes. The differential is required to
842 * ensure that buf_daemon is able to run when other processes might
843 * be blocked waiting for buffer space.
845 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
846 * this may result in KVM fragmentation which is not handled optimally
849 maxbufspace = (long)nbuf * BKVASIZE;
850 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBCACHEBUF * 10);
851 lobufspace = hibufspace - MAXBCACHEBUF;
854 * Note: The 16 MiB upper limit for hirunningspace was chosen
855 * arbitrarily and may need further tuning. It corresponds to
856 * 128 outstanding write IO requests (if IO size is 128 KiB),
857 * which fits with many RAID controllers' tagged queuing limits.
858 * The lower 1 MiB limit is the historical upper limit for
861 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBCACHEBUF),
862 16 * 1024 * 1024), 1024 * 1024);
863 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBCACHEBUF);
866 * Limit the amount of malloc memory since it is wired permanently into
867 * the kernel space. Even though this is accounted for in the buffer
868 * allocation, we don't want the malloced region to grow uncontrolled.
869 * The malloc scheme improves memory utilization significantly on average
870 * (small) directories.
872 maxbufmallocspace = hibufspace / 20;
875 * Reduce the chance of a deadlock occuring by limiting the number
876 * of delayed-write dirty buffers we allow to stack up.
878 hidirtybuffers = nbuf / 4 + 20;
879 dirtybufthresh = hidirtybuffers * 9 / 10;
882 * To support extreme low-memory systems, make sure hidirtybuffers cannot
883 * eat up all available buffer space. This occurs when our minimum cannot
884 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
885 * BKVASIZE'd buffers.
887 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
888 hidirtybuffers >>= 1;
890 lodirtybuffers = hidirtybuffers / 2;
893 * Try to keep the number of free buffers in the specified range,
894 * and give special processes (e.g. like buf_daemon) access to an
897 lofreebuffers = nbuf / 18 + 5;
898 hifreebuffers = 2 * lofreebuffers;
899 numfreebuffers = nbuf;
901 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
902 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
903 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
908 vfs_buf_check_mapped(struct buf *bp)
911 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
912 ("mapped buf %p %x", bp, bp->b_flags));
913 KASSERT(bp->b_kvabase != unmapped_buf,
914 ("mapped buf: b_kvabase was not updated %p", bp));
915 KASSERT(bp->b_data != unmapped_buf,
916 ("mapped buf: b_data was not updated %p", bp));
920 vfs_buf_check_unmapped(struct buf *bp)
923 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
924 ("unmapped buf %p %x", bp, bp->b_flags));
925 KASSERT(bp->b_kvabase == unmapped_buf,
926 ("unmapped buf: corrupted b_kvabase %p", bp));
927 KASSERT(bp->b_data == unmapped_buf,
928 ("unmapped buf: corrupted b_data %p", bp));
931 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
932 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
934 #define BUF_CHECK_MAPPED(bp) do {} while (0)
935 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
939 bpmap_qenter(struct buf *bp)
942 BUF_CHECK_MAPPED(bp);
945 * bp->b_data is relative to bp->b_offset, but
946 * bp->b_offset may be offset into the first page.
948 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
949 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
950 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
951 (vm_offset_t)(bp->b_offset & PAGE_MASK));
955 * bfreekva() - free the kva allocation for a buffer.
957 * Since this call frees up buffer space, we call bufspacewakeup().
960 bfreekva(struct buf *bp)
963 if (bp->b_kvasize == 0)
966 atomic_add_int(&buffreekvacnt, 1);
967 atomic_subtract_long(&bufspace, bp->b_kvasize);
968 if ((bp->b_flags & B_UNMAPPED) == 0) {
969 BUF_CHECK_MAPPED(bp);
970 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase,
973 BUF_CHECK_UNMAPPED(bp);
974 if ((bp->b_flags & B_KVAALLOC) != 0) {
975 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvaalloc,
978 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
979 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
988 * Insert the buffer into the appropriate free list.
991 binsfree(struct buf *bp, int qindex)
993 struct mtx *olock, *nlock;
995 BUF_ASSERT_XLOCKED(bp);
997 olock = bqlock(bp->b_qindex);
998 nlock = bqlock(qindex);
1000 /* Handle delayed bremfree() processing. */
1001 if (bp->b_flags & B_REMFREE)
1004 if (bp->b_qindex != QUEUE_NONE)
1005 panic("binsfree: free buffer onto another queue???");
1007 bp->b_qindex = qindex;
1008 if (olock != nlock) {
1012 if (bp->b_flags & B_AGE)
1013 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1015 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1017 bq_len[bp->b_qindex]++;
1022 * Something we can maybe free or reuse.
1024 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1027 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1034 * Mark the buffer for removal from the appropriate free list.
1038 bremfree(struct buf *bp)
1041 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1042 KASSERT((bp->b_flags & B_REMFREE) == 0,
1043 ("bremfree: buffer %p already marked for delayed removal.", bp));
1044 KASSERT(bp->b_qindex != QUEUE_NONE,
1045 ("bremfree: buffer %p not on a queue.", bp));
1046 BUF_ASSERT_XLOCKED(bp);
1048 bp->b_flags |= B_REMFREE;
1055 * Force an immediate removal from a free list. Used only in nfs when
1056 * it abuses the b_freelist pointer.
1059 bremfreef(struct buf *bp)
1063 qlock = bqlock(bp->b_qindex);
1072 * Removes a buffer from the free list, must be called with the
1073 * correct qlock held.
1076 bremfreel(struct buf *bp)
1079 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1080 bp, bp->b_vp, bp->b_flags);
1081 KASSERT(bp->b_qindex != QUEUE_NONE,
1082 ("bremfreel: buffer %p not on a queue.", bp));
1083 BUF_ASSERT_XLOCKED(bp);
1084 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1086 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1088 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1090 bq_len[bp->b_qindex]--;
1092 bp->b_qindex = QUEUE_NONE;
1094 * If this was a delayed bremfree() we only need to remove the buffer
1095 * from the queue and return the stats are already done.
1097 if (bp->b_flags & B_REMFREE) {
1098 bp->b_flags &= ~B_REMFREE;
1105 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1106 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1107 * the buffer is valid and we do not have to do anything.
1110 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1111 int cnt, struct ucred * cred)
1116 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1117 if (inmem(vp, *rablkno))
1119 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1121 if ((rabp->b_flags & B_CACHE) == 0) {
1122 if (!TD_IS_IDLETHREAD(curthread))
1123 curthread->td_ru.ru_inblock++;
1124 rabp->b_flags |= B_ASYNC;
1125 rabp->b_flags &= ~B_INVAL;
1126 rabp->b_ioflags &= ~BIO_ERROR;
1127 rabp->b_iocmd = BIO_READ;
1128 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1129 rabp->b_rcred = crhold(cred);
1130 vfs_busy_pages(rabp, 0);
1132 rabp->b_iooffset = dbtob(rabp->b_blkno);
1141 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1143 * Get a buffer with the specified data. Look in the cache first. We
1144 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1145 * is set, the buffer is valid and we do not have to do anything, see
1146 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1149 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1150 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1153 int rv = 0, readwait = 0;
1155 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1157 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1159 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1163 /* if not found in cache, do some I/O */
1164 if ((bp->b_flags & B_CACHE) == 0) {
1165 if (!TD_IS_IDLETHREAD(curthread))
1166 curthread->td_ru.ru_inblock++;
1167 bp->b_iocmd = BIO_READ;
1168 bp->b_flags &= ~B_INVAL;
1169 bp->b_ioflags &= ~BIO_ERROR;
1170 if (bp->b_rcred == NOCRED && cred != NOCRED)
1171 bp->b_rcred = crhold(cred);
1172 vfs_busy_pages(bp, 0);
1173 bp->b_iooffset = dbtob(bp->b_blkno);
1178 breada(vp, rablkno, rabsize, cnt, cred);
1187 * Write, release buffer on completion. (Done by iodone
1188 * if async). Do not bother writing anything if the buffer
1191 * Note that we set B_CACHE here, indicating that buffer is
1192 * fully valid and thus cacheable. This is true even of NFS
1193 * now so we set it generally. This could be set either here
1194 * or in biodone() since the I/O is synchronous. We put it
1198 bufwrite(struct buf *bp)
1205 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1206 if (bp->b_flags & B_INVAL) {
1211 if (bp->b_flags & B_BARRIER)
1214 oldflags = bp->b_flags;
1216 BUF_ASSERT_HELD(bp);
1218 if (bp->b_pin_count > 0)
1221 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1222 ("FFS background buffer should not get here %p", bp));
1226 vp_md = vp->v_vflag & VV_MD;
1231 * Mark the buffer clean. Increment the bufobj write count
1232 * before bundirty() call, to prevent other thread from seeing
1233 * empty dirty list and zero counter for writes in progress,
1234 * falsely indicating that the bufobj is clean.
1236 bufobj_wref(bp->b_bufobj);
1239 bp->b_flags &= ~B_DONE;
1240 bp->b_ioflags &= ~BIO_ERROR;
1241 bp->b_flags |= B_CACHE;
1242 bp->b_iocmd = BIO_WRITE;
1244 vfs_busy_pages(bp, 1);
1247 * Normal bwrites pipeline writes
1249 bp->b_runningbufspace = bp->b_bufsize;
1250 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1252 if (!TD_IS_IDLETHREAD(curthread))
1253 curthread->td_ru.ru_oublock++;
1254 if (oldflags & B_ASYNC)
1256 bp->b_iooffset = dbtob(bp->b_blkno);
1259 if ((oldflags & B_ASYNC) == 0) {
1260 int rtval = bufwait(bp);
1263 } else if (space > hirunningspace) {
1265 * don't allow the async write to saturate the I/O
1266 * system. We will not deadlock here because
1267 * we are blocking waiting for I/O that is already in-progress
1268 * to complete. We do not block here if it is the update
1269 * or syncer daemon trying to clean up as that can lead
1272 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1273 waitrunningbufspace();
1280 bufbdflush(struct bufobj *bo, struct buf *bp)
1284 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1285 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1287 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1290 * Try to find a buffer to flush.
1292 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1293 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1295 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1298 panic("bdwrite: found ourselves");
1300 /* Don't countdeps with the bo lock held. */
1301 if (buf_countdeps(nbp, 0)) {
1306 if (nbp->b_flags & B_CLUSTEROK) {
1307 vfs_bio_awrite(nbp);
1312 dirtybufferflushes++;
1321 * Delayed write. (Buffer is marked dirty). Do not bother writing
1322 * anything if the buffer is marked invalid.
1324 * Note that since the buffer must be completely valid, we can safely
1325 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1326 * biodone() in order to prevent getblk from writing the buffer
1327 * out synchronously.
1330 bdwrite(struct buf *bp)
1332 struct thread *td = curthread;
1336 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1337 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1338 KASSERT((bp->b_flags & B_BARRIER) == 0,
1339 ("Barrier request in delayed write %p", bp));
1340 BUF_ASSERT_HELD(bp);
1342 if (bp->b_flags & B_INVAL) {
1348 * If we have too many dirty buffers, don't create any more.
1349 * If we are wildly over our limit, then force a complete
1350 * cleanup. Otherwise, just keep the situation from getting
1351 * out of control. Note that we have to avoid a recursive
1352 * disaster and not try to clean up after our own cleanup!
1356 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1357 td->td_pflags |= TDP_INBDFLUSH;
1359 td->td_pflags &= ~TDP_INBDFLUSH;
1365 * Set B_CACHE, indicating that the buffer is fully valid. This is
1366 * true even of NFS now.
1368 bp->b_flags |= B_CACHE;
1371 * This bmap keeps the system from needing to do the bmap later,
1372 * perhaps when the system is attempting to do a sync. Since it
1373 * is likely that the indirect block -- or whatever other datastructure
1374 * that the filesystem needs is still in memory now, it is a good
1375 * thing to do this. Note also, that if the pageout daemon is
1376 * requesting a sync -- there might not be enough memory to do
1377 * the bmap then... So, this is important to do.
1379 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1380 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1384 * Set the *dirty* buffer range based upon the VM system dirty
1387 * Mark the buffer pages as clean. We need to do this here to
1388 * satisfy the vnode_pager and the pageout daemon, so that it
1389 * thinks that the pages have been "cleaned". Note that since
1390 * the pages are in a delayed write buffer -- the VFS layer
1391 * "will" see that the pages get written out on the next sync,
1392 * or perhaps the cluster will be completed.
1394 vfs_clean_pages_dirty_buf(bp);
1398 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1399 * due to the softdep code.
1406 * Turn buffer into delayed write request. We must clear BIO_READ and
1407 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1408 * itself to properly update it in the dirty/clean lists. We mark it
1409 * B_DONE to ensure that any asynchronization of the buffer properly
1410 * clears B_DONE ( else a panic will occur later ).
1412 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1413 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1414 * should only be called if the buffer is known-good.
1416 * Since the buffer is not on a queue, we do not update the numfreebuffers
1419 * The buffer must be on QUEUE_NONE.
1422 bdirty(struct buf *bp)
1425 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1426 bp, bp->b_vp, bp->b_flags);
1427 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1428 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1429 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1430 BUF_ASSERT_HELD(bp);
1431 bp->b_flags &= ~(B_RELBUF);
1432 bp->b_iocmd = BIO_WRITE;
1434 if ((bp->b_flags & B_DELWRI) == 0) {
1435 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1444 * Clear B_DELWRI for buffer.
1446 * Since the buffer is not on a queue, we do not update the numfreebuffers
1449 * The buffer must be on QUEUE_NONE.
1453 bundirty(struct buf *bp)
1456 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1457 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1458 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1459 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1460 BUF_ASSERT_HELD(bp);
1462 if (bp->b_flags & B_DELWRI) {
1463 bp->b_flags &= ~B_DELWRI;
1468 * Since it is now being written, we can clear its deferred write flag.
1470 bp->b_flags &= ~B_DEFERRED;
1476 * Asynchronous write. Start output on a buffer, but do not wait for
1477 * it to complete. The buffer is released when the output completes.
1479 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1480 * B_INVAL buffers. Not us.
1483 bawrite(struct buf *bp)
1486 bp->b_flags |= B_ASYNC;
1493 * Asynchronous barrier write. Start output on a buffer, but do not
1494 * wait for it to complete. Place a write barrier after this write so
1495 * that this buffer and all buffers written before it are committed to
1496 * the disk before any buffers written after this write are committed
1497 * to the disk. The buffer is released when the output completes.
1500 babarrierwrite(struct buf *bp)
1503 bp->b_flags |= B_ASYNC | B_BARRIER;
1510 * Synchronous barrier write. Start output on a buffer and wait for
1511 * it to complete. Place a write barrier after this write so that
1512 * this buffer and all buffers written before it are committed to
1513 * the disk before any buffers written after this write are committed
1514 * to the disk. The buffer is released when the output completes.
1517 bbarrierwrite(struct buf *bp)
1520 bp->b_flags |= B_BARRIER;
1521 return (bwrite(bp));
1527 * Called prior to the locking of any vnodes when we are expecting to
1528 * write. We do not want to starve the buffer cache with too many
1529 * dirty buffers so we block here. By blocking prior to the locking
1530 * of any vnodes we attempt to avoid the situation where a locked vnode
1531 * prevents the various system daemons from flushing related buffers.
1537 if (numdirtybuffers >= hidirtybuffers) {
1538 mtx_lock(&bdirtylock);
1539 while (numdirtybuffers >= hidirtybuffers) {
1541 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
1544 mtx_unlock(&bdirtylock);
1549 * Return true if we have too many dirty buffers.
1552 buf_dirty_count_severe(void)
1555 return(numdirtybuffers >= hidirtybuffers);
1558 static __noinline int
1559 buf_vm_page_count_severe(void)
1562 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1564 return vm_page_count_severe();
1570 * Release a busy buffer and, if requested, free its resources. The
1571 * buffer will be stashed in the appropriate bufqueue[] allowing it
1572 * to be accessed later as a cache entity or reused for other purposes.
1575 brelse(struct buf *bp)
1579 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1580 bp, bp->b_vp, bp->b_flags);
1581 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1582 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1584 if (BUF_LOCKRECURSED(bp)) {
1586 * Do not process, in particular, do not handle the
1587 * B_INVAL/B_RELBUF and do not release to free list.
1593 if (bp->b_flags & B_MANAGED) {
1598 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1599 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1601 * Failed write, redirty. Must clear BIO_ERROR to prevent
1602 * pages from being scrapped. If the error is anything
1603 * other than an I/O error (EIO), assume that retrying
1606 bp->b_ioflags &= ~BIO_ERROR;
1608 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1609 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1611 * Either a failed I/O or we were asked to free or not
1614 bp->b_flags |= B_INVAL;
1615 if (!LIST_EMPTY(&bp->b_dep))
1617 if (bp->b_flags & B_DELWRI)
1619 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1620 if ((bp->b_flags & B_VMIO) == 0) {
1629 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1630 * is called with B_DELWRI set, the underlying pages may wind up
1631 * getting freed causing a previous write (bdwrite()) to get 'lost'
1632 * because pages associated with a B_DELWRI bp are marked clean.
1634 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1635 * if B_DELWRI is set.
1637 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1638 * on pages to return pages to the VM page queues.
1640 if (bp->b_flags & B_DELWRI)
1641 bp->b_flags &= ~B_RELBUF;
1642 else if (buf_vm_page_count_severe()) {
1644 * BKGRDINPROG can only be set with the buf and bufobj
1645 * locks both held. We tolerate a race to clear it here.
1647 if (!(bp->b_vflags & BV_BKGRDINPROG))
1648 bp->b_flags |= B_RELBUF;
1652 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1653 * constituted, not even NFS buffers now. Two flags effect this. If
1654 * B_INVAL, the struct buf is invalidated but the VM object is kept
1655 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1657 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1658 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1659 * buffer is also B_INVAL because it hits the re-dirtying code above.
1661 * Normally we can do this whether a buffer is B_DELWRI or not. If
1662 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1663 * the commit state and we cannot afford to lose the buffer. If the
1664 * buffer has a background write in progress, we need to keep it
1665 * around to prevent it from being reconstituted and starting a second
1668 if ((bp->b_flags & B_VMIO)
1669 && !(bp->b_vp->v_mount != NULL &&
1670 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1671 !vn_isdisk(bp->b_vp, NULL) &&
1672 (bp->b_flags & B_DELWRI))
1681 obj = bp->b_bufobj->bo_object;
1684 * Get the base offset and length of the buffer. Note that
1685 * in the VMIO case if the buffer block size is not
1686 * page-aligned then b_data pointer may not be page-aligned.
1687 * But our b_pages[] array *IS* page aligned.
1689 * block sizes less then DEV_BSIZE (usually 512) are not
1690 * supported due to the page granularity bits (m->valid,
1691 * m->dirty, etc...).
1693 * See man buf(9) for more information
1695 resid = bp->b_bufsize;
1696 foff = bp->b_offset;
1697 for (i = 0; i < bp->b_npages; i++) {
1703 * If we hit a bogus page, fixup *all* the bogus pages
1706 if (m == bogus_page) {
1707 poff = OFF_TO_IDX(bp->b_offset);
1710 VM_OBJECT_RLOCK(obj);
1711 for (j = i; j < bp->b_npages; j++) {
1713 mtmp = bp->b_pages[j];
1714 if (mtmp == bogus_page) {
1715 mtmp = vm_page_lookup(obj, poff + j);
1717 panic("brelse: page missing\n");
1719 bp->b_pages[j] = mtmp;
1722 VM_OBJECT_RUNLOCK(obj);
1724 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1725 BUF_CHECK_MAPPED(bp);
1727 trunc_page((vm_offset_t)bp->b_data),
1728 bp->b_pages, bp->b_npages);
1732 if ((bp->b_flags & B_NOCACHE) ||
1733 (bp->b_ioflags & BIO_ERROR &&
1734 bp->b_iocmd == BIO_READ)) {
1735 int poffset = foff & PAGE_MASK;
1736 int presid = resid > (PAGE_SIZE - poffset) ?
1737 (PAGE_SIZE - poffset) : resid;
1739 KASSERT(presid >= 0, ("brelse: extra page"));
1740 VM_OBJECT_WLOCK(obj);
1741 while (vm_page_xbusied(m)) {
1743 VM_OBJECT_WUNLOCK(obj);
1744 vm_page_busy_sleep(m, "mbncsh");
1745 VM_OBJECT_WLOCK(obj);
1747 if (pmap_page_wired_mappings(m) == 0)
1748 vm_page_set_invalid(m, poffset, presid);
1749 VM_OBJECT_WUNLOCK(obj);
1751 printf("avoided corruption bug in bogus_page/brelse code\n");
1753 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1754 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1756 if (bp->b_flags & (B_INVAL | B_RELBUF))
1757 vfs_vmio_release(bp);
1759 } else if (bp->b_flags & B_VMIO) {
1761 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1762 vfs_vmio_release(bp);
1765 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1766 if (bp->b_bufsize != 0)
1768 if (bp->b_vp != NULL)
1773 * If the buffer has junk contents signal it and eventually
1774 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1777 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1778 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1779 bp->b_flags |= B_INVAL;
1780 if (bp->b_flags & B_INVAL) {
1781 if (bp->b_flags & B_DELWRI)
1787 /* buffers with no memory */
1788 if (bp->b_bufsize == 0) {
1789 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1790 if (bp->b_vflags & BV_BKGRDINPROG)
1791 panic("losing buffer 1");
1793 qindex = QUEUE_EMPTYKVA;
1795 qindex = QUEUE_EMPTY;
1796 bp->b_flags |= B_AGE;
1797 /* buffers with junk contents */
1798 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1799 (bp->b_ioflags & BIO_ERROR)) {
1800 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1801 if (bp->b_vflags & BV_BKGRDINPROG)
1802 panic("losing buffer 2");
1803 qindex = QUEUE_CLEAN;
1804 bp->b_flags |= B_AGE;
1805 /* remaining buffers */
1806 } else if (bp->b_flags & B_DELWRI)
1807 qindex = QUEUE_DIRTY;
1809 qindex = QUEUE_CLEAN;
1811 binsfree(bp, qindex);
1813 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1814 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1815 panic("brelse: not dirty");
1821 * Release a buffer back to the appropriate queue but do not try to free
1822 * it. The buffer is expected to be used again soon.
1824 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1825 * biodone() to requeue an async I/O on completion. It is also used when
1826 * known good buffers need to be requeued but we think we may need the data
1829 * XXX we should be able to leave the B_RELBUF hint set on completion.
1832 bqrelse(struct buf *bp)
1836 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1837 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1838 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1840 if (BUF_LOCKRECURSED(bp)) {
1841 /* do not release to free list */
1845 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1847 if (bp->b_flags & B_MANAGED) {
1848 if (bp->b_flags & B_REMFREE)
1853 /* buffers with stale but valid contents */
1854 if (bp->b_flags & B_DELWRI) {
1855 qindex = QUEUE_DIRTY;
1857 if ((bp->b_flags & B_DELWRI) == 0 &&
1858 (bp->b_xflags & BX_VNDIRTY))
1859 panic("bqrelse: not dirty");
1861 * BKGRDINPROG can only be set with the buf and bufobj
1862 * locks both held. We tolerate a race to clear it here.
1864 if (buf_vm_page_count_severe() &&
1865 (bp->b_vflags & BV_BKGRDINPROG) == 0) {
1867 * We are too low on memory, we have to try to free
1868 * the buffer (most importantly: the wired pages
1869 * making up its backing store) *now*.
1874 qindex = QUEUE_CLEAN;
1876 binsfree(bp, qindex);
1883 /* Give pages used by the bp back to the VM system (where possible) */
1885 vfs_vmio_release(struct buf *bp)
1891 if ((bp->b_flags & B_UNMAPPED) == 0) {
1892 BUF_CHECK_MAPPED(bp);
1893 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1895 BUF_CHECK_UNMAPPED(bp);
1896 obj = bp->b_bufobj->bo_object;
1898 VM_OBJECT_WLOCK(obj);
1899 for (i = 0; i < bp->b_npages; i++) {
1901 bp->b_pages[i] = NULL;
1903 * In order to keep page LRU ordering consistent, put
1904 * everything on the inactive queue.
1907 vm_page_unwire(m, PQ_INACTIVE);
1910 * Might as well free the page if we can and it has
1911 * no valid data. We also free the page if the
1912 * buffer was used for direct I/O
1914 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1915 if (m->wire_count == 0 && !vm_page_busied(m))
1917 } else if (bp->b_flags & B_DIRECT)
1918 vm_page_try_to_free(m);
1919 else if (buf_vm_page_count_severe())
1920 vm_page_try_to_cache(m);
1924 VM_OBJECT_WUNLOCK(obj);
1926 if (bp->b_bufsize) {
1931 bp->b_flags &= ~B_VMIO;
1937 * Check to see if a block at a particular lbn is available for a clustered
1941 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1948 /* If the buf isn't in core skip it */
1949 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1952 /* If the buf is busy we don't want to wait for it */
1953 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1956 /* Only cluster with valid clusterable delayed write buffers */
1957 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1958 (B_DELWRI | B_CLUSTEROK))
1961 if (bpa->b_bufsize != size)
1965 * Check to see if it is in the expected place on disk and that the
1966 * block has been mapped.
1968 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1978 * Implement clustered async writes for clearing out B_DELWRI buffers.
1979 * This is much better then the old way of writing only one buffer at
1980 * a time. Note that we may not be presented with the buffers in the
1981 * correct order, so we search for the cluster in both directions.
1984 vfs_bio_awrite(struct buf *bp)
1989 daddr_t lblkno = bp->b_lblkno;
1990 struct vnode *vp = bp->b_vp;
1998 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
2000 * right now we support clustered writing only to regular files. If
2001 * we find a clusterable block we could be in the middle of a cluster
2002 * rather then at the beginning.
2004 if ((vp->v_type == VREG) &&
2005 (vp->v_mount != 0) && /* Only on nodes that have the size info */
2006 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2008 size = vp->v_mount->mnt_stat.f_iosize;
2009 maxcl = MAXPHYS / size;
2012 for (i = 1; i < maxcl; i++)
2013 if (vfs_bio_clcheck(vp, size, lblkno + i,
2014 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2017 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2018 if (vfs_bio_clcheck(vp, size, lblkno - j,
2019 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2025 * this is a possible cluster write
2029 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2035 bp->b_flags |= B_ASYNC;
2037 * default (old) behavior, writing out only one block
2039 * XXX returns b_bufsize instead of b_bcount for nwritten?
2041 nwritten = bp->b_bufsize;
2048 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
2051 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2052 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
2053 if ((gbflags & GB_UNMAPPED) == 0) {
2054 bp->b_kvabase = (caddr_t)addr;
2055 } else if ((gbflags & GB_KVAALLOC) != 0) {
2056 KASSERT((gbflags & GB_UNMAPPED) != 0,
2057 ("GB_KVAALLOC without GB_UNMAPPED"));
2058 bp->b_kvaalloc = (caddr_t)addr;
2059 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2060 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2062 bp->b_kvasize = maxsize;
2066 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2070 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2077 if (vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr)) {
2079 * Buffer map is too fragmented. Request the caller
2080 * to defragment the map.
2082 atomic_add_int(&bufdefragcnt, 1);
2085 setbufkva(bp, addr, maxsize, gbflags);
2086 atomic_add_long(&bufspace, bp->b_kvasize);
2091 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2092 * locked vnode is supplied.
2095 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2100 int cnt, error, flags, norunbuf, wait;
2102 mtx_assert(&bqclean, MA_OWNED);
2105 flags = VFS_BIO_NEED_BUFSPACE;
2107 } else if (bufspace >= hibufspace) {
2109 flags = VFS_BIO_NEED_BUFSPACE;
2112 flags = VFS_BIO_NEED_ANY;
2114 atomic_set_int(&needsbuffer, flags);
2115 mtx_unlock(&bqclean);
2117 bd_speedup(); /* heeeelp */
2118 if ((gbflags & GB_NOWAIT_BD) != 0)
2125 while ((needsbuffer & flags) != 0) {
2126 if (vp != NULL && vp->v_type != VCHR &&
2127 (td->td_pflags & TDP_BUFNEED) == 0) {
2128 rw_wunlock(&nblock);
2130 * getblk() is called with a vnode locked, and
2131 * some majority of the dirty buffers may as
2132 * well belong to the vnode. Flushing the
2133 * buffers there would make a progress that
2134 * cannot be achieved by the buf_daemon, that
2135 * cannot lock the vnode.
2139 ASSERT_VOP_LOCKED(vp, "bufd_helper");
2140 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
2141 vn_lock(vp, LK_TRYUPGRADE);
2143 /* play bufdaemon */
2144 norunbuf = curthread_pflags_set(TDP_BUFNEED |
2146 VOP_FSYNC(vp, wait, td);
2147 atomic_add_long(¬bufdflushes, 1);
2148 curthread_pflags_restore(norunbuf);
2151 if ((needsbuffer & flags) == 0)
2154 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
2155 (PRIBIO + 4) | slpflag, waitmsg, slptimeo);
2159 rw_wunlock(&nblock);
2163 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2166 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2167 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2168 bp->b_kvasize, bp->b_bufsize, qindex);
2169 mtx_assert(&bqclean, MA_NOTOWNED);
2172 * Note: we no longer distinguish between VMIO and non-VMIO
2175 KASSERT((bp->b_flags & B_DELWRI) == 0,
2176 ("delwri buffer %p found in queue %d", bp, qindex));
2178 if (qindex == QUEUE_CLEAN) {
2179 if (bp->b_flags & B_VMIO) {
2180 bp->b_flags &= ~B_ASYNC;
2181 vfs_vmio_release(bp);
2183 if (bp->b_vp != NULL)
2188 * Get the rest of the buffer freed up. b_kva* is still valid
2189 * after this operation.
2192 if (bp->b_rcred != NOCRED) {
2193 crfree(bp->b_rcred);
2194 bp->b_rcred = NOCRED;
2196 if (bp->b_wcred != NOCRED) {
2197 crfree(bp->b_wcred);
2198 bp->b_wcred = NOCRED;
2200 if (!LIST_EMPTY(&bp->b_dep))
2202 if (bp->b_vflags & BV_BKGRDINPROG)
2203 panic("losing buffer 3");
2204 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2205 bp, bp->b_vp, qindex));
2206 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2207 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2212 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2215 KASSERT((bp->b_flags & B_INFREECNT) == 0,
2216 ("buf %p still counted as free?", bp));
2219 bp->b_blkno = bp->b_lblkno = 0;
2220 bp->b_offset = NOOFFSET;
2226 bp->b_dirtyoff = bp->b_dirtyend = 0;
2227 bp->b_bufobj = NULL;
2228 bp->b_pin_count = 0;
2229 bp->b_fsprivate1 = NULL;
2230 bp->b_fsprivate2 = NULL;
2231 bp->b_fsprivate3 = NULL;
2233 LIST_INIT(&bp->b_dep);
2236 static int flushingbufs;
2239 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2241 struct buf *bp, *nbp;
2242 int nqindex, qindex, pass;
2244 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2248 atomic_add_int(&getnewbufrestarts, 1);
2251 * Setup for scan. If we do not have enough free buffers,
2252 * we setup a degenerate case that immediately fails. Note
2253 * that if we are specially marked process, we are allowed to
2254 * dip into our reserves.
2256 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2257 * for the allocation of the mapped buffer. For unmapped, the
2258 * easiest is to start with EMPTY outright.
2260 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2261 * However, there are a number of cases (defragging, reusing, ...)
2262 * where we cannot backup.
2266 if (!defrag && unmapped) {
2267 nqindex = QUEUE_EMPTY;
2268 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2271 nqindex = QUEUE_EMPTYKVA;
2272 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2276 * If no EMPTYKVA buffers and we are either defragging or
2277 * reusing, locate a CLEAN buffer to free or reuse. If
2278 * bufspace useage is low skip this step so we can allocate a
2281 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2282 nqindex = QUEUE_CLEAN;
2283 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2287 * If we could not find or were not allowed to reuse a CLEAN
2288 * buffer, check to see if it is ok to use an EMPTY buffer.
2289 * We can only use an EMPTY buffer if allocating its KVA would
2290 * not otherwise run us out of buffer space. No KVA is needed
2291 * for the unmapped allocation.
2293 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2295 nqindex = QUEUE_EMPTY;
2296 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2300 * All available buffers might be clean, retry ignoring the
2301 * lobufspace as the last resort.
2303 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2304 nqindex = QUEUE_CLEAN;
2305 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2309 * Run scan, possibly freeing data and/or kva mappings on the fly
2312 while ((bp = nbp) != NULL) {
2316 * Calculate next bp (we can only use it if we do not
2317 * block or do other fancy things).
2319 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2322 nqindex = QUEUE_EMPTYKVA;
2323 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2327 case QUEUE_EMPTYKVA:
2328 nqindex = QUEUE_CLEAN;
2329 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2334 if (metadata && pass == 1) {
2336 nqindex = QUEUE_EMPTY;
2338 &bufqueues[QUEUE_EMPTY]);
2347 * If we are defragging then we need a buffer with
2348 * b_kvasize != 0. XXX this situation should no longer
2349 * occur, if defrag is non-zero the buffer's b_kvasize
2350 * should also be non-zero at this point. XXX
2352 if (defrag && bp->b_kvasize == 0) {
2353 printf("Warning: defrag empty buffer %p\n", bp);
2358 * Start freeing the bp. This is somewhat involved. nbp
2359 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2361 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2364 * BKGRDINPROG can only be set with the buf and bufobj
2365 * locks both held. We tolerate a race to clear it here.
2367 if (bp->b_vflags & BV_BKGRDINPROG) {
2372 KASSERT(bp->b_qindex == qindex,
2373 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2376 mtx_unlock(&bqclean);
2378 * NOTE: nbp is now entirely invalid. We can only restart
2379 * the scan from this point on.
2382 getnewbuf_reuse_bp(bp, qindex);
2383 mtx_assert(&bqclean, MA_NOTOWNED);
2386 * If we are defragging then free the buffer.
2389 bp->b_flags |= B_INVAL;
2397 * Notify any waiters for the buffer lock about
2398 * identity change by freeing the buffer.
2400 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2401 bp->b_flags |= B_INVAL;
2411 * If we are overcomitted then recover the buffer and its
2412 * KVM space. This occurs in rare situations when multiple
2413 * processes are blocked in getnewbuf() or allocbuf().
2415 if (bufspace >= hibufspace)
2417 if (flushingbufs && bp->b_kvasize != 0) {
2418 bp->b_flags |= B_INVAL;
2423 if (bufspace < lobufspace)
2433 * Find and initialize a new buffer header, freeing up existing buffers
2434 * in the bufqueues as necessary. The new buffer is returned locked.
2436 * Important: B_INVAL is not set. If the caller wishes to throw the
2437 * buffer away, the caller must set B_INVAL prior to calling brelse().
2440 * We have insufficient buffer headers
2441 * We have insufficient buffer space
2442 * buffer_arena is too fragmented ( space reservation fails )
2443 * If we have to flush dirty buffers ( but we try to avoid this )
2446 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2450 int defrag, metadata;
2452 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2453 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2454 if (!unmapped_buf_allowed)
2455 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2458 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2464 * We can't afford to block since we might be holding a vnode lock,
2465 * which may prevent system daemons from running. We deal with
2466 * low-memory situations by proactively returning memory and running
2467 * async I/O rather then sync I/O.
2469 atomic_add_int(&getnewbufcalls, 1);
2470 atomic_subtract_int(&getnewbufrestarts, 1);
2472 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2473 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2478 * If we exhausted our list, sleep as appropriate. We may have to
2479 * wakeup various daemons and write out some dirty buffers.
2481 * Generally we are sleeping due to insufficient buffer space.
2484 mtx_assert(&bqclean, MA_OWNED);
2485 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2486 mtx_assert(&bqclean, MA_NOTOWNED);
2487 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2488 mtx_assert(&bqclean, MA_NOTOWNED);
2491 bp->b_flags |= B_UNMAPPED;
2492 bp->b_kvabase = bp->b_data = unmapped_buf;
2493 bp->b_kvasize = maxsize;
2494 atomic_add_long(&bufspace, bp->b_kvasize);
2495 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2496 atomic_add_int(&bufreusecnt, 1);
2498 mtx_assert(&bqclean, MA_NOTOWNED);
2501 * We finally have a valid bp. We aren't quite out of the
2502 * woods, we still have to reserve kva space. In order
2503 * to keep fragmentation sane we only allocate kva in
2506 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2508 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2509 B_KVAALLOC)) == B_UNMAPPED) {
2510 if (allocbufkva(bp, maxsize, gbflags)) {
2512 bp->b_flags |= B_INVAL;
2516 atomic_add_int(&bufreusecnt, 1);
2517 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2518 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2520 * If the reused buffer has KVA allocated,
2521 * reassign b_kvaalloc to b_kvabase.
2523 bp->b_kvabase = bp->b_kvaalloc;
2524 bp->b_flags &= ~B_KVAALLOC;
2525 atomic_subtract_long(&unmapped_bufspace,
2527 atomic_add_int(&bufreusecnt, 1);
2528 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2529 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2532 * The case of reused buffer already have KVA
2533 * mapped, but the request is for unmapped
2534 * buffer with KVA allocated.
2536 bp->b_kvaalloc = bp->b_kvabase;
2537 bp->b_data = bp->b_kvabase = unmapped_buf;
2538 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2539 atomic_add_long(&unmapped_bufspace,
2541 atomic_add_int(&bufreusecnt, 1);
2543 if ((gbflags & GB_UNMAPPED) == 0) {
2544 bp->b_saveaddr = bp->b_kvabase;
2545 bp->b_data = bp->b_saveaddr;
2546 bp->b_flags &= ~B_UNMAPPED;
2547 BUF_CHECK_MAPPED(bp);
2556 * buffer flushing daemon. Buffers are normally flushed by the
2557 * update daemon but if it cannot keep up this process starts to
2558 * take the load in an attempt to prevent getnewbuf() from blocking.
2561 static struct kproc_desc buf_kp = {
2566 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2569 buf_flush(int target)
2573 flushed = flushbufqueues(target, 0);
2576 * Could not find any buffers without rollback
2577 * dependencies, so just write the first one
2578 * in the hopes of eventually making progress.
2580 flushed = flushbufqueues(target, 1);
2591 * This process needs to be suspended prior to shutdown sync.
2593 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2597 * This process is allowed to take the buffer cache to the limit
2599 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2603 mtx_unlock(&bdlock);
2605 kproc_suspend_check(bufdaemonproc);
2606 lodirty = lodirtybuffers;
2607 if (bd_speedupreq) {
2608 lodirty = numdirtybuffers / 2;
2612 * Do the flush. Limit the amount of in-transit I/O we
2613 * allow to build up, otherwise we would completely saturate
2616 while (numdirtybuffers > lodirty) {
2617 if (buf_flush(numdirtybuffers - lodirty) == 0)
2619 kern_yield(PRI_USER);
2623 * Only clear bd_request if we have reached our low water
2624 * mark. The buf_daemon normally waits 1 second and
2625 * then incrementally flushes any dirty buffers that have
2626 * built up, within reason.
2628 * If we were unable to hit our low water mark and couldn't
2629 * find any flushable buffers, we sleep for a short period
2630 * to avoid endless loops on unlockable buffers.
2633 if (numdirtybuffers <= lodirtybuffers) {
2635 * We reached our low water mark, reset the
2636 * request and sleep until we are needed again.
2637 * The sleep is just so the suspend code works.
2641 * Do an extra wakeup in case dirty threshold
2642 * changed via sysctl and the explicit transition
2643 * out of shortfall was missed.
2646 if (runningbufspace <= lorunningspace)
2648 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2651 * We couldn't find any flushable dirty buffers but
2652 * still have too many dirty buffers, we
2653 * have to sleep and try again. (rare)
2655 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2663 * Try to flush a buffer in the dirty queue. We must be careful to
2664 * free up B_INVAL buffers instead of write them, which NFS is
2665 * particularly sensitive to.
2667 static int flushwithdeps = 0;
2668 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2669 0, "Number of buffers flushed with dependecies that require rollbacks");
2672 flushbufqueues(int target, int flushdeps)
2674 struct buf *sentinel;
2684 queue = QUEUE_DIRTY;
2686 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2687 sentinel->b_qindex = QUEUE_SENTINEL;
2689 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2690 mtx_unlock(&bqdirty);
2691 while (flushed != target) {
2694 bp = TAILQ_NEXT(sentinel, b_freelist);
2696 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2697 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2700 mtx_unlock(&bqdirty);
2703 KASSERT(bp->b_qindex != QUEUE_SENTINEL,
2704 ("parallel calls to flushbufqueues() bp %p", bp));
2705 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
2706 mtx_unlock(&bqdirty);
2709 if (bp->b_pin_count > 0) {
2714 * BKGRDINPROG can only be set with the buf and bufobj
2715 * locks both held. We tolerate a race to clear it here.
2717 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2718 (bp->b_flags & B_DELWRI) == 0) {
2722 if (bp->b_flags & B_INVAL) {
2729 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2730 if (flushdeps == 0) {
2738 * We must hold the lock on a vnode before writing
2739 * one of its buffers. Otherwise we may confuse, or
2740 * in the case of a snapshot vnode, deadlock the
2743 * The lock order here is the reverse of the normal
2744 * of vnode followed by buf lock. This is ok because
2745 * the NOWAIT will prevent deadlock.
2748 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2752 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
2754 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2755 bp, bp->b_vp, bp->b_flags);
2757 vn_finished_write(mp);
2759 flushwithdeps += hasdeps;
2761 if (runningbufspace > hirunningspace)
2762 waitrunningbufspace();
2765 vn_finished_write(mp);
2769 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2770 mtx_unlock(&bqdirty);
2771 free(sentinel, M_TEMP);
2776 * Check to see if a block is currently memory resident.
2779 incore(struct bufobj *bo, daddr_t blkno)
2784 bp = gbincore(bo, blkno);
2790 * Returns true if no I/O is needed to access the
2791 * associated VM object. This is like incore except
2792 * it also hunts around in the VM system for the data.
2796 inmem(struct vnode * vp, daddr_t blkno)
2799 vm_offset_t toff, tinc, size;
2803 ASSERT_VOP_LOCKED(vp, "inmem");
2805 if (incore(&vp->v_bufobj, blkno))
2807 if (vp->v_mount == NULL)
2814 if (size > vp->v_mount->mnt_stat.f_iosize)
2815 size = vp->v_mount->mnt_stat.f_iosize;
2816 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2818 VM_OBJECT_RLOCK(obj);
2819 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2820 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2824 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2825 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2826 if (vm_page_is_valid(m,
2827 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2830 VM_OBJECT_RUNLOCK(obj);
2834 VM_OBJECT_RUNLOCK(obj);
2839 * Set the dirty range for a buffer based on the status of the dirty
2840 * bits in the pages comprising the buffer. The range is limited
2841 * to the size of the buffer.
2843 * Tell the VM system that the pages associated with this buffer
2844 * are clean. This is used for delayed writes where the data is
2845 * going to go to disk eventually without additional VM intevention.
2847 * Note that while we only really need to clean through to b_bcount, we
2848 * just go ahead and clean through to b_bufsize.
2851 vfs_clean_pages_dirty_buf(struct buf *bp)
2853 vm_ooffset_t foff, noff, eoff;
2857 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2860 foff = bp->b_offset;
2861 KASSERT(bp->b_offset != NOOFFSET,
2862 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2864 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2865 vfs_drain_busy_pages(bp);
2866 vfs_setdirty_locked_object(bp);
2867 for (i = 0; i < bp->b_npages; i++) {
2868 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2870 if (eoff > bp->b_offset + bp->b_bufsize)
2871 eoff = bp->b_offset + bp->b_bufsize;
2873 vfs_page_set_validclean(bp, foff, m);
2874 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2877 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2881 vfs_setdirty_locked_object(struct buf *bp)
2886 object = bp->b_bufobj->bo_object;
2887 VM_OBJECT_ASSERT_WLOCKED(object);
2890 * We qualify the scan for modified pages on whether the
2891 * object has been flushed yet.
2893 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2894 vm_offset_t boffset;
2895 vm_offset_t eoffset;
2898 * test the pages to see if they have been modified directly
2899 * by users through the VM system.
2901 for (i = 0; i < bp->b_npages; i++)
2902 vm_page_test_dirty(bp->b_pages[i]);
2905 * Calculate the encompassing dirty range, boffset and eoffset,
2906 * (eoffset - boffset) bytes.
2909 for (i = 0; i < bp->b_npages; i++) {
2910 if (bp->b_pages[i]->dirty)
2913 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2915 for (i = bp->b_npages - 1; i >= 0; --i) {
2916 if (bp->b_pages[i]->dirty) {
2920 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2923 * Fit it to the buffer.
2926 if (eoffset > bp->b_bcount)
2927 eoffset = bp->b_bcount;
2930 * If we have a good dirty range, merge with the existing
2934 if (boffset < eoffset) {
2935 if (bp->b_dirtyoff > boffset)
2936 bp->b_dirtyoff = boffset;
2937 if (bp->b_dirtyend < eoffset)
2938 bp->b_dirtyend = eoffset;
2944 * Allocate the KVA mapping for an existing buffer. It handles the
2945 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2946 * KVA which is not mapped (B_KVAALLOC).
2949 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2951 struct buf *scratch_bp;
2952 int bsize, maxsize, need_mapping, need_kva;
2955 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2956 (gbflags & GB_UNMAPPED) == 0;
2957 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2958 (gbflags & GB_KVAALLOC) != 0;
2959 if (!need_mapping && !need_kva)
2962 BUF_CHECK_UNMAPPED(bp);
2964 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2966 * Buffer is not mapped, but the KVA was already
2967 * reserved at the time of the instantiation. Use the
2970 bp->b_flags &= ~B_KVAALLOC;
2971 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2972 bp->b_kvabase = bp->b_kvaalloc;
2973 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2978 * Calculate the amount of the address space we would reserve
2979 * if the buffer was mapped.
2981 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2982 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
2983 offset = blkno * bsize;
2984 maxsize = size + (offset & PAGE_MASK);
2985 maxsize = imax(maxsize, bsize);
2988 if (allocbufkva(bp, maxsize, gbflags)) {
2990 * Request defragmentation. getnewbuf() returns us the
2991 * allocated space by the scratch buffer KVA.
2993 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2994 (GB_UNMAPPED | GB_KVAALLOC));
2995 if (scratch_bp == NULL) {
2996 if ((gbflags & GB_NOWAIT_BD) != 0) {
2998 * XXXKIB: defragmentation cannot
2999 * succeed, not sure what else to do.
3001 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
3003 atomic_add_int(&mappingrestarts, 1);
3006 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
3007 ("scratch bp !B_KVAALLOC %p", scratch_bp));
3008 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
3009 scratch_bp->b_kvasize, gbflags);
3011 /* Get rid of the scratch buffer. */
3012 scratch_bp->b_kvasize = 0;
3013 scratch_bp->b_flags |= B_INVAL;
3014 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
3021 bp->b_saveaddr = bp->b_kvabase;
3022 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
3023 bp->b_flags &= ~B_UNMAPPED;
3024 BUF_CHECK_MAPPED(bp);
3031 * Get a block given a specified block and offset into a file/device.
3032 * The buffers B_DONE bit will be cleared on return, making it almost
3033 * ready for an I/O initiation. B_INVAL may or may not be set on
3034 * return. The caller should clear B_INVAL prior to initiating a
3037 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3038 * an existing buffer.
3040 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3041 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3042 * and then cleared based on the backing VM. If the previous buffer is
3043 * non-0-sized but invalid, B_CACHE will be cleared.
3045 * If getblk() must create a new buffer, the new buffer is returned with
3046 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3047 * case it is returned with B_INVAL clear and B_CACHE set based on the
3050 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3051 * B_CACHE bit is clear.
3053 * What this means, basically, is that the caller should use B_CACHE to
3054 * determine whether the buffer is fully valid or not and should clear
3055 * B_INVAL prior to issuing a read. If the caller intends to validate
3056 * the buffer by loading its data area with something, the caller needs
3057 * to clear B_INVAL. If the caller does this without issuing an I/O,
3058 * the caller should set B_CACHE ( as an optimization ), else the caller
3059 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3060 * a write attempt or if it was a successfull read. If the caller
3061 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3062 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3065 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3070 int bsize, error, maxsize, vmio;
3073 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3074 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3075 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3076 ASSERT_VOP_LOCKED(vp, "getblk");
3077 if (size > MAXBCACHEBUF)
3078 panic("getblk: size(%d) > MAXBCACHEBUF(%d)\n", size,
3080 if (!unmapped_buf_allowed)
3081 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3086 bp = gbincore(bo, blkno);
3090 * Buffer is in-core. If the buffer is not busy nor managed,
3091 * it must be on a queue.
3093 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3095 if (flags & GB_LOCK_NOWAIT)
3096 lockflags |= LK_NOWAIT;
3098 error = BUF_TIMELOCK(bp, lockflags,
3099 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3102 * If we slept and got the lock we have to restart in case
3103 * the buffer changed identities.
3105 if (error == ENOLCK)
3107 /* We timed out or were interrupted. */
3110 /* If recursed, assume caller knows the rules. */
3111 else if (BUF_LOCKRECURSED(bp))
3115 * The buffer is locked. B_CACHE is cleared if the buffer is
3116 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3117 * and for a VMIO buffer B_CACHE is adjusted according to the
3120 if (bp->b_flags & B_INVAL)
3121 bp->b_flags &= ~B_CACHE;
3122 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3123 bp->b_flags |= B_CACHE;
3124 if (bp->b_flags & B_MANAGED)
3125 MPASS(bp->b_qindex == QUEUE_NONE);
3130 * check for size inconsistencies for non-VMIO case.
3132 if (bp->b_bcount != size) {
3133 if ((bp->b_flags & B_VMIO) == 0 ||
3134 (size > bp->b_kvasize)) {
3135 if (bp->b_flags & B_DELWRI) {
3137 * If buffer is pinned and caller does
3138 * not want sleep waiting for it to be
3139 * unpinned, bail out
3141 if (bp->b_pin_count > 0) {
3142 if (flags & GB_LOCK_NOWAIT) {
3149 bp->b_flags |= B_NOCACHE;
3152 if (LIST_EMPTY(&bp->b_dep)) {
3153 bp->b_flags |= B_RELBUF;
3156 bp->b_flags |= B_NOCACHE;
3165 * Handle the case of unmapped buffer which should
3166 * become mapped, or the buffer for which KVA
3167 * reservation is requested.
3169 bp_unmapped_get_kva(bp, blkno, size, flags);
3172 * If the size is inconsistant in the VMIO case, we can resize
3173 * the buffer. This might lead to B_CACHE getting set or
3174 * cleared. If the size has not changed, B_CACHE remains
3175 * unchanged from its previous state.
3177 if (bp->b_bcount != size)
3180 KASSERT(bp->b_offset != NOOFFSET,
3181 ("getblk: no buffer offset"));
3184 * A buffer with B_DELWRI set and B_CACHE clear must
3185 * be committed before we can return the buffer in
3186 * order to prevent the caller from issuing a read
3187 * ( due to B_CACHE not being set ) and overwriting
3190 * Most callers, including NFS and FFS, need this to
3191 * operate properly either because they assume they
3192 * can issue a read if B_CACHE is not set, or because
3193 * ( for example ) an uncached B_DELWRI might loop due
3194 * to softupdates re-dirtying the buffer. In the latter
3195 * case, B_CACHE is set after the first write completes,
3196 * preventing further loops.
3197 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3198 * above while extending the buffer, we cannot allow the
3199 * buffer to remain with B_CACHE set after the write
3200 * completes or it will represent a corrupt state. To
3201 * deal with this we set B_NOCACHE to scrap the buffer
3204 * We might be able to do something fancy, like setting
3205 * B_CACHE in bwrite() except if B_DELWRI is already set,
3206 * so the below call doesn't set B_CACHE, but that gets real
3207 * confusing. This is much easier.
3210 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3211 bp->b_flags |= B_NOCACHE;
3215 bp->b_flags &= ~B_DONE;
3218 * Buffer is not in-core, create new buffer. The buffer
3219 * returned by getnewbuf() is locked. Note that the returned
3220 * buffer is also considered valid (not marked B_INVAL).
3224 * If the user does not want us to create the buffer, bail out
3227 if (flags & GB_NOCREAT)
3229 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3232 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3233 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3234 offset = blkno * bsize;
3235 vmio = vp->v_object != NULL;
3237 maxsize = size + (offset & PAGE_MASK);
3240 /* Do not allow non-VMIO notmapped buffers. */
3241 flags &= ~GB_UNMAPPED;
3243 maxsize = imax(maxsize, bsize);
3245 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3247 if (slpflag || slptimeo)
3253 * This code is used to make sure that a buffer is not
3254 * created while the getnewbuf routine is blocked.
3255 * This can be a problem whether the vnode is locked or not.
3256 * If the buffer is created out from under us, we have to
3257 * throw away the one we just created.
3259 * Note: this must occur before we associate the buffer
3260 * with the vp especially considering limitations in
3261 * the splay tree implementation when dealing with duplicate
3265 if (gbincore(bo, blkno)) {
3267 bp->b_flags |= B_INVAL;
3273 * Insert the buffer into the hash, so that it can
3274 * be found by incore.
3276 bp->b_blkno = bp->b_lblkno = blkno;
3277 bp->b_offset = offset;
3282 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3283 * buffer size starts out as 0, B_CACHE will be set by
3284 * allocbuf() for the VMIO case prior to it testing the
3285 * backing store for validity.
3289 bp->b_flags |= B_VMIO;
3290 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3291 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3292 bp, vp->v_object, bp->b_bufobj->bo_object));
3294 bp->b_flags &= ~B_VMIO;
3295 KASSERT(bp->b_bufobj->bo_object == NULL,
3296 ("ARGH! has b_bufobj->bo_object %p %p\n",
3297 bp, bp->b_bufobj->bo_object));
3298 BUF_CHECK_MAPPED(bp);
3302 bp->b_flags &= ~B_DONE;
3304 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3305 BUF_ASSERT_HELD(bp);
3307 KASSERT(bp->b_bufobj == bo,
3308 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3313 * Get an empty, disassociated buffer of given size. The buffer is initially
3317 geteblk(int size, int flags)
3322 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3323 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3324 if ((flags & GB_NOWAIT_BD) &&
3325 (curthread->td_pflags & TDP_BUFNEED) != 0)
3329 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3330 BUF_ASSERT_HELD(bp);
3336 * This code constitutes the buffer memory from either anonymous system
3337 * memory (in the case of non-VMIO operations) or from an associated
3338 * VM object (in the case of VMIO operations). This code is able to
3339 * resize a buffer up or down.
3341 * Note that this code is tricky, and has many complications to resolve
3342 * deadlock or inconsistant data situations. Tread lightly!!!
3343 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3344 * the caller. Calling this code willy nilly can result in the loss of data.
3346 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3347 * B_CACHE for the non-VMIO case.
3351 allocbuf(struct buf *bp, int size)
3353 int newbsize, mbsize;
3356 BUF_ASSERT_HELD(bp);
3358 if (bp->b_kvasize < size)
3359 panic("allocbuf: buffer too small");
3361 if ((bp->b_flags & B_VMIO) == 0) {
3365 * Just get anonymous memory from the kernel. Don't
3366 * mess with B_CACHE.
3368 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3369 if (bp->b_flags & B_MALLOC)
3372 newbsize = round_page(size);
3374 if (newbsize < bp->b_bufsize) {
3376 * malloced buffers are not shrunk
3378 if (bp->b_flags & B_MALLOC) {
3380 bp->b_bcount = size;
3382 free(bp->b_data, M_BIOBUF);
3383 if (bp->b_bufsize) {
3384 atomic_subtract_long(
3390 bp->b_saveaddr = bp->b_kvabase;
3391 bp->b_data = bp->b_saveaddr;
3393 bp->b_flags &= ~B_MALLOC;
3397 vm_hold_free_pages(bp, newbsize);
3398 } else if (newbsize > bp->b_bufsize) {
3400 * We only use malloced memory on the first allocation.
3401 * and revert to page-allocated memory when the buffer
3405 * There is a potential smp race here that could lead
3406 * to bufmallocspace slightly passing the max. It
3407 * is probably extremely rare and not worth worrying
3410 if ( (bufmallocspace < maxbufmallocspace) &&
3411 (bp->b_bufsize == 0) &&
3412 (mbsize <= PAGE_SIZE/2)) {
3414 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3415 bp->b_bufsize = mbsize;
3416 bp->b_bcount = size;
3417 bp->b_flags |= B_MALLOC;
3418 atomic_add_long(&bufmallocspace, mbsize);
3424 * If the buffer is growing on its other-than-first allocation,
3425 * then we revert to the page-allocation scheme.
3427 if (bp->b_flags & B_MALLOC) {
3428 origbuf = bp->b_data;
3429 origbufsize = bp->b_bufsize;
3430 bp->b_data = bp->b_kvabase;
3431 if (bp->b_bufsize) {
3432 atomic_subtract_long(&bufmallocspace,
3437 bp->b_flags &= ~B_MALLOC;
3438 newbsize = round_page(newbsize);
3442 (vm_offset_t) bp->b_data + bp->b_bufsize,
3443 (vm_offset_t) bp->b_data + newbsize);
3445 bcopy(origbuf, bp->b_data, origbufsize);
3446 free(origbuf, M_BIOBUF);
3452 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3453 desiredpages = (size == 0) ? 0 :
3454 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3456 if (bp->b_flags & B_MALLOC)
3457 panic("allocbuf: VMIO buffer can't be malloced");
3459 * Set B_CACHE initially if buffer is 0 length or will become
3462 if (size == 0 || bp->b_bufsize == 0)
3463 bp->b_flags |= B_CACHE;
3465 if (newbsize < bp->b_bufsize) {
3467 * DEV_BSIZE aligned new buffer size is less then the
3468 * DEV_BSIZE aligned existing buffer size. Figure out
3469 * if we have to remove any pages.
3471 if (desiredpages < bp->b_npages) {
3474 if ((bp->b_flags & B_UNMAPPED) == 0) {
3475 BUF_CHECK_MAPPED(bp);
3476 pmap_qremove((vm_offset_t)trunc_page(
3477 (vm_offset_t)bp->b_data) +
3478 (desiredpages << PAGE_SHIFT),
3479 (bp->b_npages - desiredpages));
3481 BUF_CHECK_UNMAPPED(bp);
3482 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3483 for (i = desiredpages; i < bp->b_npages; i++) {
3485 * the page is not freed here -- it
3486 * is the responsibility of
3487 * vnode_pager_setsize
3490 KASSERT(m != bogus_page,
3491 ("allocbuf: bogus page found"));
3492 while (vm_page_sleep_if_busy(m,
3496 bp->b_pages[i] = NULL;
3498 vm_page_unwire(m, PQ_INACTIVE);
3501 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3502 bp->b_npages = desiredpages;
3504 } else if (size > bp->b_bcount) {
3506 * We are growing the buffer, possibly in a
3507 * byte-granular fashion.
3514 * Step 1, bring in the VM pages from the object,
3515 * allocating them if necessary. We must clear
3516 * B_CACHE if these pages are not valid for the
3517 * range covered by the buffer.
3520 obj = bp->b_bufobj->bo_object;
3522 VM_OBJECT_WLOCK(obj);
3523 while (bp->b_npages < desiredpages) {
3527 * We must allocate system pages since blocking
3528 * here could interfere with paging I/O, no
3529 * matter which process we are.
3531 * Only exclusive busy can be tested here.
3532 * Blocking on shared busy might lead to
3533 * deadlocks once allocbuf() is called after
3534 * pages are vfs_busy_pages().
3536 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3537 bp->b_npages, VM_ALLOC_NOBUSY |
3538 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3539 VM_ALLOC_IGN_SBUSY |
3540 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3542 bp->b_flags &= ~B_CACHE;
3543 bp->b_pages[bp->b_npages] = m;
3548 * Step 2. We've loaded the pages into the buffer,
3549 * we have to figure out if we can still have B_CACHE
3550 * set. Note that B_CACHE is set according to the
3551 * byte-granular range ( bcount and size ), new the
3552 * aligned range ( newbsize ).
3554 * The VM test is against m->valid, which is DEV_BSIZE
3555 * aligned. Needless to say, the validity of the data
3556 * needs to also be DEV_BSIZE aligned. Note that this
3557 * fails with NFS if the server or some other client
3558 * extends the file's EOF. If our buffer is resized,
3559 * B_CACHE may remain set! XXX
3562 toff = bp->b_bcount;
3563 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3565 while ((bp->b_flags & B_CACHE) && toff < size) {
3568 if (tinc > (size - toff))
3571 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3584 VM_OBJECT_WUNLOCK(obj);
3587 * Step 3, fixup the KVM pmap.
3589 if ((bp->b_flags & B_UNMAPPED) == 0)
3592 BUF_CHECK_UNMAPPED(bp);
3595 if (newbsize < bp->b_bufsize)
3597 bp->b_bufsize = newbsize; /* actual buffer allocation */
3598 bp->b_bcount = size; /* requested buffer size */
3602 extern int inflight_transient_maps;
3605 biodone(struct bio *bp)
3608 void (*done)(struct bio *);
3609 vm_offset_t start, end;
3611 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3612 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3613 bp->bio_flags |= BIO_UNMAPPED;
3614 start = trunc_page((vm_offset_t)bp->bio_data);
3615 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3616 bp->bio_data = unmapped_buf;
3617 pmap_qremove(start, OFF_TO_IDX(end - start));
3618 vmem_free(transient_arena, start, end - start);
3619 atomic_add_int(&inflight_transient_maps, -1);
3621 done = bp->bio_done;
3623 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3625 bp->bio_flags |= BIO_DONE;
3629 bp->bio_flags |= BIO_DONE;
3635 * Wait for a BIO to finish.
3638 biowait(struct bio *bp, const char *wchan)
3642 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3644 while ((bp->bio_flags & BIO_DONE) == 0)
3645 msleep(bp, mtxp, PRIBIO, wchan, 0);
3647 if (bp->bio_error != 0)
3648 return (bp->bio_error);
3649 if (!(bp->bio_flags & BIO_ERROR))
3655 biofinish(struct bio *bp, struct devstat *stat, int error)
3659 bp->bio_error = error;
3660 bp->bio_flags |= BIO_ERROR;
3663 devstat_end_transaction_bio(stat, bp);
3670 * Wait for buffer I/O completion, returning error status. The buffer
3671 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3672 * error and cleared.
3675 bufwait(struct buf *bp)
3677 if (bp->b_iocmd == BIO_READ)
3678 bwait(bp, PRIBIO, "biord");
3680 bwait(bp, PRIBIO, "biowr");
3681 if (bp->b_flags & B_EINTR) {
3682 bp->b_flags &= ~B_EINTR;
3685 if (bp->b_ioflags & BIO_ERROR) {
3686 return (bp->b_error ? bp->b_error : EIO);
3693 * Call back function from struct bio back up to struct buf.
3696 bufdonebio(struct bio *bip)
3700 bp = bip->bio_caller2;
3701 bp->b_resid = bip->bio_resid;
3702 bp->b_ioflags = bip->bio_flags;
3703 bp->b_error = bip->bio_error;
3705 bp->b_ioflags |= BIO_ERROR;
3711 dev_strategy(struct cdev *dev, struct buf *bp)
3716 KASSERT(dev->si_refcount > 0,
3717 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3718 devtoname(dev), dev));
3720 csw = dev_refthread(dev, &ref);
3721 dev_strategy_csw(dev, csw, bp);
3722 dev_relthread(dev, ref);
3726 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3730 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3732 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3733 dev->si_threadcount > 0,
3734 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3737 bp->b_error = ENXIO;
3738 bp->b_ioflags = BIO_ERROR;
3746 /* Try again later */
3747 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3749 bip->bio_cmd = bp->b_iocmd;
3750 bip->bio_offset = bp->b_iooffset;
3751 bip->bio_length = bp->b_bcount;
3752 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3754 bip->bio_done = bufdonebio;
3755 bip->bio_caller2 = bp;
3757 (*csw->d_strategy)(bip);
3763 * Finish I/O on a buffer, optionally calling a completion function.
3764 * This is usually called from an interrupt so process blocking is
3767 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3768 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3769 * assuming B_INVAL is clear.
3771 * For the VMIO case, we set B_CACHE if the op was a read and no
3772 * read error occured, or if the op was a write. B_CACHE is never
3773 * set if the buffer is invalid or otherwise uncacheable.
3775 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3776 * initiator to leave B_INVAL set to brelse the buffer out of existance
3777 * in the biodone routine.
3780 bufdone(struct buf *bp)
3782 struct bufobj *dropobj;
3783 void (*biodone)(struct buf *);
3785 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3788 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3789 BUF_ASSERT_HELD(bp);
3791 runningbufwakeup(bp);
3792 if (bp->b_iocmd == BIO_WRITE)
3793 dropobj = bp->b_bufobj;
3794 /* call optional completion function if requested */
3795 if (bp->b_iodone != NULL) {
3796 biodone = bp->b_iodone;
3797 bp->b_iodone = NULL;
3800 bufobj_wdrop(dropobj);
3807 bufobj_wdrop(dropobj);
3811 bufdone_finish(struct buf *bp)
3813 BUF_ASSERT_HELD(bp);
3815 if (!LIST_EMPTY(&bp->b_dep))
3818 if (bp->b_flags & B_VMIO) {
3823 int bogus, i, iosize;
3825 obj = bp->b_bufobj->bo_object;
3826 KASSERT(obj->paging_in_progress >= bp->b_npages,
3827 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3828 obj->paging_in_progress, bp->b_npages));
3831 KASSERT(vp->v_holdcnt > 0,
3832 ("biodone_finish: vnode %p has zero hold count", vp));
3833 KASSERT(vp->v_object != NULL,
3834 ("biodone_finish: vnode %p has no vm_object", vp));
3836 foff = bp->b_offset;
3837 KASSERT(bp->b_offset != NOOFFSET,
3838 ("biodone_finish: bp %p has no buffer offset", bp));
3841 * Set B_CACHE if the op was a normal read and no error
3842 * occured. B_CACHE is set for writes in the b*write()
3845 iosize = bp->b_bcount - bp->b_resid;
3846 if (bp->b_iocmd == BIO_READ &&
3847 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3848 !(bp->b_ioflags & BIO_ERROR)) {
3849 bp->b_flags |= B_CACHE;
3852 VM_OBJECT_WLOCK(obj);
3853 for (i = 0; i < bp->b_npages; i++) {
3857 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3862 * cleanup bogus pages, restoring the originals
3865 if (m == bogus_page) {
3866 bogus = bogusflag = 1;
3867 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3869 panic("biodone: page disappeared!");
3872 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3873 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3874 (intmax_t)foff, (uintmax_t)m->pindex));
3877 * In the write case, the valid and clean bits are
3878 * already changed correctly ( see bdwrite() ), so we
3879 * only need to do this here in the read case.
3881 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3882 KASSERT((m->dirty & vm_page_bits(foff &
3883 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3884 " page %p has unexpected dirty bits", m));
3885 vfs_page_set_valid(bp, foff, m);
3889 vm_object_pip_subtract(obj, 1);
3890 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3893 vm_object_pip_wakeupn(obj, 0);
3894 VM_OBJECT_WUNLOCK(obj);
3895 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3896 BUF_CHECK_MAPPED(bp);
3897 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3898 bp->b_pages, bp->b_npages);
3903 * For asynchronous completions, release the buffer now. The brelse
3904 * will do a wakeup there if necessary - so no need to do a wakeup
3905 * here in the async case. The sync case always needs to do a wakeup.
3908 if (bp->b_flags & B_ASYNC) {
3909 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3918 * This routine is called in lieu of iodone in the case of
3919 * incomplete I/O. This keeps the busy status for pages
3923 vfs_unbusy_pages(struct buf *bp)
3929 runningbufwakeup(bp);
3930 if (!(bp->b_flags & B_VMIO))
3933 obj = bp->b_bufobj->bo_object;
3934 VM_OBJECT_WLOCK(obj);
3935 for (i = 0; i < bp->b_npages; i++) {
3937 if (m == bogus_page) {
3938 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3940 panic("vfs_unbusy_pages: page missing\n");
3942 if ((bp->b_flags & B_UNMAPPED) == 0) {
3943 BUF_CHECK_MAPPED(bp);
3944 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3945 bp->b_pages, bp->b_npages);
3947 BUF_CHECK_UNMAPPED(bp);
3949 vm_object_pip_subtract(obj, 1);
3952 vm_object_pip_wakeupn(obj, 0);
3953 VM_OBJECT_WUNLOCK(obj);
3957 * vfs_page_set_valid:
3959 * Set the valid bits in a page based on the supplied offset. The
3960 * range is restricted to the buffer's size.
3962 * This routine is typically called after a read completes.
3965 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3970 * Compute the end offset, eoff, such that [off, eoff) does not span a
3971 * page boundary and eoff is not greater than the end of the buffer.
3972 * The end of the buffer, in this case, is our file EOF, not the
3973 * allocation size of the buffer.
3975 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3976 if (eoff > bp->b_offset + bp->b_bcount)
3977 eoff = bp->b_offset + bp->b_bcount;
3980 * Set valid range. This is typically the entire buffer and thus the
3984 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3988 * vfs_page_set_validclean:
3990 * Set the valid bits and clear the dirty bits in a page based on the
3991 * supplied offset. The range is restricted to the buffer's size.
3994 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3996 vm_ooffset_t soff, eoff;
3999 * Start and end offsets in buffer. eoff - soff may not cross a
4000 * page boundry or cross the end of the buffer. The end of the
4001 * buffer, in this case, is our file EOF, not the allocation size
4005 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4006 if (eoff > bp->b_offset + bp->b_bcount)
4007 eoff = bp->b_offset + bp->b_bcount;
4010 * Set valid range. This is typically the entire buffer and thus the
4014 vm_page_set_validclean(
4016 (vm_offset_t) (soff & PAGE_MASK),
4017 (vm_offset_t) (eoff - soff)
4023 * Ensure that all buffer pages are not exclusive busied. If any page is
4024 * exclusive busy, drain it.
4027 vfs_drain_busy_pages(struct buf *bp)
4032 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4034 for (i = 0; i < bp->b_npages; i++) {
4036 if (vm_page_xbusied(m)) {
4037 for (; last_busied < i; last_busied++)
4038 vm_page_sbusy(bp->b_pages[last_busied]);
4039 while (vm_page_xbusied(m)) {
4041 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4042 vm_page_busy_sleep(m, "vbpage");
4043 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4047 for (i = 0; i < last_busied; i++)
4048 vm_page_sunbusy(bp->b_pages[i]);
4052 * This routine is called before a device strategy routine.
4053 * It is used to tell the VM system that paging I/O is in
4054 * progress, and treat the pages associated with the buffer
4055 * almost as being exclusive busy. Also the object paging_in_progress
4056 * flag is handled to make sure that the object doesn't become
4059 * Since I/O has not been initiated yet, certain buffer flags
4060 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4061 * and should be ignored.
4064 vfs_busy_pages(struct buf *bp, int clear_modify)
4071 if (!(bp->b_flags & B_VMIO))
4074 obj = bp->b_bufobj->bo_object;
4075 foff = bp->b_offset;
4076 KASSERT(bp->b_offset != NOOFFSET,
4077 ("vfs_busy_pages: no buffer offset"));
4078 VM_OBJECT_WLOCK(obj);
4079 vfs_drain_busy_pages(bp);
4080 if (bp->b_bufsize != 0)
4081 vfs_setdirty_locked_object(bp);
4083 for (i = 0; i < bp->b_npages; i++) {
4086 if ((bp->b_flags & B_CLUSTER) == 0) {
4087 vm_object_pip_add(obj, 1);
4091 * When readying a buffer for a read ( i.e
4092 * clear_modify == 0 ), it is important to do
4093 * bogus_page replacement for valid pages in
4094 * partially instantiated buffers. Partially
4095 * instantiated buffers can, in turn, occur when
4096 * reconstituting a buffer from its VM backing store
4097 * base. We only have to do this if B_CACHE is
4098 * clear ( which causes the I/O to occur in the
4099 * first place ). The replacement prevents the read
4100 * I/O from overwriting potentially dirty VM-backed
4101 * pages. XXX bogus page replacement is, uh, bogus.
4102 * It may not work properly with small-block devices.
4103 * We need to find a better way.
4106 pmap_remove_write(m);
4107 vfs_page_set_validclean(bp, foff, m);
4108 } else if (m->valid == VM_PAGE_BITS_ALL &&
4109 (bp->b_flags & B_CACHE) == 0) {
4110 bp->b_pages[i] = bogus_page;
4113 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4115 VM_OBJECT_WUNLOCK(obj);
4116 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4117 BUF_CHECK_MAPPED(bp);
4118 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4119 bp->b_pages, bp->b_npages);
4124 * vfs_bio_set_valid:
4126 * Set the range within the buffer to valid. The range is
4127 * relative to the beginning of the buffer, b_offset. Note that
4128 * b_offset itself may be offset from the beginning of the first
4132 vfs_bio_set_valid(struct buf *bp, int base, int size)
4137 if (!(bp->b_flags & B_VMIO))
4141 * Fixup base to be relative to beginning of first page.
4142 * Set initial n to be the maximum number of bytes in the
4143 * first page that can be validated.
4145 base += (bp->b_offset & PAGE_MASK);
4146 n = PAGE_SIZE - (base & PAGE_MASK);
4148 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4149 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4153 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4158 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4164 * If the specified buffer is a non-VMIO buffer, clear the entire
4165 * buffer. If the specified buffer is a VMIO buffer, clear and
4166 * validate only the previously invalid portions of the buffer.
4167 * This routine essentially fakes an I/O, so we need to clear
4168 * BIO_ERROR and B_INVAL.
4170 * Note that while we only theoretically need to clear through b_bcount,
4171 * we go ahead and clear through b_bufsize.
4174 vfs_bio_clrbuf(struct buf *bp)
4176 int i, j, mask, sa, ea, slide;
4178 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4182 bp->b_flags &= ~B_INVAL;
4183 bp->b_ioflags &= ~BIO_ERROR;
4184 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4185 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4186 (bp->b_offset & PAGE_MASK) == 0) {
4187 if (bp->b_pages[0] == bogus_page)
4189 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4190 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4191 if ((bp->b_pages[0]->valid & mask) == mask)
4193 if ((bp->b_pages[0]->valid & mask) == 0) {
4194 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4195 bp->b_pages[0]->valid |= mask;
4199 sa = bp->b_offset & PAGE_MASK;
4201 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4202 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4203 ea = slide & PAGE_MASK;
4206 if (bp->b_pages[i] == bogus_page)
4209 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4210 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4211 if ((bp->b_pages[i]->valid & mask) == mask)
4213 if ((bp->b_pages[i]->valid & mask) == 0)
4214 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4216 for (; sa < ea; sa += DEV_BSIZE, j++) {
4217 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4218 pmap_zero_page_area(bp->b_pages[i],
4223 bp->b_pages[i]->valid |= mask;
4226 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4231 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4236 if ((bp->b_flags & B_UNMAPPED) == 0) {
4237 BUF_CHECK_MAPPED(bp);
4238 bzero(bp->b_data + base, size);
4240 BUF_CHECK_UNMAPPED(bp);
4241 n = PAGE_SIZE - (base & PAGE_MASK);
4242 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4246 pmap_zero_page_area(m, base & PAGE_MASK, n);
4255 * vm_hold_load_pages and vm_hold_free_pages get pages into
4256 * a buffers address space. The pages are anonymous and are
4257 * not associated with a file object.
4260 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4266 BUF_CHECK_MAPPED(bp);
4268 to = round_page(to);
4269 from = round_page(from);
4270 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4272 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4275 * note: must allocate system pages since blocking here
4276 * could interfere with paging I/O, no matter which
4279 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4280 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4285 pmap_qenter(pg, &p, 1);
4286 bp->b_pages[index] = p;
4288 bp->b_npages = index;
4291 /* Return pages associated with this buf to the vm system */
4293 vm_hold_free_pages(struct buf *bp, int newbsize)
4297 int index, newnpages;
4299 BUF_CHECK_MAPPED(bp);
4301 from = round_page((vm_offset_t)bp->b_data + newbsize);
4302 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4303 if (bp->b_npages > newnpages)
4304 pmap_qremove(from, bp->b_npages - newnpages);
4305 for (index = newnpages; index < bp->b_npages; index++) {
4306 p = bp->b_pages[index];
4307 bp->b_pages[index] = NULL;
4308 if (vm_page_sbusied(p))
4309 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4310 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4313 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
4315 bp->b_npages = newnpages;
4319 * Map an IO request into kernel virtual address space.
4321 * All requests are (re)mapped into kernel VA space.
4322 * Notice that we use b_bufsize for the size of the buffer
4323 * to be mapped. b_bcount might be modified by the driver.
4325 * Note that even if the caller determines that the address space should
4326 * be valid, a race or a smaller-file mapped into a larger space may
4327 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4328 * check the return value.
4331 vmapbuf(struct buf *bp, int mapbuf)
4337 if (bp->b_bufsize < 0)
4339 prot = VM_PROT_READ;
4340 if (bp->b_iocmd == BIO_READ)
4341 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4342 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4343 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4344 btoc(MAXPHYS))) < 0)
4346 bp->b_npages = pidx;
4347 if (mapbuf || !unmapped_buf_allowed) {
4348 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4349 kva = bp->b_saveaddr;
4350 bp->b_saveaddr = bp->b_data;
4351 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4352 bp->b_flags &= ~B_UNMAPPED;
4354 bp->b_flags |= B_UNMAPPED;
4355 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4356 bp->b_saveaddr = bp->b_data;
4357 bp->b_data = unmapped_buf;
4363 * Free the io map PTEs associated with this IO operation.
4364 * We also invalidate the TLB entries and restore the original b_addr.
4367 vunmapbuf(struct buf *bp)
4371 npages = bp->b_npages;
4372 if (bp->b_flags & B_UNMAPPED)
4373 bp->b_flags &= ~B_UNMAPPED;
4375 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4376 vm_page_unhold_pages(bp->b_pages, npages);
4378 bp->b_data = bp->b_saveaddr;
4382 bdone(struct buf *bp)
4386 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4388 bp->b_flags |= B_DONE;
4394 bwait(struct buf *bp, u_char pri, const char *wchan)
4398 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4400 while ((bp->b_flags & B_DONE) == 0)
4401 msleep(bp, mtxp, pri, wchan, 0);
4406 bufsync(struct bufobj *bo, int waitfor)
4409 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4413 bufstrategy(struct bufobj *bo, struct buf *bp)
4419 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4420 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4421 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4422 i = VOP_STRATEGY(vp, bp);
4423 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4427 bufobj_wrefl(struct bufobj *bo)
4430 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4431 ASSERT_BO_WLOCKED(bo);
4436 bufobj_wref(struct bufobj *bo)
4439 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4446 bufobj_wdrop(struct bufobj *bo)
4449 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4451 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4452 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4453 bo->bo_flag &= ~BO_WWAIT;
4454 wakeup(&bo->bo_numoutput);
4460 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4464 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4465 ASSERT_BO_WLOCKED(bo);
4467 while (bo->bo_numoutput) {
4468 bo->bo_flag |= BO_WWAIT;
4469 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4470 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4478 bpin(struct buf *bp)
4482 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4489 bunpin(struct buf *bp)
4493 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4495 if (--bp->b_pin_count == 0)
4501 bunpin_wait(struct buf *bp)
4505 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4507 while (bp->b_pin_count > 0)
4508 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4513 * Set bio_data or bio_ma for struct bio from the struct buf.
4516 bdata2bio(struct buf *bp, struct bio *bip)
4519 if ((bp->b_flags & B_UNMAPPED) != 0) {
4520 KASSERT(unmapped_buf_allowed, ("unmapped"));
4521 bip->bio_ma = bp->b_pages;
4522 bip->bio_ma_n = bp->b_npages;
4523 bip->bio_data = unmapped_buf;
4524 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4525 bip->bio_flags |= BIO_UNMAPPED;
4526 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4527 PAGE_SIZE == bp->b_npages,
4528 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4529 (long long)bip->bio_length, bip->bio_ma_n));
4531 bip->bio_data = bp->b_data;
4536 #include "opt_ddb.h"
4538 #include <ddb/ddb.h>
4540 /* DDB command to show buffer data */
4541 DB_SHOW_COMMAND(buffer, db_show_buffer)
4544 struct buf *bp = (struct buf *)addr;
4547 db_printf("usage: show buffer <addr>\n");
4551 db_printf("buf at %p\n", bp);
4552 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4553 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4554 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4556 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4557 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4559 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4560 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4561 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4564 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4565 for (i = 0; i < bp->b_npages; i++) {
4568 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4569 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4570 if ((i + 1) < bp->b_npages)
4576 BUF_LOCKPRINTINFO(bp);
4579 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4584 for (i = 0; i < nbuf; i++) {
4586 if (BUF_ISLOCKED(bp)) {
4587 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4593 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4599 db_printf("usage: show vnodebufs <addr>\n");
4602 vp = (struct vnode *)addr;
4603 db_printf("Clean buffers:\n");
4604 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4605 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4608 db_printf("Dirty buffers:\n");
4609 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4610 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4615 DB_COMMAND(countfreebufs, db_coundfreebufs)
4618 int i, used = 0, nfree = 0;
4621 db_printf("usage: countfreebufs\n");
4625 for (i = 0; i < nbuf; i++) {
4627 if ((bp->b_flags & B_INFREECNT) != 0)
4633 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4635 db_printf("numfreebuffers is %d\n", numfreebuffers);