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 mtx_init(&bqclean, "bufq clean lock", NULL, MTX_DEF);
809 mtx_init(&bqdirty, "bufq dirty lock", NULL, MTX_DEF);
810 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
811 rw_init(&nblock, "needsbuffer lock");
812 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
813 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
815 /* next, make a null set of free lists */
816 for (i = 0; i < BUFFER_QUEUES; i++)
817 TAILQ_INIT(&bufqueues[i]);
819 /* finally, initialize each buffer header and stick on empty q */
820 for (i = 0; i < nbuf; i++) {
822 bzero(bp, sizeof *bp);
823 bp->b_flags = B_INVAL | B_INFREECNT;
824 bp->b_rcred = NOCRED;
825 bp->b_wcred = NOCRED;
826 bp->b_qindex = QUEUE_EMPTY;
828 LIST_INIT(&bp->b_dep);
830 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
832 bq_len[QUEUE_EMPTY]++;
837 * maxbufspace is the absolute maximum amount of buffer space we are
838 * allowed to reserve in KVM and in real terms. The absolute maximum
839 * is nominally used by buf_daemon. hibufspace is the nominal maximum
840 * used by most other processes. The differential is required to
841 * ensure that buf_daemon is able to run when other processes might
842 * be blocked waiting for buffer space.
844 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
845 * this may result in KVM fragmentation which is not handled optimally
848 maxbufspace = (long)nbuf * BKVASIZE;
849 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
850 lobufspace = hibufspace - MAXBSIZE;
853 * Note: The 16 MiB upper limit for hirunningspace was chosen
854 * arbitrarily and may need further tuning. It corresponds to
855 * 128 outstanding write IO requests (if IO size is 128 KiB),
856 * which fits with many RAID controllers' tagged queuing limits.
857 * The lower 1 MiB limit is the historical upper limit for
860 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
861 16 * 1024 * 1024), 1024 * 1024);
862 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
865 * Limit the amount of malloc memory since it is wired permanently into
866 * the kernel space. Even though this is accounted for in the buffer
867 * allocation, we don't want the malloced region to grow uncontrolled.
868 * The malloc scheme improves memory utilization significantly on average
869 * (small) directories.
871 maxbufmallocspace = hibufspace / 20;
874 * Reduce the chance of a deadlock occuring by limiting the number
875 * of delayed-write dirty buffers we allow to stack up.
877 hidirtybuffers = nbuf / 4 + 20;
878 dirtybufthresh = hidirtybuffers * 9 / 10;
881 * To support extreme low-memory systems, make sure hidirtybuffers cannot
882 * eat up all available buffer space. This occurs when our minimum cannot
883 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
884 * BKVASIZE'd buffers.
886 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
887 hidirtybuffers >>= 1;
889 lodirtybuffers = hidirtybuffers / 2;
892 * Try to keep the number of free buffers in the specified range,
893 * and give special processes (e.g. like buf_daemon) access to an
896 lofreebuffers = nbuf / 18 + 5;
897 hifreebuffers = 2 * lofreebuffers;
898 numfreebuffers = nbuf;
900 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
901 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
902 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
907 vfs_buf_check_mapped(struct buf *bp)
910 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
911 ("mapped buf %p %x", bp, bp->b_flags));
912 KASSERT(bp->b_kvabase != unmapped_buf,
913 ("mapped buf: b_kvabase was not updated %p", bp));
914 KASSERT(bp->b_data != unmapped_buf,
915 ("mapped buf: b_data was not updated %p", bp));
919 vfs_buf_check_unmapped(struct buf *bp)
922 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
923 ("unmapped buf %p %x", bp, bp->b_flags));
924 KASSERT(bp->b_kvabase == unmapped_buf,
925 ("unmapped buf: corrupted b_kvabase %p", bp));
926 KASSERT(bp->b_data == unmapped_buf,
927 ("unmapped buf: corrupted b_data %p", bp));
930 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
931 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
933 #define BUF_CHECK_MAPPED(bp) do {} while (0)
934 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
938 bpmap_qenter(struct buf *bp)
941 BUF_CHECK_MAPPED(bp);
944 * bp->b_data is relative to bp->b_offset, but
945 * bp->b_offset may be offset into the first page.
947 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
948 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
949 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
950 (vm_offset_t)(bp->b_offset & PAGE_MASK));
954 * bfreekva() - free the kva allocation for a buffer.
956 * Since this call frees up buffer space, we call bufspacewakeup().
959 bfreekva(struct buf *bp)
962 if (bp->b_kvasize == 0)
965 atomic_add_int(&buffreekvacnt, 1);
966 atomic_subtract_long(&bufspace, bp->b_kvasize);
967 if ((bp->b_flags & B_UNMAPPED) == 0) {
968 BUF_CHECK_MAPPED(bp);
969 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase,
972 BUF_CHECK_UNMAPPED(bp);
973 if ((bp->b_flags & B_KVAALLOC) != 0) {
974 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvaalloc,
977 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
978 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
987 * Insert the buffer into the appropriate free list.
990 binsfree(struct buf *bp, int qindex)
992 struct mtx *olock, *nlock;
994 BUF_ASSERT_XLOCKED(bp);
996 olock = bqlock(bp->b_qindex);
997 nlock = bqlock(qindex);
999 /* Handle delayed bremfree() processing. */
1000 if (bp->b_flags & B_REMFREE)
1003 if (bp->b_qindex != QUEUE_NONE)
1004 panic("binsfree: free buffer onto another queue???");
1006 bp->b_qindex = qindex;
1007 if (olock != nlock) {
1011 if (bp->b_flags & B_AGE)
1012 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1014 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1016 bq_len[bp->b_qindex]++;
1021 * Something we can maybe free or reuse.
1023 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1026 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1033 * Mark the buffer for removal from the appropriate free list.
1037 bremfree(struct buf *bp)
1040 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1041 KASSERT((bp->b_flags & B_REMFREE) == 0,
1042 ("bremfree: buffer %p already marked for delayed removal.", bp));
1043 KASSERT(bp->b_qindex != QUEUE_NONE,
1044 ("bremfree: buffer %p not on a queue.", bp));
1045 BUF_ASSERT_XLOCKED(bp);
1047 bp->b_flags |= B_REMFREE;
1054 * Force an immediate removal from a free list. Used only in nfs when
1055 * it abuses the b_freelist pointer.
1058 bremfreef(struct buf *bp)
1062 qlock = bqlock(bp->b_qindex);
1071 * Removes a buffer from the free list, must be called with the
1072 * correct qlock held.
1075 bremfreel(struct buf *bp)
1078 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1079 bp, bp->b_vp, bp->b_flags);
1080 KASSERT(bp->b_qindex != QUEUE_NONE,
1081 ("bremfreel: buffer %p not on a queue.", bp));
1082 BUF_ASSERT_XLOCKED(bp);
1083 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1085 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1087 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1089 bq_len[bp->b_qindex]--;
1091 bp->b_qindex = QUEUE_NONE;
1093 * If this was a delayed bremfree() we only need to remove the buffer
1094 * from the queue and return the stats are already done.
1096 if (bp->b_flags & B_REMFREE) {
1097 bp->b_flags &= ~B_REMFREE;
1104 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1105 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1106 * the buffer is valid and we do not have to do anything.
1109 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1110 int cnt, struct ucred * cred)
1115 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1116 if (inmem(vp, *rablkno))
1118 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1120 if ((rabp->b_flags & B_CACHE) == 0) {
1121 if (!TD_IS_IDLETHREAD(curthread))
1122 curthread->td_ru.ru_inblock++;
1123 rabp->b_flags |= B_ASYNC;
1124 rabp->b_flags &= ~B_INVAL;
1125 rabp->b_ioflags &= ~BIO_ERROR;
1126 rabp->b_iocmd = BIO_READ;
1127 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1128 rabp->b_rcred = crhold(cred);
1129 vfs_busy_pages(rabp, 0);
1131 rabp->b_iooffset = dbtob(rabp->b_blkno);
1140 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1142 * Get a buffer with the specified data. Look in the cache first. We
1143 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1144 * is set, the buffer is valid and we do not have to do anything, see
1145 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1148 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1149 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1152 int rv = 0, readwait = 0;
1154 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1156 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1158 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1162 /* if not found in cache, do some I/O */
1163 if ((bp->b_flags & B_CACHE) == 0) {
1164 if (!TD_IS_IDLETHREAD(curthread))
1165 curthread->td_ru.ru_inblock++;
1166 bp->b_iocmd = BIO_READ;
1167 bp->b_flags &= ~B_INVAL;
1168 bp->b_ioflags &= ~BIO_ERROR;
1169 if (bp->b_rcred == NOCRED && cred != NOCRED)
1170 bp->b_rcred = crhold(cred);
1171 vfs_busy_pages(bp, 0);
1172 bp->b_iooffset = dbtob(bp->b_blkno);
1177 breada(vp, rablkno, rabsize, cnt, cred);
1186 * Write, release buffer on completion. (Done by iodone
1187 * if async). Do not bother writing anything if the buffer
1190 * Note that we set B_CACHE here, indicating that buffer is
1191 * fully valid and thus cacheable. This is true even of NFS
1192 * now so we set it generally. This could be set either here
1193 * or in biodone() since the I/O is synchronous. We put it
1197 bufwrite(struct buf *bp)
1204 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1205 if (bp->b_flags & B_INVAL) {
1210 if (bp->b_flags & B_BARRIER)
1213 oldflags = bp->b_flags;
1215 BUF_ASSERT_HELD(bp);
1217 if (bp->b_pin_count > 0)
1220 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1221 ("FFS background buffer should not get here %p", bp));
1225 vp_md = vp->v_vflag & VV_MD;
1230 * Mark the buffer clean. Increment the bufobj write count
1231 * before bundirty() call, to prevent other thread from seeing
1232 * empty dirty list and zero counter for writes in progress,
1233 * falsely indicating that the bufobj is clean.
1235 bufobj_wref(bp->b_bufobj);
1238 bp->b_flags &= ~B_DONE;
1239 bp->b_ioflags &= ~BIO_ERROR;
1240 bp->b_flags |= B_CACHE;
1241 bp->b_iocmd = BIO_WRITE;
1243 vfs_busy_pages(bp, 1);
1246 * Normal bwrites pipeline writes
1248 bp->b_runningbufspace = bp->b_bufsize;
1249 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1251 if (!TD_IS_IDLETHREAD(curthread))
1252 curthread->td_ru.ru_oublock++;
1253 if (oldflags & B_ASYNC)
1255 bp->b_iooffset = dbtob(bp->b_blkno);
1258 if ((oldflags & B_ASYNC) == 0) {
1259 int rtval = bufwait(bp);
1262 } else if (space > hirunningspace) {
1264 * don't allow the async write to saturate the I/O
1265 * system. We will not deadlock here because
1266 * we are blocking waiting for I/O that is already in-progress
1267 * to complete. We do not block here if it is the update
1268 * or syncer daemon trying to clean up as that can lead
1271 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1272 waitrunningbufspace();
1279 bufbdflush(struct bufobj *bo, struct buf *bp)
1283 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1284 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1286 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1289 * Try to find a buffer to flush.
1291 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1292 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1294 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1297 panic("bdwrite: found ourselves");
1299 /* Don't countdeps with the bo lock held. */
1300 if (buf_countdeps(nbp, 0)) {
1305 if (nbp->b_flags & B_CLUSTEROK) {
1306 vfs_bio_awrite(nbp);
1311 dirtybufferflushes++;
1320 * Delayed write. (Buffer is marked dirty). Do not bother writing
1321 * anything if the buffer is marked invalid.
1323 * Note that since the buffer must be completely valid, we can safely
1324 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1325 * biodone() in order to prevent getblk from writing the buffer
1326 * out synchronously.
1329 bdwrite(struct buf *bp)
1331 struct thread *td = curthread;
1335 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1336 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1337 KASSERT((bp->b_flags & B_BARRIER) == 0,
1338 ("Barrier request in delayed write %p", bp));
1339 BUF_ASSERT_HELD(bp);
1341 if (bp->b_flags & B_INVAL) {
1347 * If we have too many dirty buffers, don't create any more.
1348 * If we are wildly over our limit, then force a complete
1349 * cleanup. Otherwise, just keep the situation from getting
1350 * out of control. Note that we have to avoid a recursive
1351 * disaster and not try to clean up after our own cleanup!
1355 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1356 td->td_pflags |= TDP_INBDFLUSH;
1358 td->td_pflags &= ~TDP_INBDFLUSH;
1364 * Set B_CACHE, indicating that the buffer is fully valid. This is
1365 * true even of NFS now.
1367 bp->b_flags |= B_CACHE;
1370 * This bmap keeps the system from needing to do the bmap later,
1371 * perhaps when the system is attempting to do a sync. Since it
1372 * is likely that the indirect block -- or whatever other datastructure
1373 * that the filesystem needs is still in memory now, it is a good
1374 * thing to do this. Note also, that if the pageout daemon is
1375 * requesting a sync -- there might not be enough memory to do
1376 * the bmap then... So, this is important to do.
1378 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1379 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1383 * Set the *dirty* buffer range based upon the VM system dirty
1386 * Mark the buffer pages as clean. We need to do this here to
1387 * satisfy the vnode_pager and the pageout daemon, so that it
1388 * thinks that the pages have been "cleaned". Note that since
1389 * the pages are in a delayed write buffer -- the VFS layer
1390 * "will" see that the pages get written out on the next sync,
1391 * or perhaps the cluster will be completed.
1393 vfs_clean_pages_dirty_buf(bp);
1397 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1398 * due to the softdep code.
1405 * Turn buffer into delayed write request. We must clear BIO_READ and
1406 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1407 * itself to properly update it in the dirty/clean lists. We mark it
1408 * B_DONE to ensure that any asynchronization of the buffer properly
1409 * clears B_DONE ( else a panic will occur later ).
1411 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1412 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1413 * should only be called if the buffer is known-good.
1415 * Since the buffer is not on a queue, we do not update the numfreebuffers
1418 * The buffer must be on QUEUE_NONE.
1421 bdirty(struct buf *bp)
1424 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1425 bp, bp->b_vp, bp->b_flags);
1426 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1427 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1428 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1429 BUF_ASSERT_HELD(bp);
1430 bp->b_flags &= ~(B_RELBUF);
1431 bp->b_iocmd = BIO_WRITE;
1433 if ((bp->b_flags & B_DELWRI) == 0) {
1434 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1443 * Clear B_DELWRI for buffer.
1445 * Since the buffer is not on a queue, we do not update the numfreebuffers
1448 * The buffer must be on QUEUE_NONE.
1452 bundirty(struct buf *bp)
1455 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1456 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1457 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1458 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1459 BUF_ASSERT_HELD(bp);
1461 if (bp->b_flags & B_DELWRI) {
1462 bp->b_flags &= ~B_DELWRI;
1467 * Since it is now being written, we can clear its deferred write flag.
1469 bp->b_flags &= ~B_DEFERRED;
1475 * Asynchronous write. Start output on a buffer, but do not wait for
1476 * it to complete. The buffer is released when the output completes.
1478 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1479 * B_INVAL buffers. Not us.
1482 bawrite(struct buf *bp)
1485 bp->b_flags |= B_ASYNC;
1492 * Asynchronous barrier write. Start output on a buffer, but do not
1493 * wait for it to complete. Place a write barrier after this write so
1494 * that this buffer and all buffers written before it are committed to
1495 * the disk before any buffers written after this write are committed
1496 * to the disk. The buffer is released when the output completes.
1499 babarrierwrite(struct buf *bp)
1502 bp->b_flags |= B_ASYNC | B_BARRIER;
1509 * Synchronous barrier write. Start output on a buffer and wait for
1510 * it to complete. Place a write barrier after this write so that
1511 * this buffer and all buffers written before it are committed to
1512 * the disk before any buffers written after this write are committed
1513 * to the disk. The buffer is released when the output completes.
1516 bbarrierwrite(struct buf *bp)
1519 bp->b_flags |= B_BARRIER;
1520 return (bwrite(bp));
1526 * Called prior to the locking of any vnodes when we are expecting to
1527 * write. We do not want to starve the buffer cache with too many
1528 * dirty buffers so we block here. By blocking prior to the locking
1529 * of any vnodes we attempt to avoid the situation where a locked vnode
1530 * prevents the various system daemons from flushing related buffers.
1536 if (numdirtybuffers >= hidirtybuffers) {
1537 mtx_lock(&bdirtylock);
1538 while (numdirtybuffers >= hidirtybuffers) {
1540 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
1543 mtx_unlock(&bdirtylock);
1548 * Return true if we have too many dirty buffers.
1551 buf_dirty_count_severe(void)
1554 return(numdirtybuffers >= hidirtybuffers);
1557 static __noinline int
1558 buf_vm_page_count_severe(void)
1561 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1563 return vm_page_count_severe();
1569 * Release a busy buffer and, if requested, free its resources. The
1570 * buffer will be stashed in the appropriate bufqueue[] allowing it
1571 * to be accessed later as a cache entity or reused for other purposes.
1574 brelse(struct buf *bp)
1578 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1579 bp, bp->b_vp, bp->b_flags);
1580 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1581 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1583 if (BUF_LOCKRECURSED(bp)) {
1585 * Do not process, in particular, do not handle the
1586 * B_INVAL/B_RELBUF and do not release to free list.
1592 if (bp->b_flags & B_MANAGED) {
1597 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1598 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1600 * Failed write, redirty. Must clear BIO_ERROR to prevent
1601 * pages from being scrapped. If the error is anything
1602 * other than an I/O error (EIO), assume that retrying
1605 bp->b_ioflags &= ~BIO_ERROR;
1607 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1608 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1610 * Either a failed I/O or we were asked to free or not
1613 bp->b_flags |= B_INVAL;
1614 if (!LIST_EMPTY(&bp->b_dep))
1616 if (bp->b_flags & B_DELWRI)
1618 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1619 if ((bp->b_flags & B_VMIO) == 0) {
1628 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1629 * is called with B_DELWRI set, the underlying pages may wind up
1630 * getting freed causing a previous write (bdwrite()) to get 'lost'
1631 * because pages associated with a B_DELWRI bp are marked clean.
1633 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1634 * if B_DELWRI is set.
1636 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1637 * on pages to return pages to the VM page queues.
1639 if (bp->b_flags & B_DELWRI)
1640 bp->b_flags &= ~B_RELBUF;
1641 else if (buf_vm_page_count_severe()) {
1643 * BKGRDINPROG can only be set with the buf and bufobj
1644 * locks both held. We tolerate a race to clear it here.
1646 if (!(bp->b_vflags & BV_BKGRDINPROG))
1647 bp->b_flags |= B_RELBUF;
1651 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1652 * constituted, not even NFS buffers now. Two flags effect this. If
1653 * B_INVAL, the struct buf is invalidated but the VM object is kept
1654 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1656 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1657 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1658 * buffer is also B_INVAL because it hits the re-dirtying code above.
1660 * Normally we can do this whether a buffer is B_DELWRI or not. If
1661 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1662 * the commit state and we cannot afford to lose the buffer. If the
1663 * buffer has a background write in progress, we need to keep it
1664 * around to prevent it from being reconstituted and starting a second
1667 if ((bp->b_flags & B_VMIO)
1668 && !(bp->b_vp->v_mount != NULL &&
1669 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1670 !vn_isdisk(bp->b_vp, NULL) &&
1671 (bp->b_flags & B_DELWRI))
1680 obj = bp->b_bufobj->bo_object;
1683 * Get the base offset and length of the buffer. Note that
1684 * in the VMIO case if the buffer block size is not
1685 * page-aligned then b_data pointer may not be page-aligned.
1686 * But our b_pages[] array *IS* page aligned.
1688 * block sizes less then DEV_BSIZE (usually 512) are not
1689 * supported due to the page granularity bits (m->valid,
1690 * m->dirty, etc...).
1692 * See man buf(9) for more information
1694 resid = bp->b_bufsize;
1695 foff = bp->b_offset;
1696 for (i = 0; i < bp->b_npages; i++) {
1702 * If we hit a bogus page, fixup *all* the bogus pages
1705 if (m == bogus_page) {
1706 poff = OFF_TO_IDX(bp->b_offset);
1709 VM_OBJECT_RLOCK(obj);
1710 for (j = i; j < bp->b_npages; j++) {
1712 mtmp = bp->b_pages[j];
1713 if (mtmp == bogus_page) {
1714 mtmp = vm_page_lookup(obj, poff + j);
1716 panic("brelse: page missing\n");
1718 bp->b_pages[j] = mtmp;
1721 VM_OBJECT_RUNLOCK(obj);
1723 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1724 BUF_CHECK_MAPPED(bp);
1726 trunc_page((vm_offset_t)bp->b_data),
1727 bp->b_pages, bp->b_npages);
1731 if ((bp->b_flags & B_NOCACHE) ||
1732 (bp->b_ioflags & BIO_ERROR &&
1733 bp->b_iocmd == BIO_READ)) {
1734 int poffset = foff & PAGE_MASK;
1735 int presid = resid > (PAGE_SIZE - poffset) ?
1736 (PAGE_SIZE - poffset) : resid;
1738 KASSERT(presid >= 0, ("brelse: extra page"));
1739 VM_OBJECT_WLOCK(obj);
1740 while (vm_page_xbusied(m)) {
1742 VM_OBJECT_WUNLOCK(obj);
1743 vm_page_busy_sleep(m, "mbncsh");
1744 VM_OBJECT_WLOCK(obj);
1746 if (pmap_page_wired_mappings(m) == 0)
1747 vm_page_set_invalid(m, poffset, presid);
1748 VM_OBJECT_WUNLOCK(obj);
1750 printf("avoided corruption bug in bogus_page/brelse code\n");
1752 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1753 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1755 if (bp->b_flags & (B_INVAL | B_RELBUF))
1756 vfs_vmio_release(bp);
1758 } else if (bp->b_flags & B_VMIO) {
1760 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1761 vfs_vmio_release(bp);
1764 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1765 if (bp->b_bufsize != 0)
1767 if (bp->b_vp != NULL)
1772 * If the buffer has junk contents signal it and eventually
1773 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1776 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1777 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1778 bp->b_flags |= B_INVAL;
1779 if (bp->b_flags & B_INVAL) {
1780 if (bp->b_flags & B_DELWRI)
1786 /* buffers with no memory */
1787 if (bp->b_bufsize == 0) {
1788 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1789 if (bp->b_vflags & BV_BKGRDINPROG)
1790 panic("losing buffer 1");
1792 qindex = QUEUE_EMPTYKVA;
1794 qindex = QUEUE_EMPTY;
1795 bp->b_flags |= B_AGE;
1796 /* buffers with junk contents */
1797 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1798 (bp->b_ioflags & BIO_ERROR)) {
1799 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1800 if (bp->b_vflags & BV_BKGRDINPROG)
1801 panic("losing buffer 2");
1802 qindex = QUEUE_CLEAN;
1803 bp->b_flags |= B_AGE;
1804 /* remaining buffers */
1805 } else if (bp->b_flags & B_DELWRI)
1806 qindex = QUEUE_DIRTY;
1808 qindex = QUEUE_CLEAN;
1810 binsfree(bp, qindex);
1812 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1813 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1814 panic("brelse: not dirty");
1820 * Release a buffer back to the appropriate queue but do not try to free
1821 * it. The buffer is expected to be used again soon.
1823 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1824 * biodone() to requeue an async I/O on completion. It is also used when
1825 * known good buffers need to be requeued but we think we may need the data
1828 * XXX we should be able to leave the B_RELBUF hint set on completion.
1831 bqrelse(struct buf *bp)
1835 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1836 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1837 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1839 if (BUF_LOCKRECURSED(bp)) {
1840 /* do not release to free list */
1844 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1846 if (bp->b_flags & B_MANAGED) {
1847 if (bp->b_flags & B_REMFREE)
1852 /* buffers with stale but valid contents */
1853 if (bp->b_flags & B_DELWRI) {
1854 qindex = QUEUE_DIRTY;
1856 if ((bp->b_flags & B_DELWRI) == 0 &&
1857 (bp->b_xflags & BX_VNDIRTY))
1858 panic("bqrelse: not dirty");
1860 * BKGRDINPROG can only be set with the buf and bufobj
1861 * locks both held. We tolerate a race to clear it here.
1863 if (buf_vm_page_count_severe() &&
1864 (bp->b_vflags & BV_BKGRDINPROG) == 0) {
1866 * We are too low on memory, we have to try to free
1867 * the buffer (most importantly: the wired pages
1868 * making up its backing store) *now*.
1873 qindex = QUEUE_CLEAN;
1875 binsfree(bp, qindex);
1882 /* Give pages used by the bp back to the VM system (where possible) */
1884 vfs_vmio_release(struct buf *bp)
1889 if ((bp->b_flags & B_UNMAPPED) == 0) {
1890 BUF_CHECK_MAPPED(bp);
1891 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1893 BUF_CHECK_UNMAPPED(bp);
1894 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
1895 for (i = 0; i < bp->b_npages; i++) {
1897 bp->b_pages[i] = NULL;
1899 * In order to keep page LRU ordering consistent, put
1900 * everything on the inactive queue.
1903 vm_page_unwire(m, PQ_INACTIVE);
1906 * Might as well free the page if we can and it has
1907 * no valid data. We also free the page if the
1908 * buffer was used for direct I/O
1910 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1911 if (m->wire_count == 0 && !vm_page_busied(m))
1913 } else if (bp->b_flags & B_DIRECT)
1914 vm_page_try_to_free(m);
1915 else if (buf_vm_page_count_severe())
1916 vm_page_try_to_cache(m);
1919 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
1921 if (bp->b_bufsize) {
1926 bp->b_flags &= ~B_VMIO;
1932 * Check to see if a block at a particular lbn is available for a clustered
1936 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1943 /* If the buf isn't in core skip it */
1944 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1947 /* If the buf is busy we don't want to wait for it */
1948 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1951 /* Only cluster with valid clusterable delayed write buffers */
1952 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1953 (B_DELWRI | B_CLUSTEROK))
1956 if (bpa->b_bufsize != size)
1960 * Check to see if it is in the expected place on disk and that the
1961 * block has been mapped.
1963 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1973 * Implement clustered async writes for clearing out B_DELWRI buffers.
1974 * This is much better then the old way of writing only one buffer at
1975 * a time. Note that we may not be presented with the buffers in the
1976 * correct order, so we search for the cluster in both directions.
1979 vfs_bio_awrite(struct buf *bp)
1984 daddr_t lblkno = bp->b_lblkno;
1985 struct vnode *vp = bp->b_vp;
1993 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1995 * right now we support clustered writing only to regular files. If
1996 * we find a clusterable block we could be in the middle of a cluster
1997 * rather then at the beginning.
1999 if ((vp->v_type == VREG) &&
2000 (vp->v_mount != 0) && /* Only on nodes that have the size info */
2001 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2003 size = vp->v_mount->mnt_stat.f_iosize;
2004 maxcl = MAXPHYS / size;
2007 for (i = 1; i < maxcl; i++)
2008 if (vfs_bio_clcheck(vp, size, lblkno + i,
2009 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2012 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2013 if (vfs_bio_clcheck(vp, size, lblkno - j,
2014 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2020 * this is a possible cluster write
2024 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2030 bp->b_flags |= B_ASYNC;
2032 * default (old) behavior, writing out only one block
2034 * XXX returns b_bufsize instead of b_bcount for nwritten?
2036 nwritten = bp->b_bufsize;
2043 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
2046 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2047 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
2048 if ((gbflags & GB_UNMAPPED) == 0) {
2049 bp->b_kvabase = (caddr_t)addr;
2050 } else if ((gbflags & GB_KVAALLOC) != 0) {
2051 KASSERT((gbflags & GB_UNMAPPED) != 0,
2052 ("GB_KVAALLOC without GB_UNMAPPED"));
2053 bp->b_kvaalloc = (caddr_t)addr;
2054 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2055 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2057 bp->b_kvasize = maxsize;
2061 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2065 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2072 if (vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr)) {
2074 * Buffer map is too fragmented. Request the caller
2075 * to defragment the map.
2077 atomic_add_int(&bufdefragcnt, 1);
2080 setbufkva(bp, addr, maxsize, gbflags);
2081 atomic_add_long(&bufspace, bp->b_kvasize);
2086 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2087 * locked vnode is supplied.
2090 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2095 int cnt, error, flags, norunbuf, wait;
2097 mtx_assert(&bqclean, MA_OWNED);
2100 flags = VFS_BIO_NEED_BUFSPACE;
2102 } else if (bufspace >= hibufspace) {
2104 flags = VFS_BIO_NEED_BUFSPACE;
2107 flags = VFS_BIO_NEED_ANY;
2109 atomic_set_int(&needsbuffer, flags);
2110 mtx_unlock(&bqclean);
2112 bd_speedup(); /* heeeelp */
2113 if ((gbflags & GB_NOWAIT_BD) != 0)
2120 while ((needsbuffer & flags) != 0) {
2121 if (vp != NULL && vp->v_type != VCHR &&
2122 (td->td_pflags & TDP_BUFNEED) == 0) {
2123 rw_wunlock(&nblock);
2125 * getblk() is called with a vnode locked, and
2126 * some majority of the dirty buffers may as
2127 * well belong to the vnode. Flushing the
2128 * buffers there would make a progress that
2129 * cannot be achieved by the buf_daemon, that
2130 * cannot lock the vnode.
2134 ASSERT_VOP_LOCKED(vp, "bufd_helper");
2135 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
2136 vn_lock(vp, LK_TRYUPGRADE);
2138 /* play bufdaemon */
2139 norunbuf = curthread_pflags_set(TDP_BUFNEED |
2141 VOP_FSYNC(vp, wait, td);
2142 atomic_add_long(¬bufdflushes, 1);
2143 curthread_pflags_restore(norunbuf);
2146 if ((needsbuffer & flags) == 0)
2149 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
2150 (PRIBIO + 4) | slpflag, waitmsg, slptimeo);
2154 rw_wunlock(&nblock);
2158 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2161 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2162 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2163 bp->b_kvasize, bp->b_bufsize, qindex);
2164 mtx_assert(&bqclean, MA_NOTOWNED);
2167 * Note: we no longer distinguish between VMIO and non-VMIO
2170 KASSERT((bp->b_flags & B_DELWRI) == 0,
2171 ("delwri buffer %p found in queue %d", bp, qindex));
2173 if (qindex == QUEUE_CLEAN) {
2174 if (bp->b_flags & B_VMIO) {
2175 bp->b_flags &= ~B_ASYNC;
2176 vfs_vmio_release(bp);
2178 if (bp->b_vp != NULL)
2183 * Get the rest of the buffer freed up. b_kva* is still valid
2184 * after this operation.
2187 if (bp->b_rcred != NOCRED) {
2188 crfree(bp->b_rcred);
2189 bp->b_rcred = NOCRED;
2191 if (bp->b_wcred != NOCRED) {
2192 crfree(bp->b_wcred);
2193 bp->b_wcred = NOCRED;
2195 if (!LIST_EMPTY(&bp->b_dep))
2197 if (bp->b_vflags & BV_BKGRDINPROG)
2198 panic("losing buffer 3");
2199 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2200 bp, bp->b_vp, qindex));
2201 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2202 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2207 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2210 KASSERT((bp->b_flags & B_INFREECNT) == 0,
2211 ("buf %p still counted as free?", bp));
2214 bp->b_blkno = bp->b_lblkno = 0;
2215 bp->b_offset = NOOFFSET;
2221 bp->b_dirtyoff = bp->b_dirtyend = 0;
2222 bp->b_bufobj = NULL;
2223 bp->b_pin_count = 0;
2224 bp->b_fsprivate1 = NULL;
2225 bp->b_fsprivate2 = NULL;
2226 bp->b_fsprivate3 = NULL;
2228 LIST_INIT(&bp->b_dep);
2231 static int flushingbufs;
2234 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2236 struct buf *bp, *nbp;
2237 int nqindex, qindex, pass;
2239 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2243 atomic_add_int(&getnewbufrestarts, 1);
2246 * Setup for scan. If we do not have enough free buffers,
2247 * we setup a degenerate case that immediately fails. Note
2248 * that if we are specially marked process, we are allowed to
2249 * dip into our reserves.
2251 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2252 * for the allocation of the mapped buffer. For unmapped, the
2253 * easiest is to start with EMPTY outright.
2255 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2256 * However, there are a number of cases (defragging, reusing, ...)
2257 * where we cannot backup.
2261 if (!defrag && unmapped) {
2262 nqindex = QUEUE_EMPTY;
2263 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2266 nqindex = QUEUE_EMPTYKVA;
2267 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2271 * If no EMPTYKVA buffers and we are either defragging or
2272 * reusing, locate a CLEAN buffer to free or reuse. If
2273 * bufspace useage is low skip this step so we can allocate a
2276 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2277 nqindex = QUEUE_CLEAN;
2278 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2282 * If we could not find or were not allowed to reuse a CLEAN
2283 * buffer, check to see if it is ok to use an EMPTY buffer.
2284 * We can only use an EMPTY buffer if allocating its KVA would
2285 * not otherwise run us out of buffer space. No KVA is needed
2286 * for the unmapped allocation.
2288 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2290 nqindex = QUEUE_EMPTY;
2291 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2295 * All available buffers might be clean, retry ignoring the
2296 * lobufspace as the last resort.
2298 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2299 nqindex = QUEUE_CLEAN;
2300 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2304 * Run scan, possibly freeing data and/or kva mappings on the fly
2307 while ((bp = nbp) != NULL) {
2311 * Calculate next bp (we can only use it if we do not
2312 * block or do other fancy things).
2314 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2317 nqindex = QUEUE_EMPTYKVA;
2318 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2322 case QUEUE_EMPTYKVA:
2323 nqindex = QUEUE_CLEAN;
2324 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2329 if (metadata && pass == 1) {
2331 nqindex = QUEUE_EMPTY;
2333 &bufqueues[QUEUE_EMPTY]);
2342 * If we are defragging then we need a buffer with
2343 * b_kvasize != 0. XXX this situation should no longer
2344 * occur, if defrag is non-zero the buffer's b_kvasize
2345 * should also be non-zero at this point. XXX
2347 if (defrag && bp->b_kvasize == 0) {
2348 printf("Warning: defrag empty buffer %p\n", bp);
2353 * Start freeing the bp. This is somewhat involved. nbp
2354 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2356 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2359 * BKGRDINPROG can only be set with the buf and bufobj
2360 * locks both held. We tolerate a race to clear it here.
2362 if (bp->b_vflags & BV_BKGRDINPROG) {
2367 KASSERT(bp->b_qindex == qindex,
2368 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2371 mtx_unlock(&bqclean);
2373 * NOTE: nbp is now entirely invalid. We can only restart
2374 * the scan from this point on.
2377 getnewbuf_reuse_bp(bp, qindex);
2378 mtx_assert(&bqclean, MA_NOTOWNED);
2381 * If we are defragging then free the buffer.
2384 bp->b_flags |= B_INVAL;
2392 * Notify any waiters for the buffer lock about
2393 * identity change by freeing the buffer.
2395 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2396 bp->b_flags |= B_INVAL;
2406 * If we are overcomitted then recover the buffer and its
2407 * KVM space. This occurs in rare situations when multiple
2408 * processes are blocked in getnewbuf() or allocbuf().
2410 if (bufspace >= hibufspace)
2412 if (flushingbufs && bp->b_kvasize != 0) {
2413 bp->b_flags |= B_INVAL;
2418 if (bufspace < lobufspace)
2428 * Find and initialize a new buffer header, freeing up existing buffers
2429 * in the bufqueues as necessary. The new buffer is returned locked.
2431 * Important: B_INVAL is not set. If the caller wishes to throw the
2432 * buffer away, the caller must set B_INVAL prior to calling brelse().
2435 * We have insufficient buffer headers
2436 * We have insufficient buffer space
2437 * buffer_arena is too fragmented ( space reservation fails )
2438 * If we have to flush dirty buffers ( but we try to avoid this )
2441 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2445 int defrag, metadata;
2447 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2448 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2449 if (!unmapped_buf_allowed)
2450 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2453 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2459 * We can't afford to block since we might be holding a vnode lock,
2460 * which may prevent system daemons from running. We deal with
2461 * low-memory situations by proactively returning memory and running
2462 * async I/O rather then sync I/O.
2464 atomic_add_int(&getnewbufcalls, 1);
2465 atomic_subtract_int(&getnewbufrestarts, 1);
2467 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2468 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2473 * If we exhausted our list, sleep as appropriate. We may have to
2474 * wakeup various daemons and write out some dirty buffers.
2476 * Generally we are sleeping due to insufficient buffer space.
2479 mtx_assert(&bqclean, MA_OWNED);
2480 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2481 mtx_assert(&bqclean, MA_NOTOWNED);
2482 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2483 mtx_assert(&bqclean, MA_NOTOWNED);
2486 bp->b_flags |= B_UNMAPPED;
2487 bp->b_kvabase = bp->b_data = unmapped_buf;
2488 bp->b_kvasize = maxsize;
2489 atomic_add_long(&bufspace, bp->b_kvasize);
2490 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2491 atomic_add_int(&bufreusecnt, 1);
2493 mtx_assert(&bqclean, MA_NOTOWNED);
2496 * We finally have a valid bp. We aren't quite out of the
2497 * woods, we still have to reserve kva space. In order
2498 * to keep fragmentation sane we only allocate kva in
2501 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2503 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2504 B_KVAALLOC)) == B_UNMAPPED) {
2505 if (allocbufkva(bp, maxsize, gbflags)) {
2507 bp->b_flags |= B_INVAL;
2511 atomic_add_int(&bufreusecnt, 1);
2512 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2513 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2515 * If the reused buffer has KVA allocated,
2516 * reassign b_kvaalloc to b_kvabase.
2518 bp->b_kvabase = bp->b_kvaalloc;
2519 bp->b_flags &= ~B_KVAALLOC;
2520 atomic_subtract_long(&unmapped_bufspace,
2522 atomic_add_int(&bufreusecnt, 1);
2523 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2524 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2527 * The case of reused buffer already have KVA
2528 * mapped, but the request is for unmapped
2529 * buffer with KVA allocated.
2531 bp->b_kvaalloc = bp->b_kvabase;
2532 bp->b_data = bp->b_kvabase = unmapped_buf;
2533 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2534 atomic_add_long(&unmapped_bufspace,
2536 atomic_add_int(&bufreusecnt, 1);
2538 if ((gbflags & GB_UNMAPPED) == 0) {
2539 bp->b_saveaddr = bp->b_kvabase;
2540 bp->b_data = bp->b_saveaddr;
2541 bp->b_flags &= ~B_UNMAPPED;
2542 BUF_CHECK_MAPPED(bp);
2551 * buffer flushing daemon. Buffers are normally flushed by the
2552 * update daemon but if it cannot keep up this process starts to
2553 * take the load in an attempt to prevent getnewbuf() from blocking.
2556 static struct kproc_desc buf_kp = {
2561 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2564 buf_flush(int target)
2568 flushed = flushbufqueues(target, 0);
2571 * Could not find any buffers without rollback
2572 * dependencies, so just write the first one
2573 * in the hopes of eventually making progress.
2575 flushed = flushbufqueues(target, 1);
2586 * This process needs to be suspended prior to shutdown sync.
2588 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2592 * This process is allowed to take the buffer cache to the limit
2594 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2598 mtx_unlock(&bdlock);
2600 kproc_suspend_check(bufdaemonproc);
2601 lodirty = lodirtybuffers;
2602 if (bd_speedupreq) {
2603 lodirty = numdirtybuffers / 2;
2607 * Do the flush. Limit the amount of in-transit I/O we
2608 * allow to build up, otherwise we would completely saturate
2611 while (numdirtybuffers > lodirty) {
2612 if (buf_flush(numdirtybuffers - lodirty) == 0)
2614 kern_yield(PRI_USER);
2618 * Only clear bd_request if we have reached our low water
2619 * mark. The buf_daemon normally waits 1 second and
2620 * then incrementally flushes any dirty buffers that have
2621 * built up, within reason.
2623 * If we were unable to hit our low water mark and couldn't
2624 * find any flushable buffers, we sleep for a short period
2625 * to avoid endless loops on unlockable buffers.
2628 if (numdirtybuffers <= lodirtybuffers) {
2630 * We reached our low water mark, reset the
2631 * request and sleep until we are needed again.
2632 * The sleep is just so the suspend code works.
2636 * Do an extra wakeup in case dirty threshold
2637 * changed via sysctl and the explicit transition
2638 * out of shortfall was missed.
2641 if (runningbufspace <= lorunningspace)
2643 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2646 * We couldn't find any flushable dirty buffers but
2647 * still have too many dirty buffers, we
2648 * have to sleep and try again. (rare)
2650 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2658 * Try to flush a buffer in the dirty queue. We must be careful to
2659 * free up B_INVAL buffers instead of write them, which NFS is
2660 * particularly sensitive to.
2662 static int flushwithdeps = 0;
2663 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2664 0, "Number of buffers flushed with dependecies that require rollbacks");
2667 flushbufqueues(int target, int flushdeps)
2669 struct buf *sentinel;
2679 queue = QUEUE_DIRTY;
2681 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2682 sentinel->b_qindex = QUEUE_SENTINEL;
2684 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2685 mtx_unlock(&bqdirty);
2686 while (flushed != target) {
2689 bp = TAILQ_NEXT(sentinel, b_freelist);
2691 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2692 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2695 mtx_unlock(&bqdirty);
2698 KASSERT(bp->b_qindex != QUEUE_SENTINEL,
2699 ("parallel calls to flushbufqueues() bp %p", bp));
2700 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
2701 mtx_unlock(&bqdirty);
2704 if (bp->b_pin_count > 0) {
2709 * BKGRDINPROG can only be set with the buf and bufobj
2710 * locks both held. We tolerate a race to clear it here.
2712 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2713 (bp->b_flags & B_DELWRI) == 0) {
2717 if (bp->b_flags & B_INVAL) {
2724 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2725 if (flushdeps == 0) {
2733 * We must hold the lock on a vnode before writing
2734 * one of its buffers. Otherwise we may confuse, or
2735 * in the case of a snapshot vnode, deadlock the
2738 * The lock order here is the reverse of the normal
2739 * of vnode followed by buf lock. This is ok because
2740 * the NOWAIT will prevent deadlock.
2743 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2747 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
2749 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2750 bp, bp->b_vp, bp->b_flags);
2752 vn_finished_write(mp);
2754 flushwithdeps += hasdeps;
2756 if (runningbufspace > hirunningspace)
2757 waitrunningbufspace();
2760 vn_finished_write(mp);
2764 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2765 mtx_unlock(&bqdirty);
2766 free(sentinel, M_TEMP);
2771 * Check to see if a block is currently memory resident.
2774 incore(struct bufobj *bo, daddr_t blkno)
2779 bp = gbincore(bo, blkno);
2785 * Returns true if no I/O is needed to access the
2786 * associated VM object. This is like incore except
2787 * it also hunts around in the VM system for the data.
2791 inmem(struct vnode * vp, daddr_t blkno)
2794 vm_offset_t toff, tinc, size;
2798 ASSERT_VOP_LOCKED(vp, "inmem");
2800 if (incore(&vp->v_bufobj, blkno))
2802 if (vp->v_mount == NULL)
2809 if (size > vp->v_mount->mnt_stat.f_iosize)
2810 size = vp->v_mount->mnt_stat.f_iosize;
2811 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2813 VM_OBJECT_RLOCK(obj);
2814 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2815 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2819 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2820 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2821 if (vm_page_is_valid(m,
2822 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2825 VM_OBJECT_RUNLOCK(obj);
2829 VM_OBJECT_RUNLOCK(obj);
2834 * Set the dirty range for a buffer based on the status of the dirty
2835 * bits in the pages comprising the buffer. The range is limited
2836 * to the size of the buffer.
2838 * Tell the VM system that the pages associated with this buffer
2839 * are clean. This is used for delayed writes where the data is
2840 * going to go to disk eventually without additional VM intevention.
2842 * Note that while we only really need to clean through to b_bcount, we
2843 * just go ahead and clean through to b_bufsize.
2846 vfs_clean_pages_dirty_buf(struct buf *bp)
2848 vm_ooffset_t foff, noff, eoff;
2852 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2855 foff = bp->b_offset;
2856 KASSERT(bp->b_offset != NOOFFSET,
2857 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2859 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2860 vfs_drain_busy_pages(bp);
2861 vfs_setdirty_locked_object(bp);
2862 for (i = 0; i < bp->b_npages; i++) {
2863 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2865 if (eoff > bp->b_offset + bp->b_bufsize)
2866 eoff = bp->b_offset + bp->b_bufsize;
2868 vfs_page_set_validclean(bp, foff, m);
2869 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2872 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2876 vfs_setdirty_locked_object(struct buf *bp)
2881 object = bp->b_bufobj->bo_object;
2882 VM_OBJECT_ASSERT_WLOCKED(object);
2885 * We qualify the scan for modified pages on whether the
2886 * object has been flushed yet.
2888 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2889 vm_offset_t boffset;
2890 vm_offset_t eoffset;
2893 * test the pages to see if they have been modified directly
2894 * by users through the VM system.
2896 for (i = 0; i < bp->b_npages; i++)
2897 vm_page_test_dirty(bp->b_pages[i]);
2900 * Calculate the encompassing dirty range, boffset and eoffset,
2901 * (eoffset - boffset) bytes.
2904 for (i = 0; i < bp->b_npages; i++) {
2905 if (bp->b_pages[i]->dirty)
2908 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2910 for (i = bp->b_npages - 1; i >= 0; --i) {
2911 if (bp->b_pages[i]->dirty) {
2915 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2918 * Fit it to the buffer.
2921 if (eoffset > bp->b_bcount)
2922 eoffset = bp->b_bcount;
2925 * If we have a good dirty range, merge with the existing
2929 if (boffset < eoffset) {
2930 if (bp->b_dirtyoff > boffset)
2931 bp->b_dirtyoff = boffset;
2932 if (bp->b_dirtyend < eoffset)
2933 bp->b_dirtyend = eoffset;
2939 * Allocate the KVA mapping for an existing buffer. It handles the
2940 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2941 * KVA which is not mapped (B_KVAALLOC).
2944 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2946 struct buf *scratch_bp;
2947 int bsize, maxsize, need_mapping, need_kva;
2950 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2951 (gbflags & GB_UNMAPPED) == 0;
2952 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2953 (gbflags & GB_KVAALLOC) != 0;
2954 if (!need_mapping && !need_kva)
2957 BUF_CHECK_UNMAPPED(bp);
2959 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2961 * Buffer is not mapped, but the KVA was already
2962 * reserved at the time of the instantiation. Use the
2965 bp->b_flags &= ~B_KVAALLOC;
2966 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2967 bp->b_kvabase = bp->b_kvaalloc;
2968 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2973 * Calculate the amount of the address space we would reserve
2974 * if the buffer was mapped.
2976 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2977 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
2978 offset = blkno * bsize;
2979 maxsize = size + (offset & PAGE_MASK);
2980 maxsize = imax(maxsize, bsize);
2983 if (allocbufkva(bp, maxsize, gbflags)) {
2985 * Request defragmentation. getnewbuf() returns us the
2986 * allocated space by the scratch buffer KVA.
2988 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2989 (GB_UNMAPPED | GB_KVAALLOC));
2990 if (scratch_bp == NULL) {
2991 if ((gbflags & GB_NOWAIT_BD) != 0) {
2993 * XXXKIB: defragmentation cannot
2994 * succeed, not sure what else to do.
2996 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
2998 atomic_add_int(&mappingrestarts, 1);
3001 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
3002 ("scratch bp !B_KVAALLOC %p", scratch_bp));
3003 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
3004 scratch_bp->b_kvasize, gbflags);
3006 /* Get rid of the scratch buffer. */
3007 scratch_bp->b_kvasize = 0;
3008 scratch_bp->b_flags |= B_INVAL;
3009 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
3016 bp->b_saveaddr = bp->b_kvabase;
3017 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
3018 bp->b_flags &= ~B_UNMAPPED;
3019 BUF_CHECK_MAPPED(bp);
3026 * Get a block given a specified block and offset into a file/device.
3027 * The buffers B_DONE bit will be cleared on return, making it almost
3028 * ready for an I/O initiation. B_INVAL may or may not be set on
3029 * return. The caller should clear B_INVAL prior to initiating a
3032 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3033 * an existing buffer.
3035 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3036 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3037 * and then cleared based on the backing VM. If the previous buffer is
3038 * non-0-sized but invalid, B_CACHE will be cleared.
3040 * If getblk() must create a new buffer, the new buffer is returned with
3041 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3042 * case it is returned with B_INVAL clear and B_CACHE set based on the
3045 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3046 * B_CACHE bit is clear.
3048 * What this means, basically, is that the caller should use B_CACHE to
3049 * determine whether the buffer is fully valid or not and should clear
3050 * B_INVAL prior to issuing a read. If the caller intends to validate
3051 * the buffer by loading its data area with something, the caller needs
3052 * to clear B_INVAL. If the caller does this without issuing an I/O,
3053 * the caller should set B_CACHE ( as an optimization ), else the caller
3054 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3055 * a write attempt or if it was a successfull read. If the caller
3056 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3057 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3060 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3065 int bsize, error, maxsize, vmio;
3068 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3069 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3070 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3071 ASSERT_VOP_LOCKED(vp, "getblk");
3072 if (size > MAXBSIZE)
3073 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
3074 if (!unmapped_buf_allowed)
3075 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3080 bp = gbincore(bo, blkno);
3084 * Buffer is in-core. If the buffer is not busy nor managed,
3085 * it must be on a queue.
3087 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3089 if (flags & GB_LOCK_NOWAIT)
3090 lockflags |= LK_NOWAIT;
3092 error = BUF_TIMELOCK(bp, lockflags,
3093 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3096 * If we slept and got the lock we have to restart in case
3097 * the buffer changed identities.
3099 if (error == ENOLCK)
3101 /* We timed out or were interrupted. */
3104 /* If recursed, assume caller knows the rules. */
3105 else if (BUF_LOCKRECURSED(bp))
3109 * The buffer is locked. B_CACHE is cleared if the buffer is
3110 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3111 * and for a VMIO buffer B_CACHE is adjusted according to the
3114 if (bp->b_flags & B_INVAL)
3115 bp->b_flags &= ~B_CACHE;
3116 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3117 bp->b_flags |= B_CACHE;
3118 if (bp->b_flags & B_MANAGED)
3119 MPASS(bp->b_qindex == QUEUE_NONE);
3124 * check for size inconsistencies for non-VMIO case.
3126 if (bp->b_bcount != size) {
3127 if ((bp->b_flags & B_VMIO) == 0 ||
3128 (size > bp->b_kvasize)) {
3129 if (bp->b_flags & B_DELWRI) {
3131 * If buffer is pinned and caller does
3132 * not want sleep waiting for it to be
3133 * unpinned, bail out
3135 if (bp->b_pin_count > 0) {
3136 if (flags & GB_LOCK_NOWAIT) {
3143 bp->b_flags |= B_NOCACHE;
3146 if (LIST_EMPTY(&bp->b_dep)) {
3147 bp->b_flags |= B_RELBUF;
3150 bp->b_flags |= B_NOCACHE;
3159 * Handle the case of unmapped buffer which should
3160 * become mapped, or the buffer for which KVA
3161 * reservation is requested.
3163 bp_unmapped_get_kva(bp, blkno, size, flags);
3166 * If the size is inconsistant in the VMIO case, we can resize
3167 * the buffer. This might lead to B_CACHE getting set or
3168 * cleared. If the size has not changed, B_CACHE remains
3169 * unchanged from its previous state.
3171 if (bp->b_bcount != size)
3174 KASSERT(bp->b_offset != NOOFFSET,
3175 ("getblk: no buffer offset"));
3178 * A buffer with B_DELWRI set and B_CACHE clear must
3179 * be committed before we can return the buffer in
3180 * order to prevent the caller from issuing a read
3181 * ( due to B_CACHE not being set ) and overwriting
3184 * Most callers, including NFS and FFS, need this to
3185 * operate properly either because they assume they
3186 * can issue a read if B_CACHE is not set, or because
3187 * ( for example ) an uncached B_DELWRI might loop due
3188 * to softupdates re-dirtying the buffer. In the latter
3189 * case, B_CACHE is set after the first write completes,
3190 * preventing further loops.
3191 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3192 * above while extending the buffer, we cannot allow the
3193 * buffer to remain with B_CACHE set after the write
3194 * completes or it will represent a corrupt state. To
3195 * deal with this we set B_NOCACHE to scrap the buffer
3198 * We might be able to do something fancy, like setting
3199 * B_CACHE in bwrite() except if B_DELWRI is already set,
3200 * so the below call doesn't set B_CACHE, but that gets real
3201 * confusing. This is much easier.
3204 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3205 bp->b_flags |= B_NOCACHE;
3209 bp->b_flags &= ~B_DONE;
3212 * Buffer is not in-core, create new buffer. The buffer
3213 * returned by getnewbuf() is locked. Note that the returned
3214 * buffer is also considered valid (not marked B_INVAL).
3218 * If the user does not want us to create the buffer, bail out
3221 if (flags & GB_NOCREAT)
3223 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3226 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3227 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3228 offset = blkno * bsize;
3229 vmio = vp->v_object != NULL;
3231 maxsize = size + (offset & PAGE_MASK);
3234 /* Do not allow non-VMIO notmapped buffers. */
3235 flags &= ~GB_UNMAPPED;
3237 maxsize = imax(maxsize, bsize);
3239 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3241 if (slpflag || slptimeo)
3247 * This code is used to make sure that a buffer is not
3248 * created while the getnewbuf routine is blocked.
3249 * This can be a problem whether the vnode is locked or not.
3250 * If the buffer is created out from under us, we have to
3251 * throw away the one we just created.
3253 * Note: this must occur before we associate the buffer
3254 * with the vp especially considering limitations in
3255 * the splay tree implementation when dealing with duplicate
3259 if (gbincore(bo, blkno)) {
3261 bp->b_flags |= B_INVAL;
3267 * Insert the buffer into the hash, so that it can
3268 * be found by incore.
3270 bp->b_blkno = bp->b_lblkno = blkno;
3271 bp->b_offset = offset;
3276 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3277 * buffer size starts out as 0, B_CACHE will be set by
3278 * allocbuf() for the VMIO case prior to it testing the
3279 * backing store for validity.
3283 bp->b_flags |= B_VMIO;
3284 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3285 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3286 bp, vp->v_object, bp->b_bufobj->bo_object));
3288 bp->b_flags &= ~B_VMIO;
3289 KASSERT(bp->b_bufobj->bo_object == NULL,
3290 ("ARGH! has b_bufobj->bo_object %p %p\n",
3291 bp, bp->b_bufobj->bo_object));
3292 BUF_CHECK_MAPPED(bp);
3296 bp->b_flags &= ~B_DONE;
3298 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3299 BUF_ASSERT_HELD(bp);
3301 KASSERT(bp->b_bufobj == bo,
3302 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3307 * Get an empty, disassociated buffer of given size. The buffer is initially
3311 geteblk(int size, int flags)
3316 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3317 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3318 if ((flags & GB_NOWAIT_BD) &&
3319 (curthread->td_pflags & TDP_BUFNEED) != 0)
3323 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3324 BUF_ASSERT_HELD(bp);
3330 * This code constitutes the buffer memory from either anonymous system
3331 * memory (in the case of non-VMIO operations) or from an associated
3332 * VM object (in the case of VMIO operations). This code is able to
3333 * resize a buffer up or down.
3335 * Note that this code is tricky, and has many complications to resolve
3336 * deadlock or inconsistant data situations. Tread lightly!!!
3337 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3338 * the caller. Calling this code willy nilly can result in the loss of data.
3340 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3341 * B_CACHE for the non-VMIO case.
3345 allocbuf(struct buf *bp, int size)
3347 int newbsize, mbsize;
3350 BUF_ASSERT_HELD(bp);
3352 if (bp->b_kvasize < size)
3353 panic("allocbuf: buffer too small");
3355 if ((bp->b_flags & B_VMIO) == 0) {
3359 * Just get anonymous memory from the kernel. Don't
3360 * mess with B_CACHE.
3362 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3363 if (bp->b_flags & B_MALLOC)
3366 newbsize = round_page(size);
3368 if (newbsize < bp->b_bufsize) {
3370 * malloced buffers are not shrunk
3372 if (bp->b_flags & B_MALLOC) {
3374 bp->b_bcount = size;
3376 free(bp->b_data, M_BIOBUF);
3377 if (bp->b_bufsize) {
3378 atomic_subtract_long(
3384 bp->b_saveaddr = bp->b_kvabase;
3385 bp->b_data = bp->b_saveaddr;
3387 bp->b_flags &= ~B_MALLOC;
3391 vm_hold_free_pages(bp, newbsize);
3392 } else if (newbsize > bp->b_bufsize) {
3394 * We only use malloced memory on the first allocation.
3395 * and revert to page-allocated memory when the buffer
3399 * There is a potential smp race here that could lead
3400 * to bufmallocspace slightly passing the max. It
3401 * is probably extremely rare and not worth worrying
3404 if ( (bufmallocspace < maxbufmallocspace) &&
3405 (bp->b_bufsize == 0) &&
3406 (mbsize <= PAGE_SIZE/2)) {
3408 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3409 bp->b_bufsize = mbsize;
3410 bp->b_bcount = size;
3411 bp->b_flags |= B_MALLOC;
3412 atomic_add_long(&bufmallocspace, mbsize);
3418 * If the buffer is growing on its other-than-first allocation,
3419 * then we revert to the page-allocation scheme.
3421 if (bp->b_flags & B_MALLOC) {
3422 origbuf = bp->b_data;
3423 origbufsize = bp->b_bufsize;
3424 bp->b_data = bp->b_kvabase;
3425 if (bp->b_bufsize) {
3426 atomic_subtract_long(&bufmallocspace,
3431 bp->b_flags &= ~B_MALLOC;
3432 newbsize = round_page(newbsize);
3436 (vm_offset_t) bp->b_data + bp->b_bufsize,
3437 (vm_offset_t) bp->b_data + newbsize);
3439 bcopy(origbuf, bp->b_data, origbufsize);
3440 free(origbuf, M_BIOBUF);
3446 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3447 desiredpages = (size == 0) ? 0 :
3448 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3450 if (bp->b_flags & B_MALLOC)
3451 panic("allocbuf: VMIO buffer can't be malloced");
3453 * Set B_CACHE initially if buffer is 0 length or will become
3456 if (size == 0 || bp->b_bufsize == 0)
3457 bp->b_flags |= B_CACHE;
3459 if (newbsize < bp->b_bufsize) {
3461 * DEV_BSIZE aligned new buffer size is less then the
3462 * DEV_BSIZE aligned existing buffer size. Figure out
3463 * if we have to remove any pages.
3465 if (desiredpages < bp->b_npages) {
3468 if ((bp->b_flags & B_UNMAPPED) == 0) {
3469 BUF_CHECK_MAPPED(bp);
3470 pmap_qremove((vm_offset_t)trunc_page(
3471 (vm_offset_t)bp->b_data) +
3472 (desiredpages << PAGE_SHIFT),
3473 (bp->b_npages - desiredpages));
3475 BUF_CHECK_UNMAPPED(bp);
3476 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3477 for (i = desiredpages; i < bp->b_npages; i++) {
3479 * the page is not freed here -- it
3480 * is the responsibility of
3481 * vnode_pager_setsize
3484 KASSERT(m != bogus_page,
3485 ("allocbuf: bogus page found"));
3486 while (vm_page_sleep_if_busy(m,
3490 bp->b_pages[i] = NULL;
3492 vm_page_unwire(m, PQ_INACTIVE);
3495 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3496 bp->b_npages = desiredpages;
3498 } else if (size > bp->b_bcount) {
3500 * We are growing the buffer, possibly in a
3501 * byte-granular fashion.
3508 * Step 1, bring in the VM pages from the object,
3509 * allocating them if necessary. We must clear
3510 * B_CACHE if these pages are not valid for the
3511 * range covered by the buffer.
3514 obj = bp->b_bufobj->bo_object;
3516 VM_OBJECT_WLOCK(obj);
3517 while (bp->b_npages < desiredpages) {
3521 * We must allocate system pages since blocking
3522 * here could interfere with paging I/O, no
3523 * matter which process we are.
3525 * Only exclusive busy can be tested here.
3526 * Blocking on shared busy might lead to
3527 * deadlocks once allocbuf() is called after
3528 * pages are vfs_busy_pages().
3530 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3531 bp->b_npages, VM_ALLOC_NOBUSY |
3532 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3533 VM_ALLOC_IGN_SBUSY |
3534 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3536 bp->b_flags &= ~B_CACHE;
3537 bp->b_pages[bp->b_npages] = m;
3542 * Step 2. We've loaded the pages into the buffer,
3543 * we have to figure out if we can still have B_CACHE
3544 * set. Note that B_CACHE is set according to the
3545 * byte-granular range ( bcount and size ), new the
3546 * aligned range ( newbsize ).
3548 * The VM test is against m->valid, which is DEV_BSIZE
3549 * aligned. Needless to say, the validity of the data
3550 * needs to also be DEV_BSIZE aligned. Note that this
3551 * fails with NFS if the server or some other client
3552 * extends the file's EOF. If our buffer is resized,
3553 * B_CACHE may remain set! XXX
3556 toff = bp->b_bcount;
3557 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3559 while ((bp->b_flags & B_CACHE) && toff < size) {
3562 if (tinc > (size - toff))
3565 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3578 VM_OBJECT_WUNLOCK(obj);
3581 * Step 3, fixup the KVM pmap.
3583 if ((bp->b_flags & B_UNMAPPED) == 0)
3586 BUF_CHECK_UNMAPPED(bp);
3589 if (newbsize < bp->b_bufsize)
3591 bp->b_bufsize = newbsize; /* actual buffer allocation */
3592 bp->b_bcount = size; /* requested buffer size */
3596 extern int inflight_transient_maps;
3599 biodone(struct bio *bp)
3602 void (*done)(struct bio *);
3603 vm_offset_t start, end;
3605 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3606 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3607 bp->bio_flags |= BIO_UNMAPPED;
3608 start = trunc_page((vm_offset_t)bp->bio_data);
3609 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3610 pmap_qremove(start, OFF_TO_IDX(end - start));
3611 vmem_free(transient_arena, start, end - start);
3612 atomic_add_int(&inflight_transient_maps, -1);
3614 done = bp->bio_done;
3616 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3618 bp->bio_flags |= BIO_DONE;
3622 bp->bio_flags |= BIO_DONE;
3628 * Wait for a BIO to finish.
3631 biowait(struct bio *bp, const char *wchan)
3635 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3637 while ((bp->bio_flags & BIO_DONE) == 0)
3638 msleep(bp, mtxp, PRIBIO, wchan, 0);
3640 if (bp->bio_error != 0)
3641 return (bp->bio_error);
3642 if (!(bp->bio_flags & BIO_ERROR))
3648 biofinish(struct bio *bp, struct devstat *stat, int error)
3652 bp->bio_error = error;
3653 bp->bio_flags |= BIO_ERROR;
3656 devstat_end_transaction_bio(stat, bp);
3663 * Wait for buffer I/O completion, returning error status. The buffer
3664 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3665 * error and cleared.
3668 bufwait(struct buf *bp)
3670 if (bp->b_iocmd == BIO_READ)
3671 bwait(bp, PRIBIO, "biord");
3673 bwait(bp, PRIBIO, "biowr");
3674 if (bp->b_flags & B_EINTR) {
3675 bp->b_flags &= ~B_EINTR;
3678 if (bp->b_ioflags & BIO_ERROR) {
3679 return (bp->b_error ? bp->b_error : EIO);
3686 * Call back function from struct bio back up to struct buf.
3689 bufdonebio(struct bio *bip)
3693 bp = bip->bio_caller2;
3694 bp->b_resid = bip->bio_resid;
3695 bp->b_ioflags = bip->bio_flags;
3696 bp->b_error = bip->bio_error;
3698 bp->b_ioflags |= BIO_ERROR;
3704 dev_strategy(struct cdev *dev, struct buf *bp)
3709 KASSERT(dev->si_refcount > 0,
3710 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3711 devtoname(dev), dev));
3713 csw = dev_refthread(dev, &ref);
3714 dev_strategy_csw(dev, csw, bp);
3715 dev_relthread(dev, ref);
3719 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3723 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3725 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3726 dev->si_threadcount > 0,
3727 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3730 bp->b_error = ENXIO;
3731 bp->b_ioflags = BIO_ERROR;
3739 /* Try again later */
3740 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3742 bip->bio_cmd = bp->b_iocmd;
3743 bip->bio_offset = bp->b_iooffset;
3744 bip->bio_length = bp->b_bcount;
3745 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3747 bip->bio_done = bufdonebio;
3748 bip->bio_caller2 = bp;
3750 (*csw->d_strategy)(bip);
3756 * Finish I/O on a buffer, optionally calling a completion function.
3757 * This is usually called from an interrupt so process blocking is
3760 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3761 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3762 * assuming B_INVAL is clear.
3764 * For the VMIO case, we set B_CACHE if the op was a read and no
3765 * read error occured, or if the op was a write. B_CACHE is never
3766 * set if the buffer is invalid or otherwise uncacheable.
3768 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3769 * initiator to leave B_INVAL set to brelse the buffer out of existance
3770 * in the biodone routine.
3773 bufdone(struct buf *bp)
3775 struct bufobj *dropobj;
3776 void (*biodone)(struct buf *);
3778 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3781 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3782 BUF_ASSERT_HELD(bp);
3784 runningbufwakeup(bp);
3785 if (bp->b_iocmd == BIO_WRITE)
3786 dropobj = bp->b_bufobj;
3787 /* call optional completion function if requested */
3788 if (bp->b_iodone != NULL) {
3789 biodone = bp->b_iodone;
3790 bp->b_iodone = NULL;
3793 bufobj_wdrop(dropobj);
3800 bufobj_wdrop(dropobj);
3804 bufdone_finish(struct buf *bp)
3806 BUF_ASSERT_HELD(bp);
3808 if (!LIST_EMPTY(&bp->b_dep))
3811 if (bp->b_flags & B_VMIO) {
3816 int bogus, i, iosize;
3818 obj = bp->b_bufobj->bo_object;
3819 KASSERT(obj->paging_in_progress >= bp->b_npages,
3820 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3821 obj->paging_in_progress, bp->b_npages));
3824 KASSERT(vp->v_holdcnt > 0,
3825 ("biodone_finish: vnode %p has zero hold count", vp));
3826 KASSERT(vp->v_object != NULL,
3827 ("biodone_finish: vnode %p has no vm_object", vp));
3829 foff = bp->b_offset;
3830 KASSERT(bp->b_offset != NOOFFSET,
3831 ("biodone_finish: bp %p has no buffer offset", bp));
3834 * Set B_CACHE if the op was a normal read and no error
3835 * occured. B_CACHE is set for writes in the b*write()
3838 iosize = bp->b_bcount - bp->b_resid;
3839 if (bp->b_iocmd == BIO_READ &&
3840 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3841 !(bp->b_ioflags & BIO_ERROR)) {
3842 bp->b_flags |= B_CACHE;
3845 VM_OBJECT_WLOCK(obj);
3846 for (i = 0; i < bp->b_npages; i++) {
3850 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3855 * cleanup bogus pages, restoring the originals
3858 if (m == bogus_page) {
3859 bogus = bogusflag = 1;
3860 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3862 panic("biodone: page disappeared!");
3865 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3866 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3867 (intmax_t)foff, (uintmax_t)m->pindex));
3870 * In the write case, the valid and clean bits are
3871 * already changed correctly ( see bdwrite() ), so we
3872 * only need to do this here in the read case.
3874 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3875 KASSERT((m->dirty & vm_page_bits(foff &
3876 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3877 " page %p has unexpected dirty bits", m));
3878 vfs_page_set_valid(bp, foff, m);
3882 vm_object_pip_subtract(obj, 1);
3883 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3886 vm_object_pip_wakeupn(obj, 0);
3887 VM_OBJECT_WUNLOCK(obj);
3888 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3889 BUF_CHECK_MAPPED(bp);
3890 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3891 bp->b_pages, bp->b_npages);
3896 * For asynchronous completions, release the buffer now. The brelse
3897 * will do a wakeup there if necessary - so no need to do a wakeup
3898 * here in the async case. The sync case always needs to do a wakeup.
3901 if (bp->b_flags & B_ASYNC) {
3902 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3911 * This routine is called in lieu of iodone in the case of
3912 * incomplete I/O. This keeps the busy status for pages
3916 vfs_unbusy_pages(struct buf *bp)
3922 runningbufwakeup(bp);
3923 if (!(bp->b_flags & B_VMIO))
3926 obj = bp->b_bufobj->bo_object;
3927 VM_OBJECT_WLOCK(obj);
3928 for (i = 0; i < bp->b_npages; i++) {
3930 if (m == bogus_page) {
3931 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3933 panic("vfs_unbusy_pages: page missing\n");
3935 if ((bp->b_flags & B_UNMAPPED) == 0) {
3936 BUF_CHECK_MAPPED(bp);
3937 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3938 bp->b_pages, bp->b_npages);
3940 BUF_CHECK_UNMAPPED(bp);
3942 vm_object_pip_subtract(obj, 1);
3945 vm_object_pip_wakeupn(obj, 0);
3946 VM_OBJECT_WUNLOCK(obj);
3950 * vfs_page_set_valid:
3952 * Set the valid bits in a page based on the supplied offset. The
3953 * range is restricted to the buffer's size.
3955 * This routine is typically called after a read completes.
3958 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3963 * Compute the end offset, eoff, such that [off, eoff) does not span a
3964 * page boundary and eoff is not greater than the end of the buffer.
3965 * The end of the buffer, in this case, is our file EOF, not the
3966 * allocation size of the buffer.
3968 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3969 if (eoff > bp->b_offset + bp->b_bcount)
3970 eoff = bp->b_offset + bp->b_bcount;
3973 * Set valid range. This is typically the entire buffer and thus the
3977 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3981 * vfs_page_set_validclean:
3983 * Set the valid bits and clear the dirty bits in a page based on the
3984 * supplied offset. The range is restricted to the buffer's size.
3987 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3989 vm_ooffset_t soff, eoff;
3992 * Start and end offsets in buffer. eoff - soff may not cross a
3993 * page boundry or cross the end of the buffer. The end of the
3994 * buffer, in this case, is our file EOF, not the allocation size
3998 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3999 if (eoff > bp->b_offset + bp->b_bcount)
4000 eoff = bp->b_offset + bp->b_bcount;
4003 * Set valid range. This is typically the entire buffer and thus the
4007 vm_page_set_validclean(
4009 (vm_offset_t) (soff & PAGE_MASK),
4010 (vm_offset_t) (eoff - soff)
4016 * Ensure that all buffer pages are not exclusive busied. If any page is
4017 * exclusive busy, drain it.
4020 vfs_drain_busy_pages(struct buf *bp)
4025 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4027 for (i = 0; i < bp->b_npages; i++) {
4029 if (vm_page_xbusied(m)) {
4030 for (; last_busied < i; last_busied++)
4031 vm_page_sbusy(bp->b_pages[last_busied]);
4032 while (vm_page_xbusied(m)) {
4034 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4035 vm_page_busy_sleep(m, "vbpage");
4036 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4040 for (i = 0; i < last_busied; i++)
4041 vm_page_sunbusy(bp->b_pages[i]);
4045 * This routine is called before a device strategy routine.
4046 * It is used to tell the VM system that paging I/O is in
4047 * progress, and treat the pages associated with the buffer
4048 * almost as being exclusive busy. Also the object paging_in_progress
4049 * flag is handled to make sure that the object doesn't become
4052 * Since I/O has not been initiated yet, certain buffer flags
4053 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4054 * and should be ignored.
4057 vfs_busy_pages(struct buf *bp, int clear_modify)
4064 if (!(bp->b_flags & B_VMIO))
4067 obj = bp->b_bufobj->bo_object;
4068 foff = bp->b_offset;
4069 KASSERT(bp->b_offset != NOOFFSET,
4070 ("vfs_busy_pages: no buffer offset"));
4071 VM_OBJECT_WLOCK(obj);
4072 vfs_drain_busy_pages(bp);
4073 if (bp->b_bufsize != 0)
4074 vfs_setdirty_locked_object(bp);
4076 for (i = 0; i < bp->b_npages; i++) {
4079 if ((bp->b_flags & B_CLUSTER) == 0) {
4080 vm_object_pip_add(obj, 1);
4084 * When readying a buffer for a read ( i.e
4085 * clear_modify == 0 ), it is important to do
4086 * bogus_page replacement for valid pages in
4087 * partially instantiated buffers. Partially
4088 * instantiated buffers can, in turn, occur when
4089 * reconstituting a buffer from its VM backing store
4090 * base. We only have to do this if B_CACHE is
4091 * clear ( which causes the I/O to occur in the
4092 * first place ). The replacement prevents the read
4093 * I/O from overwriting potentially dirty VM-backed
4094 * pages. XXX bogus page replacement is, uh, bogus.
4095 * It may not work properly with small-block devices.
4096 * We need to find a better way.
4099 pmap_remove_write(m);
4100 vfs_page_set_validclean(bp, foff, m);
4101 } else if (m->valid == VM_PAGE_BITS_ALL &&
4102 (bp->b_flags & B_CACHE) == 0) {
4103 bp->b_pages[i] = bogus_page;
4106 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4108 VM_OBJECT_WUNLOCK(obj);
4109 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4110 BUF_CHECK_MAPPED(bp);
4111 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4112 bp->b_pages, bp->b_npages);
4117 * vfs_bio_set_valid:
4119 * Set the range within the buffer to valid. The range is
4120 * relative to the beginning of the buffer, b_offset. Note that
4121 * b_offset itself may be offset from the beginning of the first
4125 vfs_bio_set_valid(struct buf *bp, int base, int size)
4130 if (!(bp->b_flags & B_VMIO))
4134 * Fixup base to be relative to beginning of first page.
4135 * Set initial n to be the maximum number of bytes in the
4136 * first page that can be validated.
4138 base += (bp->b_offset & PAGE_MASK);
4139 n = PAGE_SIZE - (base & PAGE_MASK);
4141 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4142 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4146 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4151 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4157 * If the specified buffer is a non-VMIO buffer, clear the entire
4158 * buffer. If the specified buffer is a VMIO buffer, clear and
4159 * validate only the previously invalid portions of the buffer.
4160 * This routine essentially fakes an I/O, so we need to clear
4161 * BIO_ERROR and B_INVAL.
4163 * Note that while we only theoretically need to clear through b_bcount,
4164 * we go ahead and clear through b_bufsize.
4167 vfs_bio_clrbuf(struct buf *bp)
4169 int i, j, mask, sa, ea, slide;
4171 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4175 bp->b_flags &= ~B_INVAL;
4176 bp->b_ioflags &= ~BIO_ERROR;
4177 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4178 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4179 (bp->b_offset & PAGE_MASK) == 0) {
4180 if (bp->b_pages[0] == bogus_page)
4182 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4183 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4184 if ((bp->b_pages[0]->valid & mask) == mask)
4186 if ((bp->b_pages[0]->valid & mask) == 0) {
4187 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4188 bp->b_pages[0]->valid |= mask;
4192 sa = bp->b_offset & PAGE_MASK;
4194 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4195 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4196 ea = slide & PAGE_MASK;
4199 if (bp->b_pages[i] == bogus_page)
4202 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4203 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4204 if ((bp->b_pages[i]->valid & mask) == mask)
4206 if ((bp->b_pages[i]->valid & mask) == 0)
4207 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4209 for (; sa < ea; sa += DEV_BSIZE, j++) {
4210 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4211 pmap_zero_page_area(bp->b_pages[i],
4216 bp->b_pages[i]->valid |= mask;
4219 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4224 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4229 if ((bp->b_flags & B_UNMAPPED) == 0) {
4230 BUF_CHECK_MAPPED(bp);
4231 bzero(bp->b_data + base, size);
4233 BUF_CHECK_UNMAPPED(bp);
4234 n = PAGE_SIZE - (base & PAGE_MASK);
4235 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4239 pmap_zero_page_area(m, base & PAGE_MASK, n);
4248 * vm_hold_load_pages and vm_hold_free_pages get pages into
4249 * a buffers address space. The pages are anonymous and are
4250 * not associated with a file object.
4253 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4259 BUF_CHECK_MAPPED(bp);
4261 to = round_page(to);
4262 from = round_page(from);
4263 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4265 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4268 * note: must allocate system pages since blocking here
4269 * could interfere with paging I/O, no matter which
4272 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4273 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4278 pmap_qenter(pg, &p, 1);
4279 bp->b_pages[index] = p;
4281 bp->b_npages = index;
4284 /* Return pages associated with this buf to the vm system */
4286 vm_hold_free_pages(struct buf *bp, int newbsize)
4290 int index, newnpages;
4292 BUF_CHECK_MAPPED(bp);
4294 from = round_page((vm_offset_t)bp->b_data + newbsize);
4295 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4296 if (bp->b_npages > newnpages)
4297 pmap_qremove(from, bp->b_npages - newnpages);
4298 for (index = newnpages; index < bp->b_npages; index++) {
4299 p = bp->b_pages[index];
4300 bp->b_pages[index] = NULL;
4301 if (vm_page_sbusied(p))
4302 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4303 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4306 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
4308 bp->b_npages = newnpages;
4312 * Map an IO request into kernel virtual address space.
4314 * All requests are (re)mapped into kernel VA space.
4315 * Notice that we use b_bufsize for the size of the buffer
4316 * to be mapped. b_bcount might be modified by the driver.
4318 * Note that even if the caller determines that the address space should
4319 * be valid, a race or a smaller-file mapped into a larger space may
4320 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4321 * check the return value.
4324 vmapbuf(struct buf *bp, int mapbuf)
4330 if (bp->b_bufsize < 0)
4332 prot = VM_PROT_READ;
4333 if (bp->b_iocmd == BIO_READ)
4334 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4335 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4336 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4337 btoc(MAXPHYS))) < 0)
4339 bp->b_npages = pidx;
4340 if (mapbuf || !unmapped_buf_allowed) {
4341 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4342 kva = bp->b_saveaddr;
4343 bp->b_saveaddr = bp->b_data;
4344 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4345 bp->b_flags &= ~B_UNMAPPED;
4347 bp->b_flags |= B_UNMAPPED;
4348 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4349 bp->b_saveaddr = bp->b_data;
4350 bp->b_data = unmapped_buf;
4356 * Free the io map PTEs associated with this IO operation.
4357 * We also invalidate the TLB entries and restore the original b_addr.
4360 vunmapbuf(struct buf *bp)
4364 npages = bp->b_npages;
4365 if (bp->b_flags & B_UNMAPPED)
4366 bp->b_flags &= ~B_UNMAPPED;
4368 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4369 vm_page_unhold_pages(bp->b_pages, npages);
4371 bp->b_data = bp->b_saveaddr;
4375 bdone(struct buf *bp)
4379 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4381 bp->b_flags |= B_DONE;
4387 bwait(struct buf *bp, u_char pri, const char *wchan)
4391 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4393 while ((bp->b_flags & B_DONE) == 0)
4394 msleep(bp, mtxp, pri, wchan, 0);
4399 bufsync(struct bufobj *bo, int waitfor)
4402 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4406 bufstrategy(struct bufobj *bo, struct buf *bp)
4412 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4413 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4414 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4415 i = VOP_STRATEGY(vp, bp);
4416 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4420 bufobj_wrefl(struct bufobj *bo)
4423 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4424 ASSERT_BO_WLOCKED(bo);
4429 bufobj_wref(struct bufobj *bo)
4432 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4439 bufobj_wdrop(struct bufobj *bo)
4442 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4444 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4445 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4446 bo->bo_flag &= ~BO_WWAIT;
4447 wakeup(&bo->bo_numoutput);
4453 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4457 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4458 ASSERT_BO_WLOCKED(bo);
4460 while (bo->bo_numoutput) {
4461 bo->bo_flag |= BO_WWAIT;
4462 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4463 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4471 bpin(struct buf *bp)
4475 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4482 bunpin(struct buf *bp)
4486 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4488 if (--bp->b_pin_count == 0)
4494 bunpin_wait(struct buf *bp)
4498 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4500 while (bp->b_pin_count > 0)
4501 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4506 * Set bio_data or bio_ma for struct bio from the struct buf.
4509 bdata2bio(struct buf *bp, struct bio *bip)
4512 if ((bp->b_flags & B_UNMAPPED) != 0) {
4513 KASSERT(unmapped_buf_allowed, ("unmapped"));
4514 bip->bio_ma = bp->b_pages;
4515 bip->bio_ma_n = bp->b_npages;
4516 bip->bio_data = unmapped_buf;
4517 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4518 bip->bio_flags |= BIO_UNMAPPED;
4519 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4520 PAGE_SIZE == bp->b_npages,
4521 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4522 (long long)bip->bio_length, bip->bio_ma_n));
4524 bip->bio_data = bp->b_data;
4529 #include "opt_ddb.h"
4531 #include <ddb/ddb.h>
4533 /* DDB command to show buffer data */
4534 DB_SHOW_COMMAND(buffer, db_show_buffer)
4537 struct buf *bp = (struct buf *)addr;
4540 db_printf("usage: show buffer <addr>\n");
4544 db_printf("buf at %p\n", bp);
4545 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4546 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4547 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4549 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4550 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4552 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4553 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4554 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4557 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4558 for (i = 0; i < bp->b_npages; i++) {
4561 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4562 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4563 if ((i + 1) < bp->b_npages)
4569 BUF_LOCKPRINTINFO(bp);
4572 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4577 for (i = 0; i < nbuf; i++) {
4579 if (BUF_ISLOCKED(bp)) {
4580 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4586 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4592 db_printf("usage: show vnodebufs <addr>\n");
4595 vp = (struct vnode *)addr;
4596 db_printf("Clean buffers:\n");
4597 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4598 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4601 db_printf("Dirty buffers:\n");
4602 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4603 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4608 DB_COMMAND(countfreebufs, db_coundfreebufs)
4611 int i, used = 0, nfree = 0;
4614 db_printf("usage: countfreebufs\n");
4618 for (i = 0; i < nbuf; i++) {
4620 if ((bp->b_flags & B_INFREECNT) != 0)
4626 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4628 db_printf("numfreebuffers is %d\n", numfreebuffers);