2 * Copyright (c) 2004 Poul-Henning Kamp
3 * Copyright (c) 1994,1997 John S. Dyson
4 * Copyright (c) 2013 The FreeBSD Foundation
7 * Portions of this software were developed by Konstantin Belousov
8 * under sponsorship from the FreeBSD Foundation.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * this file contains a new buffer I/O scheme implementing a coherent
34 * VM object and buffer cache scheme. Pains have been taken to make
35 * sure that the performance degradation associated with schemes such
36 * as this is not realized.
38 * Author: John S. Dyson
39 * Significant help during the development and debugging phases
40 * had been provided by David Greenman, also of the FreeBSD core team.
42 * see man buf(9) for more info.
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
49 #include <sys/systm.h>
53 #include <sys/devicestat.h>
54 #include <sys/eventhandler.h>
56 #include <sys/limits.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mutex.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
64 #include <sys/resourcevar.h>
65 #include <sys/rwlock.h>
66 #include <sys/sysctl.h>
68 #include <sys/vmmeter.h>
69 #include <sys/vnode.h>
70 #include <geom/geom.h>
72 #include <vm/vm_param.h>
73 #include <vm/vm_kern.h>
74 #include <vm/vm_pageout.h>
75 #include <vm/vm_page.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_map.h>
79 #include "opt_compat.h"
80 #include "opt_directio.h"
83 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
85 struct bio_ops bioops; /* I/O operation notification */
87 struct buf_ops buf_ops_bio = {
88 .bop_name = "buf_ops_bio",
89 .bop_write = bufwrite,
90 .bop_strategy = bufstrategy,
92 .bop_bdflush = bufbdflush,
96 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has
97 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c.
99 struct buf *buf; /* buffer header pool */
100 caddr_t unmapped_buf;
102 static struct proc *bufdaemonproc;
104 static int inmem(struct vnode *vp, daddr_t blkno);
105 static void vm_hold_free_pages(struct buf *bp, int newbsize);
106 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
108 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
109 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
111 static void vfs_clean_pages_dirty_buf(struct buf *bp);
112 static void vfs_setdirty_locked_object(struct buf *bp);
113 static void vfs_vmio_release(struct buf *bp);
114 static int vfs_bio_clcheck(struct vnode *vp, int size,
115 daddr_t lblkno, daddr_t blkno);
116 static int buf_flush(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 mtx_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 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));
386 extern void ffs_rawread_setup(void);
387 #endif /* DIRECTIO */
392 * Return the appropriate queue lock based on the index.
394 static inline struct mtx *
398 if (qindex == QUEUE_DIRTY)
399 return (struct mtx *)(&bqdirty);
400 return (struct mtx *)(&bqclean);
406 * Wakeup any bwillwrite() waiters.
411 mtx_lock(&bdirtylock);
416 mtx_unlock(&bdirtylock);
422 * Decrement the numdirtybuffers count by one and wakeup any
423 * threads blocked in bwillwrite().
429 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
430 (lodirtybuffers + hidirtybuffers) / 2)
437 * Increment the numdirtybuffers count by one and wakeup the buf
445 * Only do the wakeup once as we cross the boundary. The
446 * buf daemon will keep running until the condition clears.
448 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
449 (lodirtybuffers + hidirtybuffers) / 2)
456 * Called when buffer space is potentially available for recovery.
457 * getnewbuf() will block on this flag when it is unable to free
458 * sufficient buffer space. Buffer space becomes recoverable when
459 * bp's get placed back in the queues.
467 * If someone is waiting for BUF space, wake them up. Even
468 * though we haven't freed the kva space yet, the waiting
469 * process will be able to now.
472 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
473 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
474 wakeup(&needsbuffer);
482 * Wake up processes that are waiting on asynchronous writes to fall
483 * below lorunningspace.
489 mtx_lock(&rbreqlock);
492 wakeup(&runningbufreq);
494 mtx_unlock(&rbreqlock);
500 * Decrement the outstanding write count according.
503 runningbufwakeup(struct buf *bp)
507 bspace = bp->b_runningbufspace;
510 space = atomic_fetchadd_long(&runningbufspace, -bspace);
511 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
513 bp->b_runningbufspace = 0;
515 * Only acquire the lock and wakeup on the transition from exceeding
516 * the threshold to falling below it.
518 if (space < lorunningspace)
520 if (space - bspace > lorunningspace)
528 * Called when a buffer has been added to one of the free queues to
529 * account for the buffer and to wakeup anyone waiting for free buffers.
530 * This typically occurs when large amounts of metadata are being handled
531 * by the buffer cache ( else buffer space runs out first, usually ).
534 bufcountadd(struct buf *bp)
538 KASSERT((bp->b_flags & B_INFREECNT) == 0,
539 ("buf %p already counted as free", bp));
540 bp->b_flags |= B_INFREECNT;
541 old = atomic_fetchadd_int(&numfreebuffers, 1);
542 KASSERT(old >= 0 && old < nbuf,
543 ("numfreebuffers climbed to %d", old + 1));
546 needsbuffer &= ~VFS_BIO_NEED_ANY;
547 if (numfreebuffers >= hifreebuffers)
548 needsbuffer &= ~VFS_BIO_NEED_FREE;
549 wakeup(&needsbuffer);
557 * Decrement the numfreebuffers count as needed.
560 bufcountsub(struct buf *bp)
565 * Fixup numfreebuffers count. If the buffer is invalid or not
566 * delayed-write, the buffer was free and we must decrement
569 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
570 KASSERT((bp->b_flags & B_INFREECNT) != 0,
571 ("buf %p not counted in numfreebuffers", bp));
572 bp->b_flags &= ~B_INFREECNT;
573 old = atomic_fetchadd_int(&numfreebuffers, -1);
574 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
579 * waitrunningbufspace()
581 * runningbufspace is a measure of the amount of I/O currently
582 * running. This routine is used in async-write situations to
583 * prevent creating huge backups of pending writes to a device.
584 * Only asynchronous writes are governed by this function.
586 * This does NOT turn an async write into a sync write. It waits
587 * for earlier writes to complete and generally returns before the
588 * caller's write has reached the device.
591 waitrunningbufspace(void)
594 mtx_lock(&rbreqlock);
595 while (runningbufspace > hirunningspace) {
597 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
599 mtx_unlock(&rbreqlock);
604 * vfs_buf_test_cache:
606 * Called when a buffer is extended. This function clears the B_CACHE
607 * bit if the newly extended portion of the buffer does not contain
612 vfs_buf_test_cache(struct buf *bp,
613 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
617 VM_OBJECT_ASSERT_LOCKED(m->object);
618 if (bp->b_flags & B_CACHE) {
619 int base = (foff + off) & PAGE_MASK;
620 if (vm_page_is_valid(m, base, size) == 0)
621 bp->b_flags &= ~B_CACHE;
625 /* Wake up the buffer daemon if necessary */
631 if (bd_request == 0) {
639 * bd_speedup - speedup the buffer cache flushing code
648 if (bd_speedupreq == 0 || bd_request == 0)
658 #define TRANSIENT_DENOM 5
660 #define TRANSIENT_DENOM 10
664 * Calculating buffer cache scaling values and reserve space for buffer
665 * headers. This is called during low level kernel initialization and
666 * may be called more then once. We CANNOT write to the memory area
667 * being reserved at this time.
670 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
673 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
676 * physmem_est is in pages. Convert it to kilobytes (assumes
677 * PAGE_SIZE is >= 1K)
679 physmem_est = physmem_est * (PAGE_SIZE / 1024);
682 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
683 * For the first 64MB of ram nominally allocate sufficient buffers to
684 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
685 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
686 * the buffer cache we limit the eventual kva reservation to
689 * factor represents the 1/4 x ram conversion.
692 int factor = 4 * BKVASIZE / 1024;
695 if (physmem_est > 4096)
696 nbuf += min((physmem_est - 4096) / factor,
698 if (physmem_est > 65536)
699 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
700 32 * 1024 * 1024 / (factor * 5));
702 if (maxbcache && nbuf > maxbcache / BKVASIZE)
703 nbuf = maxbcache / BKVASIZE;
708 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
709 maxbuf = (LONG_MAX / 3) / BKVASIZE;
712 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
718 * Ideal allocation size for the transient bio submap is 10%
719 * of the maximal space buffer map. This roughly corresponds
720 * to the amount of the buffer mapped for typical UFS load.
722 * Clip the buffer map to reserve space for the transient
723 * BIOs, if its extent is bigger than 90% (80% on i386) of the
724 * maximum buffer map extent on the platform.
726 * The fall-back to the maxbuf in case of maxbcache unset,
727 * allows to not trim the buffer KVA for the architectures
728 * with ample KVA space.
730 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
731 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
732 buf_sz = (long)nbuf * BKVASIZE;
733 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
734 (TRANSIENT_DENOM - 1)) {
736 * There is more KVA than memory. Do not
737 * adjust buffer map size, and assign the rest
738 * of maxbuf to transient map.
740 biotmap_sz = maxbuf_sz - buf_sz;
743 * Buffer map spans all KVA we could afford on
744 * this platform. Give 10% (20% on i386) of
745 * the buffer map to the transient bio map.
747 biotmap_sz = buf_sz / TRANSIENT_DENOM;
748 buf_sz -= biotmap_sz;
750 if (biotmap_sz / INT_MAX > MAXPHYS)
751 bio_transient_maxcnt = INT_MAX;
753 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
755 * Artifically limit to 1024 simultaneous in-flight I/Os
756 * using the transient mapping.
758 if (bio_transient_maxcnt > 1024)
759 bio_transient_maxcnt = 1024;
761 nbuf = buf_sz / BKVASIZE;
765 * swbufs are used as temporary holders for I/O, such as paging I/O.
766 * We have no less then 16 and no more then 256.
768 nswbuf = max(min(nbuf/4, 256), 16);
770 if (nswbuf < NSWBUF_MIN)
778 * Reserve space for the buffer cache buffers
781 v = (caddr_t)(swbuf + nswbuf);
783 v = (caddr_t)(buf + nbuf);
788 /* Initialize the buffer subsystem. Called before use of any buffers. */
795 mtx_init(&bqclean, "bufq clean lock", NULL, MTX_DEF);
796 mtx_init(&bqdirty, "bufq dirty lock", NULL, MTX_DEF);
797 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
798 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF);
799 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
800 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
802 /* next, make a null set of free lists */
803 for (i = 0; i < BUFFER_QUEUES; i++)
804 TAILQ_INIT(&bufqueues[i]);
806 /* finally, initialize each buffer header and stick on empty q */
807 for (i = 0; i < nbuf; i++) {
809 bzero(bp, sizeof *bp);
810 bp->b_flags = B_INVAL | B_INFREECNT;
811 bp->b_rcred = NOCRED;
812 bp->b_wcred = NOCRED;
813 bp->b_qindex = QUEUE_EMPTY;
815 LIST_INIT(&bp->b_dep);
817 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
819 bq_len[QUEUE_EMPTY]++;
824 * maxbufspace is the absolute maximum amount of buffer space we are
825 * allowed to reserve in KVM and in real terms. The absolute maximum
826 * is nominally used by buf_daemon. hibufspace is the nominal maximum
827 * used by most other processes. The differential is required to
828 * ensure that buf_daemon is able to run when other processes might
829 * be blocked waiting for buffer space.
831 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
832 * this may result in KVM fragmentation which is not handled optimally
835 maxbufspace = (long)nbuf * BKVASIZE;
836 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
837 lobufspace = hibufspace - MAXBSIZE;
840 * Note: The 16 MiB upper limit for hirunningspace was chosen
841 * arbitrarily and may need further tuning. It corresponds to
842 * 128 outstanding write IO requests (if IO size is 128 KiB),
843 * which fits with many RAID controllers' tagged queuing limits.
844 * The lower 1 MiB limit is the historical upper limit for
847 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBSIZE),
848 16 * 1024 * 1024), 1024 * 1024);
849 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBSIZE);
852 * Limit the amount of malloc memory since it is wired permanently into
853 * the kernel space. Even though this is accounted for in the buffer
854 * allocation, we don't want the malloced region to grow uncontrolled.
855 * The malloc scheme improves memory utilization significantly on average
856 * (small) directories.
858 maxbufmallocspace = hibufspace / 20;
861 * Reduce the chance of a deadlock occuring by limiting the number
862 * of delayed-write dirty buffers we allow to stack up.
864 hidirtybuffers = nbuf / 4 + 20;
865 dirtybufthresh = hidirtybuffers * 9 / 10;
868 * To support extreme low-memory systems, make sure hidirtybuffers cannot
869 * eat up all available buffer space. This occurs when our minimum cannot
870 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
871 * BKVASIZE'd buffers.
873 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
874 hidirtybuffers >>= 1;
876 lodirtybuffers = hidirtybuffers / 2;
879 * Try to keep the number of free buffers in the specified range,
880 * and give special processes (e.g. like buf_daemon) access to an
883 lofreebuffers = nbuf / 18 + 5;
884 hifreebuffers = 2 * lofreebuffers;
885 numfreebuffers = nbuf;
887 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
888 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
889 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
894 vfs_buf_check_mapped(struct buf *bp)
897 KASSERT((bp->b_flags & B_UNMAPPED) == 0,
898 ("mapped buf %p %x", bp, bp->b_flags));
899 KASSERT(bp->b_kvabase != unmapped_buf,
900 ("mapped buf: b_kvabase was not updated %p", bp));
901 KASSERT(bp->b_data != unmapped_buf,
902 ("mapped buf: b_data was not updated %p", bp));
906 vfs_buf_check_unmapped(struct buf *bp)
909 KASSERT((bp->b_flags & B_UNMAPPED) == B_UNMAPPED,
910 ("unmapped buf %p %x", bp, bp->b_flags));
911 KASSERT(bp->b_kvabase == unmapped_buf,
912 ("unmapped buf: corrupted b_kvabase %p", bp));
913 KASSERT(bp->b_data == unmapped_buf,
914 ("unmapped buf: corrupted b_data %p", bp));
917 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
918 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
920 #define BUF_CHECK_MAPPED(bp) do {} while (0)
921 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
925 bpmap_qenter(struct buf *bp)
928 BUF_CHECK_MAPPED(bp);
931 * bp->b_data is relative to bp->b_offset, but
932 * bp->b_offset may be offset into the first page.
934 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
935 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
936 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
937 (vm_offset_t)(bp->b_offset & PAGE_MASK));
941 * bfreekva() - free the kva allocation for a buffer.
943 * Since this call frees up buffer space, we call bufspacewakeup().
946 bfreekva(struct buf *bp)
949 if (bp->b_kvasize == 0)
952 atomic_add_int(&buffreekvacnt, 1);
953 atomic_subtract_long(&bufspace, bp->b_kvasize);
954 if ((bp->b_flags & B_UNMAPPED) == 0) {
955 BUF_CHECK_MAPPED(bp);
956 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase,
959 BUF_CHECK_UNMAPPED(bp);
960 if ((bp->b_flags & B_KVAALLOC) != 0) {
961 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvaalloc,
964 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
965 bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
974 * Insert the buffer into the appropriate free list.
977 binsfree(struct buf *bp, int qindex)
979 struct mtx *olock, *nlock;
981 BUF_ASSERT_XLOCKED(bp);
983 olock = bqlock(bp->b_qindex);
984 nlock = bqlock(qindex);
986 /* Handle delayed bremfree() processing. */
987 if (bp->b_flags & B_REMFREE)
990 if (bp->b_qindex != QUEUE_NONE)
991 panic("binsfree: free buffer onto another queue???");
993 bp->b_qindex = qindex;
994 if (olock != nlock) {
998 if (bp->b_flags & B_AGE)
999 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1001 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1003 bq_len[bp->b_qindex]++;
1008 * Something we can maybe free or reuse.
1010 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1013 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1020 * Mark the buffer for removal from the appropriate free list.
1024 bremfree(struct buf *bp)
1027 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1028 KASSERT((bp->b_flags & B_REMFREE) == 0,
1029 ("bremfree: buffer %p already marked for delayed removal.", bp));
1030 KASSERT(bp->b_qindex != QUEUE_NONE,
1031 ("bremfree: buffer %p not on a queue.", bp));
1032 BUF_ASSERT_XLOCKED(bp);
1034 bp->b_flags |= B_REMFREE;
1041 * Force an immediate removal from a free list. Used only in nfs when
1042 * it abuses the b_freelist pointer.
1045 bremfreef(struct buf *bp)
1049 qlock = bqlock(bp->b_qindex);
1058 * Removes a buffer from the free list, must be called with the
1059 * correct qlock held.
1062 bremfreel(struct buf *bp)
1065 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1066 bp, bp->b_vp, bp->b_flags);
1067 KASSERT(bp->b_qindex != QUEUE_NONE,
1068 ("bremfreel: buffer %p not on a queue.", bp));
1069 BUF_ASSERT_XLOCKED(bp);
1070 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1072 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1074 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1076 bq_len[bp->b_qindex]--;
1078 bp->b_qindex = QUEUE_NONE;
1080 * If this was a delayed bremfree() we only need to remove the buffer
1081 * from the queue and return the stats are already done.
1083 if (bp->b_flags & B_REMFREE) {
1084 bp->b_flags &= ~B_REMFREE;
1091 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1092 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1093 * the buffer is valid and we do not have to do anything.
1096 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1097 int cnt, struct ucred * cred)
1102 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1103 if (inmem(vp, *rablkno))
1105 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1107 if ((rabp->b_flags & B_CACHE) == 0) {
1108 if (!TD_IS_IDLETHREAD(curthread))
1109 curthread->td_ru.ru_inblock++;
1110 rabp->b_flags |= B_ASYNC;
1111 rabp->b_flags &= ~B_INVAL;
1112 rabp->b_ioflags &= ~BIO_ERROR;
1113 rabp->b_iocmd = BIO_READ;
1114 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1115 rabp->b_rcred = crhold(cred);
1116 vfs_busy_pages(rabp, 0);
1118 rabp->b_iooffset = dbtob(rabp->b_blkno);
1127 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1129 * Get a buffer with the specified data. Look in the cache first. We
1130 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1131 * is set, the buffer is valid and we do not have to do anything, see
1132 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1135 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1136 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1139 int rv = 0, readwait = 0;
1141 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1143 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1145 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1149 /* if not found in cache, do some I/O */
1150 if ((bp->b_flags & B_CACHE) == 0) {
1151 if (!TD_IS_IDLETHREAD(curthread))
1152 curthread->td_ru.ru_inblock++;
1153 bp->b_iocmd = BIO_READ;
1154 bp->b_flags &= ~B_INVAL;
1155 bp->b_ioflags &= ~BIO_ERROR;
1156 if (bp->b_rcred == NOCRED && cred != NOCRED)
1157 bp->b_rcred = crhold(cred);
1158 vfs_busy_pages(bp, 0);
1159 bp->b_iooffset = dbtob(bp->b_blkno);
1164 breada(vp, rablkno, rabsize, cnt, cred);
1173 * Write, release buffer on completion. (Done by iodone
1174 * if async). Do not bother writing anything if the buffer
1177 * Note that we set B_CACHE here, indicating that buffer is
1178 * fully valid and thus cacheable. This is true even of NFS
1179 * now so we set it generally. This could be set either here
1180 * or in biodone() since the I/O is synchronous. We put it
1184 bufwrite(struct buf *bp)
1191 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1192 if (bp->b_flags & B_INVAL) {
1197 if (bp->b_flags & B_BARRIER)
1200 oldflags = bp->b_flags;
1202 BUF_ASSERT_HELD(bp);
1204 if (bp->b_pin_count > 0)
1207 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1208 ("FFS background buffer should not get here %p", bp));
1212 vp_md = vp->v_vflag & VV_MD;
1217 * Mark the buffer clean. Increment the bufobj write count
1218 * before bundirty() call, to prevent other thread from seeing
1219 * empty dirty list and zero counter for writes in progress,
1220 * falsely indicating that the bufobj is clean.
1222 bufobj_wref(bp->b_bufobj);
1225 bp->b_flags &= ~B_DONE;
1226 bp->b_ioflags &= ~BIO_ERROR;
1227 bp->b_flags |= B_CACHE;
1228 bp->b_iocmd = BIO_WRITE;
1230 vfs_busy_pages(bp, 1);
1233 * Normal bwrites pipeline writes
1235 bp->b_runningbufspace = bp->b_bufsize;
1236 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1238 if (!TD_IS_IDLETHREAD(curthread))
1239 curthread->td_ru.ru_oublock++;
1240 if (oldflags & B_ASYNC)
1242 bp->b_iooffset = dbtob(bp->b_blkno);
1245 if ((oldflags & B_ASYNC) == 0) {
1246 int rtval = bufwait(bp);
1249 } else if (space > hirunningspace) {
1251 * don't allow the async write to saturate the I/O
1252 * system. We will not deadlock here because
1253 * we are blocking waiting for I/O that is already in-progress
1254 * to complete. We do not block here if it is the update
1255 * or syncer daemon trying to clean up as that can lead
1258 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1259 waitrunningbufspace();
1266 bufbdflush(struct bufobj *bo, struct buf *bp)
1270 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1271 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1273 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1276 * Try to find a buffer to flush.
1278 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1279 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1281 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1284 panic("bdwrite: found ourselves");
1286 /* Don't countdeps with the bo lock held. */
1287 if (buf_countdeps(nbp, 0)) {
1292 if (nbp->b_flags & B_CLUSTEROK) {
1293 vfs_bio_awrite(nbp);
1298 dirtybufferflushes++;
1307 * Delayed write. (Buffer is marked dirty). Do not bother writing
1308 * anything if the buffer is marked invalid.
1310 * Note that since the buffer must be completely valid, we can safely
1311 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1312 * biodone() in order to prevent getblk from writing the buffer
1313 * out synchronously.
1316 bdwrite(struct buf *bp)
1318 struct thread *td = curthread;
1322 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1323 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1324 KASSERT((bp->b_flags & B_BARRIER) == 0,
1325 ("Barrier request in delayed write %p", bp));
1326 BUF_ASSERT_HELD(bp);
1328 if (bp->b_flags & B_INVAL) {
1334 * If we have too many dirty buffers, don't create any more.
1335 * If we are wildly over our limit, then force a complete
1336 * cleanup. Otherwise, just keep the situation from getting
1337 * out of control. Note that we have to avoid a recursive
1338 * disaster and not try to clean up after our own cleanup!
1342 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1343 td->td_pflags |= TDP_INBDFLUSH;
1345 td->td_pflags &= ~TDP_INBDFLUSH;
1351 * Set B_CACHE, indicating that the buffer is fully valid. This is
1352 * true even of NFS now.
1354 bp->b_flags |= B_CACHE;
1357 * This bmap keeps the system from needing to do the bmap later,
1358 * perhaps when the system is attempting to do a sync. Since it
1359 * is likely that the indirect block -- or whatever other datastructure
1360 * that the filesystem needs is still in memory now, it is a good
1361 * thing to do this. Note also, that if the pageout daemon is
1362 * requesting a sync -- there might not be enough memory to do
1363 * the bmap then... So, this is important to do.
1365 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1366 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1370 * Set the *dirty* buffer range based upon the VM system dirty
1373 * Mark the buffer pages as clean. We need to do this here to
1374 * satisfy the vnode_pager and the pageout daemon, so that it
1375 * thinks that the pages have been "cleaned". Note that since
1376 * the pages are in a delayed write buffer -- the VFS layer
1377 * "will" see that the pages get written out on the next sync,
1378 * or perhaps the cluster will be completed.
1380 vfs_clean_pages_dirty_buf(bp);
1384 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1385 * due to the softdep code.
1392 * Turn buffer into delayed write request. We must clear BIO_READ and
1393 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1394 * itself to properly update it in the dirty/clean lists. We mark it
1395 * B_DONE to ensure that any asynchronization of the buffer properly
1396 * clears B_DONE ( else a panic will occur later ).
1398 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1399 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1400 * should only be called if the buffer is known-good.
1402 * Since the buffer is not on a queue, we do not update the numfreebuffers
1405 * The buffer must be on QUEUE_NONE.
1408 bdirty(struct buf *bp)
1411 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1412 bp, bp->b_vp, bp->b_flags);
1413 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1414 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1415 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1416 BUF_ASSERT_HELD(bp);
1417 bp->b_flags &= ~(B_RELBUF);
1418 bp->b_iocmd = BIO_WRITE;
1420 if ((bp->b_flags & B_DELWRI) == 0) {
1421 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1430 * Clear B_DELWRI for buffer.
1432 * Since the buffer is not on a queue, we do not update the numfreebuffers
1435 * The buffer must be on QUEUE_NONE.
1439 bundirty(struct buf *bp)
1442 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1443 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1444 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1445 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1446 BUF_ASSERT_HELD(bp);
1448 if (bp->b_flags & B_DELWRI) {
1449 bp->b_flags &= ~B_DELWRI;
1454 * Since it is now being written, we can clear its deferred write flag.
1456 bp->b_flags &= ~B_DEFERRED;
1462 * Asynchronous write. Start output on a buffer, but do not wait for
1463 * it to complete. The buffer is released when the output completes.
1465 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1466 * B_INVAL buffers. Not us.
1469 bawrite(struct buf *bp)
1472 bp->b_flags |= B_ASYNC;
1479 * Asynchronous barrier write. Start output on a buffer, but do not
1480 * wait for it to complete. Place a write barrier after this write so
1481 * that this buffer and all buffers written before it are committed to
1482 * the disk before any buffers written after this write are committed
1483 * to the disk. The buffer is released when the output completes.
1486 babarrierwrite(struct buf *bp)
1489 bp->b_flags |= B_ASYNC | B_BARRIER;
1496 * Synchronous barrier write. Start output on a buffer and wait for
1497 * it to complete. Place a write barrier after this write so that
1498 * this buffer and all buffers written before it are committed to
1499 * the disk before any buffers written after this write are committed
1500 * to the disk. The buffer is released when the output completes.
1503 bbarrierwrite(struct buf *bp)
1506 bp->b_flags |= B_BARRIER;
1507 return (bwrite(bp));
1513 * Called prior to the locking of any vnodes when we are expecting to
1514 * write. We do not want to starve the buffer cache with too many
1515 * dirty buffers so we block here. By blocking prior to the locking
1516 * of any vnodes we attempt to avoid the situation where a locked vnode
1517 * prevents the various system daemons from flushing related buffers.
1523 if (numdirtybuffers >= hidirtybuffers) {
1524 mtx_lock(&bdirtylock);
1525 while (numdirtybuffers >= hidirtybuffers) {
1527 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
1530 mtx_unlock(&bdirtylock);
1535 * Return true if we have too many dirty buffers.
1538 buf_dirty_count_severe(void)
1541 return(numdirtybuffers >= hidirtybuffers);
1544 static __noinline int
1545 buf_vm_page_count_severe(void)
1548 KFAIL_POINT_CODE(DEBUG_FP, buf_pressure, return 1);
1550 return vm_page_count_severe();
1556 * Release a busy buffer and, if requested, free its resources. The
1557 * buffer will be stashed in the appropriate bufqueue[] allowing it
1558 * to be accessed later as a cache entity or reused for other purposes.
1561 brelse(struct buf *bp)
1565 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1566 bp, bp->b_vp, bp->b_flags);
1567 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1568 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1570 if (BUF_LOCKRECURSED(bp)) {
1572 * Do not process, in particular, do not handle the
1573 * B_INVAL/B_RELBUF and do not release to free list.
1579 if (bp->b_flags & B_MANAGED) {
1584 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1585 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1587 * Failed write, redirty. Must clear BIO_ERROR to prevent
1588 * pages from being scrapped. If the error is anything
1589 * other than an I/O error (EIO), assume that retrying
1592 bp->b_ioflags &= ~BIO_ERROR;
1594 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1595 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1597 * Either a failed I/O or we were asked to free or not
1600 bp->b_flags |= B_INVAL;
1601 if (!LIST_EMPTY(&bp->b_dep))
1603 if (bp->b_flags & B_DELWRI)
1605 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1606 if ((bp->b_flags & B_VMIO) == 0) {
1615 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1616 * is called with B_DELWRI set, the underlying pages may wind up
1617 * getting freed causing a previous write (bdwrite()) to get 'lost'
1618 * because pages associated with a B_DELWRI bp are marked clean.
1620 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1621 * if B_DELWRI is set.
1623 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1624 * on pages to return pages to the VM page queues.
1626 if (bp->b_flags & B_DELWRI)
1627 bp->b_flags &= ~B_RELBUF;
1628 else if (buf_vm_page_count_severe()) {
1630 * BKGRDINPROG can only be set with the buf and bufobj
1631 * locks both held. We tolerate a race to clear it here.
1633 if (!(bp->b_vflags & BV_BKGRDINPROG))
1634 bp->b_flags |= B_RELBUF;
1638 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1639 * constituted, not even NFS buffers now. Two flags effect this. If
1640 * B_INVAL, the struct buf is invalidated but the VM object is kept
1641 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1643 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1644 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1645 * buffer is also B_INVAL because it hits the re-dirtying code above.
1647 * Normally we can do this whether a buffer is B_DELWRI or not. If
1648 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1649 * the commit state and we cannot afford to lose the buffer. If the
1650 * buffer has a background write in progress, we need to keep it
1651 * around to prevent it from being reconstituted and starting a second
1654 if ((bp->b_flags & B_VMIO)
1655 && !(bp->b_vp->v_mount != NULL &&
1656 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1657 !vn_isdisk(bp->b_vp, NULL) &&
1658 (bp->b_flags & B_DELWRI))
1667 obj = bp->b_bufobj->bo_object;
1670 * Get the base offset and length of the buffer. Note that
1671 * in the VMIO case if the buffer block size is not
1672 * page-aligned then b_data pointer may not be page-aligned.
1673 * But our b_pages[] array *IS* page aligned.
1675 * block sizes less then DEV_BSIZE (usually 512) are not
1676 * supported due to the page granularity bits (m->valid,
1677 * m->dirty, etc...).
1679 * See man buf(9) for more information
1681 resid = bp->b_bufsize;
1682 foff = bp->b_offset;
1683 for (i = 0; i < bp->b_npages; i++) {
1689 * If we hit a bogus page, fixup *all* the bogus pages
1692 if (m == bogus_page) {
1693 poff = OFF_TO_IDX(bp->b_offset);
1696 VM_OBJECT_RLOCK(obj);
1697 for (j = i; j < bp->b_npages; j++) {
1699 mtmp = bp->b_pages[j];
1700 if (mtmp == bogus_page) {
1701 mtmp = vm_page_lookup(obj, poff + j);
1703 panic("brelse: page missing\n");
1705 bp->b_pages[j] = mtmp;
1708 VM_OBJECT_RUNLOCK(obj);
1710 if ((bp->b_flags & (B_INVAL | B_UNMAPPED)) == 0) {
1711 BUF_CHECK_MAPPED(bp);
1713 trunc_page((vm_offset_t)bp->b_data),
1714 bp->b_pages, bp->b_npages);
1718 if ((bp->b_flags & B_NOCACHE) ||
1719 (bp->b_ioflags & BIO_ERROR &&
1720 bp->b_iocmd == BIO_READ)) {
1721 int poffset = foff & PAGE_MASK;
1722 int presid = resid > (PAGE_SIZE - poffset) ?
1723 (PAGE_SIZE - poffset) : resid;
1725 KASSERT(presid >= 0, ("brelse: extra page"));
1726 VM_OBJECT_WLOCK(obj);
1727 while (vm_page_xbusied(m)) {
1729 VM_OBJECT_WUNLOCK(obj);
1730 vm_page_busy_sleep(m, "mbncsh");
1731 VM_OBJECT_WLOCK(obj);
1733 if (pmap_page_wired_mappings(m) == 0)
1734 vm_page_set_invalid(m, poffset, presid);
1735 VM_OBJECT_WUNLOCK(obj);
1737 printf("avoided corruption bug in bogus_page/brelse code\n");
1739 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1740 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1742 if (bp->b_flags & (B_INVAL | B_RELBUF))
1743 vfs_vmio_release(bp);
1745 } else if (bp->b_flags & B_VMIO) {
1747 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1748 vfs_vmio_release(bp);
1751 } else if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0) {
1752 if (bp->b_bufsize != 0)
1754 if (bp->b_vp != NULL)
1759 * If the buffer has junk contents signal it and eventually
1760 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1763 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1764 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1765 bp->b_flags |= B_INVAL;
1766 if (bp->b_flags & B_INVAL) {
1767 if (bp->b_flags & B_DELWRI)
1773 /* buffers with no memory */
1774 if (bp->b_bufsize == 0) {
1775 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1776 if (bp->b_vflags & BV_BKGRDINPROG)
1777 panic("losing buffer 1");
1779 qindex = QUEUE_EMPTYKVA;
1781 qindex = QUEUE_EMPTY;
1782 bp->b_flags |= B_AGE;
1783 /* buffers with junk contents */
1784 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1785 (bp->b_ioflags & BIO_ERROR)) {
1786 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1787 if (bp->b_vflags & BV_BKGRDINPROG)
1788 panic("losing buffer 2");
1789 qindex = QUEUE_CLEAN;
1790 bp->b_flags |= B_AGE;
1791 /* remaining buffers */
1792 } else if (bp->b_flags & B_DELWRI)
1793 qindex = QUEUE_DIRTY;
1795 qindex = QUEUE_CLEAN;
1797 binsfree(bp, qindex);
1799 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1800 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1801 panic("brelse: not dirty");
1807 * Release a buffer back to the appropriate queue but do not try to free
1808 * it. The buffer is expected to be used again soon.
1810 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1811 * biodone() to requeue an async I/O on completion. It is also used when
1812 * known good buffers need to be requeued but we think we may need the data
1815 * XXX we should be able to leave the B_RELBUF hint set on completion.
1818 bqrelse(struct buf *bp)
1822 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1823 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1824 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1826 if (BUF_LOCKRECURSED(bp)) {
1827 /* do not release to free list */
1831 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1833 if (bp->b_flags & B_MANAGED) {
1834 if (bp->b_flags & B_REMFREE)
1839 /* buffers with stale but valid contents */
1840 if (bp->b_flags & B_DELWRI) {
1841 qindex = QUEUE_DIRTY;
1843 if ((bp->b_flags & B_DELWRI) == 0 &&
1844 (bp->b_xflags & BX_VNDIRTY))
1845 panic("bqrelse: not dirty");
1847 * BKGRDINPROG can only be set with the buf and bufobj
1848 * locks both held. We tolerate a race to clear it here.
1850 if (buf_vm_page_count_severe() &&
1851 (bp->b_vflags & BV_BKGRDINPROG) == 0) {
1853 * We are too low on memory, we have to try to free
1854 * the buffer (most importantly: the wired pages
1855 * making up its backing store) *now*.
1860 qindex = QUEUE_CLEAN;
1862 binsfree(bp, qindex);
1869 /* Give pages used by the bp back to the VM system (where possible) */
1871 vfs_vmio_release(struct buf *bp)
1876 if ((bp->b_flags & B_UNMAPPED) == 0) {
1877 BUF_CHECK_MAPPED(bp);
1878 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
1880 BUF_CHECK_UNMAPPED(bp);
1881 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
1882 for (i = 0; i < bp->b_npages; i++) {
1884 bp->b_pages[i] = NULL;
1886 * In order to keep page LRU ordering consistent, put
1887 * everything on the inactive queue.
1890 vm_page_unwire(m, 0);
1893 * Might as well free the page if we can and it has
1894 * no valid data. We also free the page if the
1895 * buffer was used for direct I/O
1897 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid) {
1898 if (m->wire_count == 0 && !vm_page_busied(m))
1900 } else if (bp->b_flags & B_DIRECT)
1901 vm_page_try_to_free(m);
1902 else if (buf_vm_page_count_severe())
1903 vm_page_try_to_cache(m);
1906 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
1908 if (bp->b_bufsize) {
1913 bp->b_flags &= ~B_VMIO;
1919 * Check to see if a block at a particular lbn is available for a clustered
1923 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
1930 /* If the buf isn't in core skip it */
1931 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
1934 /* If the buf is busy we don't want to wait for it */
1935 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1938 /* Only cluster with valid clusterable delayed write buffers */
1939 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
1940 (B_DELWRI | B_CLUSTEROK))
1943 if (bpa->b_bufsize != size)
1947 * Check to see if it is in the expected place on disk and that the
1948 * block has been mapped.
1950 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
1960 * Implement clustered async writes for clearing out B_DELWRI buffers.
1961 * This is much better then the old way of writing only one buffer at
1962 * a time. Note that we may not be presented with the buffers in the
1963 * correct order, so we search for the cluster in both directions.
1966 vfs_bio_awrite(struct buf *bp)
1971 daddr_t lblkno = bp->b_lblkno;
1972 struct vnode *vp = bp->b_vp;
1980 gbflags = (bp->b_flags & B_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
1982 * right now we support clustered writing only to regular files. If
1983 * we find a clusterable block we could be in the middle of a cluster
1984 * rather then at the beginning.
1986 if ((vp->v_type == VREG) &&
1987 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1988 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1990 size = vp->v_mount->mnt_stat.f_iosize;
1991 maxcl = MAXPHYS / size;
1994 for (i = 1; i < maxcl; i++)
1995 if (vfs_bio_clcheck(vp, size, lblkno + i,
1996 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
1999 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2000 if (vfs_bio_clcheck(vp, size, lblkno - j,
2001 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2007 * this is a possible cluster write
2011 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2017 bp->b_flags |= B_ASYNC;
2019 * default (old) behavior, writing out only one block
2021 * XXX returns b_bufsize instead of b_bcount for nwritten?
2023 nwritten = bp->b_bufsize;
2030 setbufkva(struct buf *bp, vm_offset_t addr, int maxsize, int gbflags)
2033 KASSERT((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2034 bp->b_kvasize == 0, ("call bfreekva(%p)", bp));
2035 if ((gbflags & GB_UNMAPPED) == 0) {
2036 bp->b_kvabase = (caddr_t)addr;
2037 } else if ((gbflags & GB_KVAALLOC) != 0) {
2038 KASSERT((gbflags & GB_UNMAPPED) != 0,
2039 ("GB_KVAALLOC without GB_UNMAPPED"));
2040 bp->b_kvaalloc = (caddr_t)addr;
2041 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2042 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2044 bp->b_kvasize = maxsize;
2048 * Allocate the buffer KVA and set b_kvasize. Also set b_kvabase if
2052 allocbufkva(struct buf *bp, int maxsize, int gbflags)
2059 if (vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr)) {
2061 * Buffer map is too fragmented. Request the caller
2062 * to defragment the map.
2064 atomic_add_int(&bufdefragcnt, 1);
2067 setbufkva(bp, addr, maxsize, gbflags);
2068 atomic_add_long(&bufspace, bp->b_kvasize);
2073 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2074 * locked vnode is supplied.
2077 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2082 int cnt, error, flags, norunbuf, wait;
2084 mtx_assert(&bqclean, MA_OWNED);
2087 flags = VFS_BIO_NEED_BUFSPACE;
2089 } else if (bufspace >= hibufspace) {
2091 flags = VFS_BIO_NEED_BUFSPACE;
2094 flags = VFS_BIO_NEED_ANY;
2097 needsbuffer |= flags;
2098 mtx_unlock(&nblock);
2099 mtx_unlock(&bqclean);
2101 bd_speedup(); /* heeeelp */
2102 if ((gbflags & GB_NOWAIT_BD) != 0)
2109 while (needsbuffer & flags) {
2110 if (vp != NULL && vp->v_type != VCHR &&
2111 (td->td_pflags & TDP_BUFNEED) == 0) {
2112 mtx_unlock(&nblock);
2115 * getblk() is called with a vnode locked, and
2116 * some majority of the dirty buffers may as
2117 * well belong to the vnode. Flushing the
2118 * buffers there would make a progress that
2119 * cannot be achieved by the buf_daemon, that
2120 * cannot lock the vnode.
2124 ASSERT_VOP_LOCKED(vp, "bufd_helper");
2125 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
2126 vn_lock(vp, LK_TRYUPGRADE);
2128 /* play bufdaemon */
2129 norunbuf = curthread_pflags_set(TDP_BUFNEED |
2131 VOP_FSYNC(vp, wait, td);
2132 atomic_add_long(¬bufdflushes, 1);
2133 curthread_pflags_restore(norunbuf);
2136 if ((needsbuffer & flags) == 0)
2139 if (msleep(&needsbuffer, &nblock, (PRIBIO + 4) | slpflag,
2143 mtx_unlock(&nblock);
2147 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2150 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2151 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2152 bp->b_kvasize, bp->b_bufsize, qindex);
2153 mtx_assert(&bqclean, MA_NOTOWNED);
2156 * Note: we no longer distinguish between VMIO and non-VMIO
2159 KASSERT((bp->b_flags & B_DELWRI) == 0,
2160 ("delwri buffer %p found in queue %d", bp, qindex));
2162 if (qindex == QUEUE_CLEAN) {
2163 if (bp->b_flags & B_VMIO) {
2164 bp->b_flags &= ~B_ASYNC;
2165 vfs_vmio_release(bp);
2167 if (bp->b_vp != NULL)
2172 * Get the rest of the buffer freed up. b_kva* is still valid
2173 * after this operation.
2176 if (bp->b_rcred != NOCRED) {
2177 crfree(bp->b_rcred);
2178 bp->b_rcred = NOCRED;
2180 if (bp->b_wcred != NOCRED) {
2181 crfree(bp->b_wcred);
2182 bp->b_wcred = NOCRED;
2184 if (!LIST_EMPTY(&bp->b_dep))
2186 if (bp->b_vflags & BV_BKGRDINPROG)
2187 panic("losing buffer 3");
2188 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2189 bp, bp->b_vp, qindex));
2190 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2191 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2196 bp->b_flags &= B_UNMAPPED | B_KVAALLOC;
2199 KASSERT((bp->b_flags & B_INFREECNT) == 0,
2200 ("buf %p still counted as free?", bp));
2203 bp->b_blkno = bp->b_lblkno = 0;
2204 bp->b_offset = NOOFFSET;
2210 bp->b_dirtyoff = bp->b_dirtyend = 0;
2211 bp->b_bufobj = NULL;
2212 bp->b_pin_count = 0;
2213 bp->b_fsprivate1 = NULL;
2214 bp->b_fsprivate2 = NULL;
2215 bp->b_fsprivate3 = NULL;
2217 LIST_INIT(&bp->b_dep);
2220 static int flushingbufs;
2223 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2225 struct buf *bp, *nbp;
2226 int nqindex, qindex, pass;
2228 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2232 atomic_add_int(&getnewbufrestarts, 1);
2235 * Setup for scan. If we do not have enough free buffers,
2236 * we setup a degenerate case that immediately fails. Note
2237 * that if we are specially marked process, we are allowed to
2238 * dip into our reserves.
2240 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
2241 * for the allocation of the mapped buffer. For unmapped, the
2242 * easiest is to start with EMPTY outright.
2244 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
2245 * However, there are a number of cases (defragging, reusing, ...)
2246 * where we cannot backup.
2250 if (!defrag && unmapped) {
2251 nqindex = QUEUE_EMPTY;
2252 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2255 nqindex = QUEUE_EMPTYKVA;
2256 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2260 * If no EMPTYKVA buffers and we are either defragging or
2261 * reusing, locate a CLEAN buffer to free or reuse. If
2262 * bufspace useage is low skip this step so we can allocate a
2265 if (nbp == NULL && (defrag || bufspace >= lobufspace)) {
2266 nqindex = QUEUE_CLEAN;
2267 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2271 * If we could not find or were not allowed to reuse a CLEAN
2272 * buffer, check to see if it is ok to use an EMPTY buffer.
2273 * We can only use an EMPTY buffer if allocating its KVA would
2274 * not otherwise run us out of buffer space. No KVA is needed
2275 * for the unmapped allocation.
2277 if (nbp == NULL && defrag == 0 && (bufspace + maxsize < hibufspace ||
2279 nqindex = QUEUE_EMPTY;
2280 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
2284 * All available buffers might be clean, retry ignoring the
2285 * lobufspace as the last resort.
2287 if (nbp == NULL && !TAILQ_EMPTY(&bufqueues[QUEUE_CLEAN])) {
2288 nqindex = QUEUE_CLEAN;
2289 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2293 * Run scan, possibly freeing data and/or kva mappings on the fly
2296 while ((bp = nbp) != NULL) {
2300 * Calculate next bp (we can only use it if we do not
2301 * block or do other fancy things).
2303 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2306 nqindex = QUEUE_EMPTYKVA;
2307 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
2311 case QUEUE_EMPTYKVA:
2312 nqindex = QUEUE_CLEAN;
2313 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2318 if (metadata && pass == 1) {
2320 nqindex = QUEUE_EMPTY;
2322 &bufqueues[QUEUE_EMPTY]);
2331 * If we are defragging then we need a buffer with
2332 * b_kvasize != 0. XXX this situation should no longer
2333 * occur, if defrag is non-zero the buffer's b_kvasize
2334 * should also be non-zero at this point. XXX
2336 if (defrag && bp->b_kvasize == 0) {
2337 printf("Warning: defrag empty buffer %p\n", bp);
2342 * Start freeing the bp. This is somewhat involved. nbp
2343 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2345 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2348 * BKGRDINPROG can only be set with the buf and bufobj
2349 * locks both held. We tolerate a race to clear it here.
2351 if (bp->b_vflags & BV_BKGRDINPROG) {
2356 KASSERT(bp->b_qindex == qindex,
2357 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2360 mtx_unlock(&bqclean);
2362 * NOTE: nbp is now entirely invalid. We can only restart
2363 * the scan from this point on.
2366 getnewbuf_reuse_bp(bp, qindex);
2367 mtx_assert(&bqclean, MA_NOTOWNED);
2370 * If we are defragging then free the buffer.
2373 bp->b_flags |= B_INVAL;
2381 * Notify any waiters for the buffer lock about
2382 * identity change by freeing the buffer.
2384 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2385 bp->b_flags |= B_INVAL;
2395 * If we are overcomitted then recover the buffer and its
2396 * KVM space. This occurs in rare situations when multiple
2397 * processes are blocked in getnewbuf() or allocbuf().
2399 if (bufspace >= hibufspace)
2401 if (flushingbufs && bp->b_kvasize != 0) {
2402 bp->b_flags |= B_INVAL;
2407 if (bufspace < lobufspace)
2417 * Find and initialize a new buffer header, freeing up existing buffers
2418 * in the bufqueues as necessary. The new buffer is returned locked.
2420 * Important: B_INVAL is not set. If the caller wishes to throw the
2421 * buffer away, the caller must set B_INVAL prior to calling brelse().
2424 * We have insufficient buffer headers
2425 * We have insufficient buffer space
2426 * buffer_arena is too fragmented ( space reservation fails )
2427 * If we have to flush dirty buffers ( but we try to avoid this )
2430 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2434 int defrag, metadata;
2436 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2437 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2438 if (!unmapped_buf_allowed)
2439 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2442 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2448 * We can't afford to block since we might be holding a vnode lock,
2449 * which may prevent system daemons from running. We deal with
2450 * low-memory situations by proactively returning memory and running
2451 * async I/O rather then sync I/O.
2453 atomic_add_int(&getnewbufcalls, 1);
2454 atomic_subtract_int(&getnewbufrestarts, 1);
2456 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2457 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2462 * If we exhausted our list, sleep as appropriate. We may have to
2463 * wakeup various daemons and write out some dirty buffers.
2465 * Generally we are sleeping due to insufficient buffer space.
2468 mtx_assert(&bqclean, MA_OWNED);
2469 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2470 mtx_assert(&bqclean, MA_NOTOWNED);
2471 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2472 mtx_assert(&bqclean, MA_NOTOWNED);
2475 bp->b_flags |= B_UNMAPPED;
2476 bp->b_kvabase = bp->b_data = unmapped_buf;
2477 bp->b_kvasize = maxsize;
2478 atomic_add_long(&bufspace, bp->b_kvasize);
2479 atomic_add_long(&unmapped_bufspace, bp->b_kvasize);
2480 atomic_add_int(&bufreusecnt, 1);
2482 mtx_assert(&bqclean, MA_NOTOWNED);
2485 * We finally have a valid bp. We aren't quite out of the
2486 * woods, we still have to reserve kva space. In order
2487 * to keep fragmentation sane we only allocate kva in
2490 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2492 if (maxsize != bp->b_kvasize || (bp->b_flags & (B_UNMAPPED |
2493 B_KVAALLOC)) == B_UNMAPPED) {
2494 if (allocbufkva(bp, maxsize, gbflags)) {
2496 bp->b_flags |= B_INVAL;
2500 atomic_add_int(&bufreusecnt, 1);
2501 } else if ((bp->b_flags & B_KVAALLOC) != 0 &&
2502 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == 0) {
2504 * If the reused buffer has KVA allocated,
2505 * reassign b_kvaalloc to b_kvabase.
2507 bp->b_kvabase = bp->b_kvaalloc;
2508 bp->b_flags &= ~B_KVAALLOC;
2509 atomic_subtract_long(&unmapped_bufspace,
2511 atomic_add_int(&bufreusecnt, 1);
2512 } else if ((bp->b_flags & (B_UNMAPPED | B_KVAALLOC)) == 0 &&
2513 (gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == (GB_UNMAPPED |
2516 * The case of reused buffer already have KVA
2517 * mapped, but the request is for unmapped
2518 * buffer with KVA allocated.
2520 bp->b_kvaalloc = bp->b_kvabase;
2521 bp->b_data = bp->b_kvabase = unmapped_buf;
2522 bp->b_flags |= B_UNMAPPED | B_KVAALLOC;
2523 atomic_add_long(&unmapped_bufspace,
2525 atomic_add_int(&bufreusecnt, 1);
2527 if ((gbflags & GB_UNMAPPED) == 0) {
2528 bp->b_saveaddr = bp->b_kvabase;
2529 bp->b_data = bp->b_saveaddr;
2530 bp->b_flags &= ~B_UNMAPPED;
2531 BUF_CHECK_MAPPED(bp);
2540 * buffer flushing daemon. Buffers are normally flushed by the
2541 * update daemon but if it cannot keep up this process starts to
2542 * take the load in an attempt to prevent getnewbuf() from blocking.
2545 static struct kproc_desc buf_kp = {
2550 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2553 buf_flush(int target)
2557 flushed = flushbufqueues(target, 0);
2560 * Could not find any buffers without rollback
2561 * dependencies, so just write the first one
2562 * in the hopes of eventually making progress.
2564 flushed = flushbufqueues(target, 1);
2575 * This process needs to be suspended prior to shutdown sync.
2577 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2581 * This process is allowed to take the buffer cache to the limit
2583 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2587 mtx_unlock(&bdlock);
2589 kproc_suspend_check(bufdaemonproc);
2590 lodirty = lodirtybuffers;
2591 if (bd_speedupreq) {
2592 lodirty = numdirtybuffers / 2;
2596 * Do the flush. Limit the amount of in-transit I/O we
2597 * allow to build up, otherwise we would completely saturate
2600 while (numdirtybuffers > lodirty) {
2601 if (buf_flush(numdirtybuffers - lodirty) == 0)
2603 kern_yield(PRI_USER);
2607 * Only clear bd_request if we have reached our low water
2608 * mark. The buf_daemon normally waits 1 second and
2609 * then incrementally flushes any dirty buffers that have
2610 * built up, within reason.
2612 * If we were unable to hit our low water mark and couldn't
2613 * find any flushable buffers, we sleep for a short period
2614 * to avoid endless loops on unlockable buffers.
2617 if (numdirtybuffers <= lodirtybuffers) {
2619 * We reached our low water mark, reset the
2620 * request and sleep until we are needed again.
2621 * The sleep is just so the suspend code works.
2625 * Do an extra wakeup in case dirty threshold
2626 * changed via sysctl and the explicit transition
2627 * out of shortfall was missed.
2630 if (runningbufspace <= lorunningspace)
2632 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2635 * We couldn't find any flushable dirty buffers but
2636 * still have too many dirty buffers, we
2637 * have to sleep and try again. (rare)
2639 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2647 * Try to flush a buffer in the dirty queue. We must be careful to
2648 * free up B_INVAL buffers instead of write them, which NFS is
2649 * particularly sensitive to.
2651 static int flushwithdeps = 0;
2652 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2653 0, "Number of buffers flushed with dependecies that require rollbacks");
2656 flushbufqueues(int target, int flushdeps)
2658 struct buf *sentinel;
2668 queue = QUEUE_DIRTY;
2670 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2671 sentinel->b_qindex = QUEUE_SENTINEL;
2673 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2674 mtx_unlock(&bqdirty);
2675 while (flushed != target) {
2678 bp = TAILQ_NEXT(sentinel, b_freelist);
2680 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2681 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2684 mtx_unlock(&bqdirty);
2687 KASSERT(bp->b_qindex != QUEUE_SENTINEL,
2688 ("parallel calls to flushbufqueues() bp %p", bp));
2689 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
2690 mtx_unlock(&bqdirty);
2693 if (bp->b_pin_count > 0) {
2698 * BKGRDINPROG can only be set with the buf and bufobj
2699 * locks both held. We tolerate a race to clear it here.
2701 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2702 (bp->b_flags & B_DELWRI) == 0) {
2706 if (bp->b_flags & B_INVAL) {
2713 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2714 if (flushdeps == 0) {
2722 * We must hold the lock on a vnode before writing
2723 * one of its buffers. Otherwise we may confuse, or
2724 * in the case of a snapshot vnode, deadlock the
2727 * The lock order here is the reverse of the normal
2728 * of vnode followed by buf lock. This is ok because
2729 * the NOWAIT will prevent deadlock.
2732 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2736 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
2738 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2739 bp, bp->b_vp, bp->b_flags);
2741 vn_finished_write(mp);
2743 flushwithdeps += hasdeps;
2745 if (runningbufspace > hirunningspace)
2746 waitrunningbufspace();
2749 vn_finished_write(mp);
2753 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2754 mtx_unlock(&bqdirty);
2755 free(sentinel, M_TEMP);
2760 * Check to see if a block is currently memory resident.
2763 incore(struct bufobj *bo, daddr_t blkno)
2768 bp = gbincore(bo, blkno);
2774 * Returns true if no I/O is needed to access the
2775 * associated VM object. This is like incore except
2776 * it also hunts around in the VM system for the data.
2780 inmem(struct vnode * vp, daddr_t blkno)
2783 vm_offset_t toff, tinc, size;
2787 ASSERT_VOP_LOCKED(vp, "inmem");
2789 if (incore(&vp->v_bufobj, blkno))
2791 if (vp->v_mount == NULL)
2798 if (size > vp->v_mount->mnt_stat.f_iosize)
2799 size = vp->v_mount->mnt_stat.f_iosize;
2800 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2802 VM_OBJECT_RLOCK(obj);
2803 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2804 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2808 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2809 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2810 if (vm_page_is_valid(m,
2811 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2814 VM_OBJECT_RUNLOCK(obj);
2818 VM_OBJECT_RUNLOCK(obj);
2823 * Set the dirty range for a buffer based on the status of the dirty
2824 * bits in the pages comprising the buffer. The range is limited
2825 * to the size of the buffer.
2827 * Tell the VM system that the pages associated with this buffer
2828 * are clean. This is used for delayed writes where the data is
2829 * going to go to disk eventually without additional VM intevention.
2831 * Note that while we only really need to clean through to b_bcount, we
2832 * just go ahead and clean through to b_bufsize.
2835 vfs_clean_pages_dirty_buf(struct buf *bp)
2837 vm_ooffset_t foff, noff, eoff;
2841 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
2844 foff = bp->b_offset;
2845 KASSERT(bp->b_offset != NOOFFSET,
2846 ("vfs_clean_pages_dirty_buf: no buffer offset"));
2848 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
2849 vfs_drain_busy_pages(bp);
2850 vfs_setdirty_locked_object(bp);
2851 for (i = 0; i < bp->b_npages; i++) {
2852 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2854 if (eoff > bp->b_offset + bp->b_bufsize)
2855 eoff = bp->b_offset + bp->b_bufsize;
2857 vfs_page_set_validclean(bp, foff, m);
2858 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2861 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
2865 vfs_setdirty_locked_object(struct buf *bp)
2870 object = bp->b_bufobj->bo_object;
2871 VM_OBJECT_ASSERT_WLOCKED(object);
2874 * We qualify the scan for modified pages on whether the
2875 * object has been flushed yet.
2877 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
2878 vm_offset_t boffset;
2879 vm_offset_t eoffset;
2882 * test the pages to see if they have been modified directly
2883 * by users through the VM system.
2885 for (i = 0; i < bp->b_npages; i++)
2886 vm_page_test_dirty(bp->b_pages[i]);
2889 * Calculate the encompassing dirty range, boffset and eoffset,
2890 * (eoffset - boffset) bytes.
2893 for (i = 0; i < bp->b_npages; i++) {
2894 if (bp->b_pages[i]->dirty)
2897 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2899 for (i = bp->b_npages - 1; i >= 0; --i) {
2900 if (bp->b_pages[i]->dirty) {
2904 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2907 * Fit it to the buffer.
2910 if (eoffset > bp->b_bcount)
2911 eoffset = bp->b_bcount;
2914 * If we have a good dirty range, merge with the existing
2918 if (boffset < eoffset) {
2919 if (bp->b_dirtyoff > boffset)
2920 bp->b_dirtyoff = boffset;
2921 if (bp->b_dirtyend < eoffset)
2922 bp->b_dirtyend = eoffset;
2928 * Allocate the KVA mapping for an existing buffer. It handles the
2929 * cases of both B_UNMAPPED buffer, and buffer with the preallocated
2930 * KVA which is not mapped (B_KVAALLOC).
2933 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
2935 struct buf *scratch_bp;
2936 int bsize, maxsize, need_mapping, need_kva;
2939 need_mapping = (bp->b_flags & B_UNMAPPED) != 0 &&
2940 (gbflags & GB_UNMAPPED) == 0;
2941 need_kva = (bp->b_flags & (B_KVAALLOC | B_UNMAPPED)) == B_UNMAPPED &&
2942 (gbflags & GB_KVAALLOC) != 0;
2943 if (!need_mapping && !need_kva)
2946 BUF_CHECK_UNMAPPED(bp);
2948 if (need_mapping && (bp->b_flags & B_KVAALLOC) != 0) {
2950 * Buffer is not mapped, but the KVA was already
2951 * reserved at the time of the instantiation. Use the
2954 bp->b_flags &= ~B_KVAALLOC;
2955 KASSERT(bp->b_kvaalloc != 0, ("kvaalloc == 0"));
2956 bp->b_kvabase = bp->b_kvaalloc;
2957 atomic_subtract_long(&unmapped_bufspace, bp->b_kvasize);
2962 * Calculate the amount of the address space we would reserve
2963 * if the buffer was mapped.
2965 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
2966 offset = blkno * bsize;
2967 maxsize = size + (offset & PAGE_MASK);
2968 maxsize = imax(maxsize, bsize);
2971 if (allocbufkva(bp, maxsize, gbflags)) {
2973 * Request defragmentation. getnewbuf() returns us the
2974 * allocated space by the scratch buffer KVA.
2976 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
2977 (GB_UNMAPPED | GB_KVAALLOC));
2978 if (scratch_bp == NULL) {
2979 if ((gbflags & GB_NOWAIT_BD) != 0) {
2981 * XXXKIB: defragmentation cannot
2982 * succeed, not sure what else to do.
2984 panic("GB_NOWAIT_BD and B_UNMAPPED %p", bp);
2986 atomic_add_int(&mappingrestarts, 1);
2989 KASSERT((scratch_bp->b_flags & B_KVAALLOC) != 0,
2990 ("scratch bp !B_KVAALLOC %p", scratch_bp));
2991 setbufkva(bp, (vm_offset_t)scratch_bp->b_kvaalloc,
2992 scratch_bp->b_kvasize, gbflags);
2994 /* Get rid of the scratch buffer. */
2995 scratch_bp->b_kvasize = 0;
2996 scratch_bp->b_flags |= B_INVAL;
2997 scratch_bp->b_flags &= ~(B_UNMAPPED | B_KVAALLOC);
3004 bp->b_saveaddr = bp->b_kvabase;
3005 bp->b_data = bp->b_saveaddr; /* b_offset is handled by bpmap_qenter */
3006 bp->b_flags &= ~B_UNMAPPED;
3007 BUF_CHECK_MAPPED(bp);
3014 * Get a block given a specified block and offset into a file/device.
3015 * The buffers B_DONE bit will be cleared on return, making it almost
3016 * ready for an I/O initiation. B_INVAL may or may not be set on
3017 * return. The caller should clear B_INVAL prior to initiating a
3020 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3021 * an existing buffer.
3023 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3024 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3025 * and then cleared based on the backing VM. If the previous buffer is
3026 * non-0-sized but invalid, B_CACHE will be cleared.
3028 * If getblk() must create a new buffer, the new buffer is returned with
3029 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3030 * case it is returned with B_INVAL clear and B_CACHE set based on the
3033 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3034 * B_CACHE bit is clear.
3036 * What this means, basically, is that the caller should use B_CACHE to
3037 * determine whether the buffer is fully valid or not and should clear
3038 * B_INVAL prior to issuing a read. If the caller intends to validate
3039 * the buffer by loading its data area with something, the caller needs
3040 * to clear B_INVAL. If the caller does this without issuing an I/O,
3041 * the caller should set B_CACHE ( as an optimization ), else the caller
3042 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3043 * a write attempt or if it was a successfull read. If the caller
3044 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3045 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3048 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3053 int bsize, error, maxsize, vmio;
3056 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3057 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3058 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3059 ASSERT_VOP_LOCKED(vp, "getblk");
3060 if (size > MAXBSIZE)
3061 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
3062 if (!unmapped_buf_allowed)
3063 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3068 bp = gbincore(bo, blkno);
3072 * Buffer is in-core. If the buffer is not busy nor managed,
3073 * it must be on a queue.
3075 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3077 if (flags & GB_LOCK_NOWAIT)
3078 lockflags |= LK_NOWAIT;
3080 error = BUF_TIMELOCK(bp, lockflags,
3081 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3084 * If we slept and got the lock we have to restart in case
3085 * the buffer changed identities.
3087 if (error == ENOLCK)
3089 /* We timed out or were interrupted. */
3092 /* If recursed, assume caller knows the rules. */
3093 else if (BUF_LOCKRECURSED(bp))
3097 * The buffer is locked. B_CACHE is cleared if the buffer is
3098 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3099 * and for a VMIO buffer B_CACHE is adjusted according to the
3102 if (bp->b_flags & B_INVAL)
3103 bp->b_flags &= ~B_CACHE;
3104 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3105 bp->b_flags |= B_CACHE;
3106 if (bp->b_flags & B_MANAGED)
3107 MPASS(bp->b_qindex == QUEUE_NONE);
3112 * check for size inconsistencies for non-VMIO case.
3114 if (bp->b_bcount != size) {
3115 if ((bp->b_flags & B_VMIO) == 0 ||
3116 (size > bp->b_kvasize)) {
3117 if (bp->b_flags & B_DELWRI) {
3119 * If buffer is pinned and caller does
3120 * not want sleep waiting for it to be
3121 * unpinned, bail out
3123 if (bp->b_pin_count > 0) {
3124 if (flags & GB_LOCK_NOWAIT) {
3131 bp->b_flags |= B_NOCACHE;
3134 if (LIST_EMPTY(&bp->b_dep)) {
3135 bp->b_flags |= B_RELBUF;
3138 bp->b_flags |= B_NOCACHE;
3147 * Handle the case of unmapped buffer which should
3148 * become mapped, or the buffer for which KVA
3149 * reservation is requested.
3151 bp_unmapped_get_kva(bp, blkno, size, flags);
3154 * If the size is inconsistant in the VMIO case, we can resize
3155 * the buffer. This might lead to B_CACHE getting set or
3156 * cleared. If the size has not changed, B_CACHE remains
3157 * unchanged from its previous state.
3159 if (bp->b_bcount != size)
3162 KASSERT(bp->b_offset != NOOFFSET,
3163 ("getblk: no buffer offset"));
3166 * A buffer with B_DELWRI set and B_CACHE clear must
3167 * be committed before we can return the buffer in
3168 * order to prevent the caller from issuing a read
3169 * ( due to B_CACHE not being set ) and overwriting
3172 * Most callers, including NFS and FFS, need this to
3173 * operate properly either because they assume they
3174 * can issue a read if B_CACHE is not set, or because
3175 * ( for example ) an uncached B_DELWRI might loop due
3176 * to softupdates re-dirtying the buffer. In the latter
3177 * case, B_CACHE is set after the first write completes,
3178 * preventing further loops.
3179 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3180 * above while extending the buffer, we cannot allow the
3181 * buffer to remain with B_CACHE set after the write
3182 * completes or it will represent a corrupt state. To
3183 * deal with this we set B_NOCACHE to scrap the buffer
3186 * We might be able to do something fancy, like setting
3187 * B_CACHE in bwrite() except if B_DELWRI is already set,
3188 * so the below call doesn't set B_CACHE, but that gets real
3189 * confusing. This is much easier.
3192 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3193 bp->b_flags |= B_NOCACHE;
3197 bp->b_flags &= ~B_DONE;
3200 * Buffer is not in-core, create new buffer. The buffer
3201 * returned by getnewbuf() is locked. Note that the returned
3202 * buffer is also considered valid (not marked B_INVAL).
3206 * If the user does not want us to create the buffer, bail out
3209 if (flags & GB_NOCREAT)
3211 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3214 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3215 offset = blkno * bsize;
3216 vmio = vp->v_object != NULL;
3218 maxsize = size + (offset & PAGE_MASK);
3221 /* Do not allow non-VMIO notmapped buffers. */
3222 flags &= ~GB_UNMAPPED;
3224 maxsize = imax(maxsize, bsize);
3226 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3228 if (slpflag || slptimeo)
3234 * This code is used to make sure that a buffer is not
3235 * created while the getnewbuf routine is blocked.
3236 * This can be a problem whether the vnode is locked or not.
3237 * If the buffer is created out from under us, we have to
3238 * throw away the one we just created.
3240 * Note: this must occur before we associate the buffer
3241 * with the vp especially considering limitations in
3242 * the splay tree implementation when dealing with duplicate
3246 if (gbincore(bo, blkno)) {
3248 bp->b_flags |= B_INVAL;
3254 * Insert the buffer into the hash, so that it can
3255 * be found by incore.
3257 bp->b_blkno = bp->b_lblkno = blkno;
3258 bp->b_offset = offset;
3263 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3264 * buffer size starts out as 0, B_CACHE will be set by
3265 * allocbuf() for the VMIO case prior to it testing the
3266 * backing store for validity.
3270 bp->b_flags |= B_VMIO;
3271 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3272 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3273 bp, vp->v_object, bp->b_bufobj->bo_object));
3275 bp->b_flags &= ~B_VMIO;
3276 KASSERT(bp->b_bufobj->bo_object == NULL,
3277 ("ARGH! has b_bufobj->bo_object %p %p\n",
3278 bp, bp->b_bufobj->bo_object));
3279 BUF_CHECK_MAPPED(bp);
3283 bp->b_flags &= ~B_DONE;
3285 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3286 BUF_ASSERT_HELD(bp);
3288 KASSERT(bp->b_bufobj == bo,
3289 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3294 * Get an empty, disassociated buffer of given size. The buffer is initially
3298 geteblk(int size, int flags)
3303 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3304 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3305 if ((flags & GB_NOWAIT_BD) &&
3306 (curthread->td_pflags & TDP_BUFNEED) != 0)
3310 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3311 BUF_ASSERT_HELD(bp);
3317 * This code constitutes the buffer memory from either anonymous system
3318 * memory (in the case of non-VMIO operations) or from an associated
3319 * VM object (in the case of VMIO operations). This code is able to
3320 * resize a buffer up or down.
3322 * Note that this code is tricky, and has many complications to resolve
3323 * deadlock or inconsistant data situations. Tread lightly!!!
3324 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3325 * the caller. Calling this code willy nilly can result in the loss of data.
3327 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3328 * B_CACHE for the non-VMIO case.
3332 allocbuf(struct buf *bp, int size)
3334 int newbsize, mbsize;
3337 BUF_ASSERT_HELD(bp);
3339 if (bp->b_kvasize < size)
3340 panic("allocbuf: buffer too small");
3342 if ((bp->b_flags & B_VMIO) == 0) {
3346 * Just get anonymous memory from the kernel. Don't
3347 * mess with B_CACHE.
3349 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3350 if (bp->b_flags & B_MALLOC)
3353 newbsize = round_page(size);
3355 if (newbsize < bp->b_bufsize) {
3357 * malloced buffers are not shrunk
3359 if (bp->b_flags & B_MALLOC) {
3361 bp->b_bcount = size;
3363 free(bp->b_data, M_BIOBUF);
3364 if (bp->b_bufsize) {
3365 atomic_subtract_long(
3371 bp->b_saveaddr = bp->b_kvabase;
3372 bp->b_data = bp->b_saveaddr;
3374 bp->b_flags &= ~B_MALLOC;
3378 vm_hold_free_pages(bp, newbsize);
3379 } else if (newbsize > bp->b_bufsize) {
3381 * We only use malloced memory on the first allocation.
3382 * and revert to page-allocated memory when the buffer
3386 * There is a potential smp race here that could lead
3387 * to bufmallocspace slightly passing the max. It
3388 * is probably extremely rare and not worth worrying
3391 if ( (bufmallocspace < maxbufmallocspace) &&
3392 (bp->b_bufsize == 0) &&
3393 (mbsize <= PAGE_SIZE/2)) {
3395 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
3396 bp->b_bufsize = mbsize;
3397 bp->b_bcount = size;
3398 bp->b_flags |= B_MALLOC;
3399 atomic_add_long(&bufmallocspace, mbsize);
3405 * If the buffer is growing on its other-than-first allocation,
3406 * then we revert to the page-allocation scheme.
3408 if (bp->b_flags & B_MALLOC) {
3409 origbuf = bp->b_data;
3410 origbufsize = bp->b_bufsize;
3411 bp->b_data = bp->b_kvabase;
3412 if (bp->b_bufsize) {
3413 atomic_subtract_long(&bufmallocspace,
3418 bp->b_flags &= ~B_MALLOC;
3419 newbsize = round_page(newbsize);
3423 (vm_offset_t) bp->b_data + bp->b_bufsize,
3424 (vm_offset_t) bp->b_data + newbsize);
3426 bcopy(origbuf, bp->b_data, origbufsize);
3427 free(origbuf, M_BIOBUF);
3433 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3434 desiredpages = (size == 0) ? 0 :
3435 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3437 if (bp->b_flags & B_MALLOC)
3438 panic("allocbuf: VMIO buffer can't be malloced");
3440 * Set B_CACHE initially if buffer is 0 length or will become
3443 if (size == 0 || bp->b_bufsize == 0)
3444 bp->b_flags |= B_CACHE;
3446 if (newbsize < bp->b_bufsize) {
3448 * DEV_BSIZE aligned new buffer size is less then the
3449 * DEV_BSIZE aligned existing buffer size. Figure out
3450 * if we have to remove any pages.
3452 if (desiredpages < bp->b_npages) {
3455 if ((bp->b_flags & B_UNMAPPED) == 0) {
3456 BUF_CHECK_MAPPED(bp);
3457 pmap_qremove((vm_offset_t)trunc_page(
3458 (vm_offset_t)bp->b_data) +
3459 (desiredpages << PAGE_SHIFT),
3460 (bp->b_npages - desiredpages));
3462 BUF_CHECK_UNMAPPED(bp);
3463 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3464 for (i = desiredpages; i < bp->b_npages; i++) {
3466 * the page is not freed here -- it
3467 * is the responsibility of
3468 * vnode_pager_setsize
3471 KASSERT(m != bogus_page,
3472 ("allocbuf: bogus page found"));
3473 while (vm_page_sleep_if_busy(m,
3477 bp->b_pages[i] = NULL;
3479 vm_page_unwire(m, 0);
3482 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3483 bp->b_npages = desiredpages;
3485 } else if (size > bp->b_bcount) {
3487 * We are growing the buffer, possibly in a
3488 * byte-granular fashion.
3495 * Step 1, bring in the VM pages from the object,
3496 * allocating them if necessary. We must clear
3497 * B_CACHE if these pages are not valid for the
3498 * range covered by the buffer.
3501 obj = bp->b_bufobj->bo_object;
3503 VM_OBJECT_WLOCK(obj);
3504 while (bp->b_npages < desiredpages) {
3508 * We must allocate system pages since blocking
3509 * here could interfere with paging I/O, no
3510 * matter which process we are.
3512 * Only exclusive busy can be tested here.
3513 * Blocking on shared busy might lead to
3514 * deadlocks once allocbuf() is called after
3515 * pages are vfs_busy_pages().
3517 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) +
3518 bp->b_npages, VM_ALLOC_NOBUSY |
3519 VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
3520 VM_ALLOC_IGN_SBUSY |
3521 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
3523 bp->b_flags &= ~B_CACHE;
3524 bp->b_pages[bp->b_npages] = m;
3529 * Step 2. We've loaded the pages into the buffer,
3530 * we have to figure out if we can still have B_CACHE
3531 * set. Note that B_CACHE is set according to the
3532 * byte-granular range ( bcount and size ), new the
3533 * aligned range ( newbsize ).
3535 * The VM test is against m->valid, which is DEV_BSIZE
3536 * aligned. Needless to say, the validity of the data
3537 * needs to also be DEV_BSIZE aligned. Note that this
3538 * fails with NFS if the server or some other client
3539 * extends the file's EOF. If our buffer is resized,
3540 * B_CACHE may remain set! XXX
3543 toff = bp->b_bcount;
3544 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3546 while ((bp->b_flags & B_CACHE) && toff < size) {
3549 if (tinc > (size - toff))
3552 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
3565 VM_OBJECT_WUNLOCK(obj);
3568 * Step 3, fixup the KVM pmap.
3570 if ((bp->b_flags & B_UNMAPPED) == 0)
3573 BUF_CHECK_UNMAPPED(bp);
3576 if (newbsize < bp->b_bufsize)
3578 bp->b_bufsize = newbsize; /* actual buffer allocation */
3579 bp->b_bcount = size; /* requested buffer size */
3583 extern int inflight_transient_maps;
3586 biodone(struct bio *bp)
3589 void (*done)(struct bio *);
3590 vm_offset_t start, end;
3592 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3593 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3594 bp->bio_flags |= BIO_UNMAPPED;
3595 start = trunc_page((vm_offset_t)bp->bio_data);
3596 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3597 pmap_qremove(start, OFF_TO_IDX(end - start));
3598 vmem_free(transient_arena, start, end - start);
3599 atomic_add_int(&inflight_transient_maps, -1);
3601 done = bp->bio_done;
3603 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3605 bp->bio_flags |= BIO_DONE;
3609 bp->bio_flags |= BIO_DONE;
3615 * Wait for a BIO to finish.
3618 biowait(struct bio *bp, const char *wchan)
3622 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3624 while ((bp->bio_flags & BIO_DONE) == 0)
3625 msleep(bp, mtxp, PRIBIO, wchan, 0);
3627 if (bp->bio_error != 0)
3628 return (bp->bio_error);
3629 if (!(bp->bio_flags & BIO_ERROR))
3635 biofinish(struct bio *bp, struct devstat *stat, int error)
3639 bp->bio_error = error;
3640 bp->bio_flags |= BIO_ERROR;
3643 devstat_end_transaction_bio(stat, bp);
3650 * Wait for buffer I/O completion, returning error status. The buffer
3651 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3652 * error and cleared.
3655 bufwait(struct buf *bp)
3657 if (bp->b_iocmd == BIO_READ)
3658 bwait(bp, PRIBIO, "biord");
3660 bwait(bp, PRIBIO, "biowr");
3661 if (bp->b_flags & B_EINTR) {
3662 bp->b_flags &= ~B_EINTR;
3665 if (bp->b_ioflags & BIO_ERROR) {
3666 return (bp->b_error ? bp->b_error : EIO);
3673 * Call back function from struct bio back up to struct buf.
3676 bufdonebio(struct bio *bip)
3680 bp = bip->bio_caller2;
3681 bp->b_resid = bip->bio_resid;
3682 bp->b_ioflags = bip->bio_flags;
3683 bp->b_error = bip->bio_error;
3685 bp->b_ioflags |= BIO_ERROR;
3691 dev_strategy(struct cdev *dev, struct buf *bp)
3696 KASSERT(dev->si_refcount > 0,
3697 ("dev_strategy on un-referenced struct cdev *(%s) %p",
3698 devtoname(dev), dev));
3700 csw = dev_refthread(dev, &ref);
3701 dev_strategy_csw(dev, csw, bp);
3702 dev_relthread(dev, ref);
3706 dev_strategy_csw(struct cdev *dev, struct cdevsw *csw, struct buf *bp)
3710 KASSERT(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE,
3712 KASSERT(((dev->si_flags & SI_ETERNAL) != 0 && csw != NULL) ||
3713 dev->si_threadcount > 0,
3714 ("dev_strategy_csw threadcount cdev *(%s) %p", devtoname(dev),
3717 bp->b_error = ENXIO;
3718 bp->b_ioflags = BIO_ERROR;
3726 /* Try again later */
3727 tsleep(&bp, PRIBIO, "dev_strat", hz/10);
3729 bip->bio_cmd = bp->b_iocmd;
3730 bip->bio_offset = bp->b_iooffset;
3731 bip->bio_length = bp->b_bcount;
3732 bip->bio_bcount = bp->b_bcount; /* XXX: remove */
3734 bip->bio_done = bufdonebio;
3735 bip->bio_caller2 = bp;
3737 (*csw->d_strategy)(bip);
3743 * Finish I/O on a buffer, optionally calling a completion function.
3744 * This is usually called from an interrupt so process blocking is
3747 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3748 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3749 * assuming B_INVAL is clear.
3751 * For the VMIO case, we set B_CACHE if the op was a read and no
3752 * read error occured, or if the op was a write. B_CACHE is never
3753 * set if the buffer is invalid or otherwise uncacheable.
3755 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3756 * initiator to leave B_INVAL set to brelse the buffer out of existance
3757 * in the biodone routine.
3760 bufdone(struct buf *bp)
3762 struct bufobj *dropobj;
3763 void (*biodone)(struct buf *);
3765 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3768 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3769 BUF_ASSERT_HELD(bp);
3771 runningbufwakeup(bp);
3772 if (bp->b_iocmd == BIO_WRITE)
3773 dropobj = bp->b_bufobj;
3774 /* call optional completion function if requested */
3775 if (bp->b_iodone != NULL) {
3776 biodone = bp->b_iodone;
3777 bp->b_iodone = NULL;
3780 bufobj_wdrop(dropobj);
3787 bufobj_wdrop(dropobj);
3791 bufdone_finish(struct buf *bp)
3793 BUF_ASSERT_HELD(bp);
3795 if (!LIST_EMPTY(&bp->b_dep))
3798 if (bp->b_flags & B_VMIO) {
3803 int bogus, i, iosize;
3805 obj = bp->b_bufobj->bo_object;
3806 KASSERT(obj->paging_in_progress >= bp->b_npages,
3807 ("biodone_finish: paging in progress(%d) < b_npages(%d)",
3808 obj->paging_in_progress, bp->b_npages));
3811 KASSERT(vp->v_holdcnt > 0,
3812 ("biodone_finish: vnode %p has zero hold count", vp));
3813 KASSERT(vp->v_object != NULL,
3814 ("biodone_finish: vnode %p has no vm_object", vp));
3816 foff = bp->b_offset;
3817 KASSERT(bp->b_offset != NOOFFSET,
3818 ("biodone_finish: bp %p has no buffer offset", bp));
3821 * Set B_CACHE if the op was a normal read and no error
3822 * occured. B_CACHE is set for writes in the b*write()
3825 iosize = bp->b_bcount - bp->b_resid;
3826 if (bp->b_iocmd == BIO_READ &&
3827 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3828 !(bp->b_ioflags & BIO_ERROR)) {
3829 bp->b_flags |= B_CACHE;
3832 VM_OBJECT_WLOCK(obj);
3833 for (i = 0; i < bp->b_npages; i++) {
3837 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3842 * cleanup bogus pages, restoring the originals
3845 if (m == bogus_page) {
3846 bogus = bogusflag = 1;
3847 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3849 panic("biodone: page disappeared!");
3852 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3853 ("biodone_finish: foff(%jd)/pindex(%ju) mismatch",
3854 (intmax_t)foff, (uintmax_t)m->pindex));
3857 * In the write case, the valid and clean bits are
3858 * already changed correctly ( see bdwrite() ), so we
3859 * only need to do this here in the read case.
3861 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) {
3862 KASSERT((m->dirty & vm_page_bits(foff &
3863 PAGE_MASK, resid)) == 0, ("bufdone_finish:"
3864 " page %p has unexpected dirty bits", m));
3865 vfs_page_set_valid(bp, foff, m);
3869 vm_object_pip_subtract(obj, 1);
3870 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3873 vm_object_pip_wakeupn(obj, 0);
3874 VM_OBJECT_WUNLOCK(obj);
3875 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
3876 BUF_CHECK_MAPPED(bp);
3877 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3878 bp->b_pages, bp->b_npages);
3883 * For asynchronous completions, release the buffer now. The brelse
3884 * will do a wakeup there if necessary - so no need to do a wakeup
3885 * here in the async case. The sync case always needs to do a wakeup.
3888 if (bp->b_flags & B_ASYNC) {
3889 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR))
3898 * This routine is called in lieu of iodone in the case of
3899 * incomplete I/O. This keeps the busy status for pages
3903 vfs_unbusy_pages(struct buf *bp)
3909 runningbufwakeup(bp);
3910 if (!(bp->b_flags & B_VMIO))
3913 obj = bp->b_bufobj->bo_object;
3914 VM_OBJECT_WLOCK(obj);
3915 for (i = 0; i < bp->b_npages; i++) {
3917 if (m == bogus_page) {
3918 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3920 panic("vfs_unbusy_pages: page missing\n");
3922 if ((bp->b_flags & B_UNMAPPED) == 0) {
3923 BUF_CHECK_MAPPED(bp);
3924 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3925 bp->b_pages, bp->b_npages);
3927 BUF_CHECK_UNMAPPED(bp);
3929 vm_object_pip_subtract(obj, 1);
3932 vm_object_pip_wakeupn(obj, 0);
3933 VM_OBJECT_WUNLOCK(obj);
3937 * vfs_page_set_valid:
3939 * Set the valid bits in a page based on the supplied offset. The
3940 * range is restricted to the buffer's size.
3942 * This routine is typically called after a read completes.
3945 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3950 * Compute the end offset, eoff, such that [off, eoff) does not span a
3951 * page boundary and eoff is not greater than the end of the buffer.
3952 * The end of the buffer, in this case, is our file EOF, not the
3953 * allocation size of the buffer.
3955 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3956 if (eoff > bp->b_offset + bp->b_bcount)
3957 eoff = bp->b_offset + bp->b_bcount;
3960 * Set valid range. This is typically the entire buffer and thus the
3964 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3968 * vfs_page_set_validclean:
3970 * Set the valid bits and clear the dirty bits in a page based on the
3971 * supplied offset. The range is restricted to the buffer's size.
3974 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3976 vm_ooffset_t soff, eoff;
3979 * Start and end offsets in buffer. eoff - soff may not cross a
3980 * page boundry or cross the end of the buffer. The end of the
3981 * buffer, in this case, is our file EOF, not the allocation size
3985 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3986 if (eoff > bp->b_offset + bp->b_bcount)
3987 eoff = bp->b_offset + bp->b_bcount;
3990 * Set valid range. This is typically the entire buffer and thus the
3994 vm_page_set_validclean(
3996 (vm_offset_t) (soff & PAGE_MASK),
3997 (vm_offset_t) (eoff - soff)
4003 * Ensure that all buffer pages are not exclusive busied. If any page is
4004 * exclusive busy, drain it.
4007 vfs_drain_busy_pages(struct buf *bp)
4012 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4014 for (i = 0; i < bp->b_npages; i++) {
4016 if (vm_page_xbusied(m)) {
4017 for (; last_busied < i; last_busied++)
4018 vm_page_sbusy(bp->b_pages[last_busied]);
4019 while (vm_page_xbusied(m)) {
4021 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4022 vm_page_busy_sleep(m, "vbpage");
4023 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4027 for (i = 0; i < last_busied; i++)
4028 vm_page_sunbusy(bp->b_pages[i]);
4032 * This routine is called before a device strategy routine.
4033 * It is used to tell the VM system that paging I/O is in
4034 * progress, and treat the pages associated with the buffer
4035 * almost as being exclusive busy. Also the object paging_in_progress
4036 * flag is handled to make sure that the object doesn't become
4039 * Since I/O has not been initiated yet, certain buffer flags
4040 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4041 * and should be ignored.
4044 vfs_busy_pages(struct buf *bp, int clear_modify)
4051 if (!(bp->b_flags & B_VMIO))
4054 obj = bp->b_bufobj->bo_object;
4055 foff = bp->b_offset;
4056 KASSERT(bp->b_offset != NOOFFSET,
4057 ("vfs_busy_pages: no buffer offset"));
4058 VM_OBJECT_WLOCK(obj);
4059 vfs_drain_busy_pages(bp);
4060 if (bp->b_bufsize != 0)
4061 vfs_setdirty_locked_object(bp);
4063 for (i = 0; i < bp->b_npages; i++) {
4066 if ((bp->b_flags & B_CLUSTER) == 0) {
4067 vm_object_pip_add(obj, 1);
4071 * When readying a buffer for a read ( i.e
4072 * clear_modify == 0 ), it is important to do
4073 * bogus_page replacement for valid pages in
4074 * partially instantiated buffers. Partially
4075 * instantiated buffers can, in turn, occur when
4076 * reconstituting a buffer from its VM backing store
4077 * base. We only have to do this if B_CACHE is
4078 * clear ( which causes the I/O to occur in the
4079 * first place ). The replacement prevents the read
4080 * I/O from overwriting potentially dirty VM-backed
4081 * pages. XXX bogus page replacement is, uh, bogus.
4082 * It may not work properly with small-block devices.
4083 * We need to find a better way.
4086 pmap_remove_write(m);
4087 vfs_page_set_validclean(bp, foff, m);
4088 } else if (m->valid == VM_PAGE_BITS_ALL &&
4089 (bp->b_flags & B_CACHE) == 0) {
4090 bp->b_pages[i] = bogus_page;
4093 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4095 VM_OBJECT_WUNLOCK(obj);
4096 if (bogus && (bp->b_flags & B_UNMAPPED) == 0) {
4097 BUF_CHECK_MAPPED(bp);
4098 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4099 bp->b_pages, bp->b_npages);
4104 * vfs_bio_set_valid:
4106 * Set the range within the buffer to valid. The range is
4107 * relative to the beginning of the buffer, b_offset. Note that
4108 * b_offset itself may be offset from the beginning of the first
4112 vfs_bio_set_valid(struct buf *bp, int base, int size)
4117 if (!(bp->b_flags & B_VMIO))
4121 * Fixup base to be relative to beginning of first page.
4122 * Set initial n to be the maximum number of bytes in the
4123 * first page that can be validated.
4125 base += (bp->b_offset & PAGE_MASK);
4126 n = PAGE_SIZE - (base & PAGE_MASK);
4128 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4129 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4133 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4138 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4144 * If the specified buffer is a non-VMIO buffer, clear the entire
4145 * buffer. If the specified buffer is a VMIO buffer, clear and
4146 * validate only the previously invalid portions of the buffer.
4147 * This routine essentially fakes an I/O, so we need to clear
4148 * BIO_ERROR and B_INVAL.
4150 * Note that while we only theoretically need to clear through b_bcount,
4151 * we go ahead and clear through b_bufsize.
4154 vfs_bio_clrbuf(struct buf *bp)
4156 int i, j, mask, sa, ea, slide;
4158 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4162 bp->b_flags &= ~B_INVAL;
4163 bp->b_ioflags &= ~BIO_ERROR;
4164 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4165 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4166 (bp->b_offset & PAGE_MASK) == 0) {
4167 if (bp->b_pages[0] == bogus_page)
4169 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4170 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4171 if ((bp->b_pages[0]->valid & mask) == mask)
4173 if ((bp->b_pages[0]->valid & mask) == 0) {
4174 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4175 bp->b_pages[0]->valid |= mask;
4179 sa = bp->b_offset & PAGE_MASK;
4181 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4182 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4183 ea = slide & PAGE_MASK;
4186 if (bp->b_pages[i] == bogus_page)
4189 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4190 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4191 if ((bp->b_pages[i]->valid & mask) == mask)
4193 if ((bp->b_pages[i]->valid & mask) == 0)
4194 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4196 for (; sa < ea; sa += DEV_BSIZE, j++) {
4197 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4198 pmap_zero_page_area(bp->b_pages[i],
4203 bp->b_pages[i]->valid |= mask;
4206 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4211 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4216 if ((bp->b_flags & B_UNMAPPED) == 0) {
4217 BUF_CHECK_MAPPED(bp);
4218 bzero(bp->b_data + base, size);
4220 BUF_CHECK_UNMAPPED(bp);
4221 n = PAGE_SIZE - (base & PAGE_MASK);
4222 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4226 pmap_zero_page_area(m, base & PAGE_MASK, n);
4235 * vm_hold_load_pages and vm_hold_free_pages get pages into
4236 * a buffers address space. The pages are anonymous and are
4237 * not associated with a file object.
4240 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4246 BUF_CHECK_MAPPED(bp);
4248 to = round_page(to);
4249 from = round_page(from);
4250 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4252 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4255 * note: must allocate system pages since blocking here
4256 * could interfere with paging I/O, no matter which
4259 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4260 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4265 pmap_qenter(pg, &p, 1);
4266 bp->b_pages[index] = p;
4268 bp->b_npages = index;
4271 /* Return pages associated with this buf to the vm system */
4273 vm_hold_free_pages(struct buf *bp, int newbsize)
4277 int index, newnpages;
4279 BUF_CHECK_MAPPED(bp);
4281 from = round_page((vm_offset_t)bp->b_data + newbsize);
4282 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4283 if (bp->b_npages > newnpages)
4284 pmap_qremove(from, bp->b_npages - newnpages);
4285 for (index = newnpages; index < bp->b_npages; index++) {
4286 p = bp->b_pages[index];
4287 bp->b_pages[index] = NULL;
4288 if (vm_page_sbusied(p))
4289 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4290 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4293 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
4295 bp->b_npages = newnpages;
4299 * Map an IO request into kernel virtual address space.
4301 * All requests are (re)mapped into kernel VA space.
4302 * Notice that we use b_bufsize for the size of the buffer
4303 * to be mapped. b_bcount might be modified by the driver.
4305 * Note that even if the caller determines that the address space should
4306 * be valid, a race or a smaller-file mapped into a larger space may
4307 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4308 * check the return value.
4311 vmapbuf(struct buf *bp, int mapbuf)
4317 if (bp->b_bufsize < 0)
4319 prot = VM_PROT_READ;
4320 if (bp->b_iocmd == BIO_READ)
4321 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4322 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4323 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4324 btoc(MAXPHYS))) < 0)
4326 bp->b_npages = pidx;
4327 if (mapbuf || !unmapped_buf_allowed) {
4328 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
4329 kva = bp->b_saveaddr;
4330 bp->b_saveaddr = bp->b_data;
4331 bp->b_data = kva + (((vm_offset_t)bp->b_data) & PAGE_MASK);
4332 bp->b_flags &= ~B_UNMAPPED;
4334 bp->b_flags |= B_UNMAPPED;
4335 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4336 bp->b_saveaddr = bp->b_data;
4337 bp->b_data = unmapped_buf;
4343 * Free the io map PTEs associated with this IO operation.
4344 * We also invalidate the TLB entries and restore the original b_addr.
4347 vunmapbuf(struct buf *bp)
4351 npages = bp->b_npages;
4352 if (bp->b_flags & B_UNMAPPED)
4353 bp->b_flags &= ~B_UNMAPPED;
4355 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4356 vm_page_unhold_pages(bp->b_pages, npages);
4358 bp->b_data = bp->b_saveaddr;
4362 bdone(struct buf *bp)
4366 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4368 bp->b_flags |= B_DONE;
4374 bwait(struct buf *bp, u_char pri, const char *wchan)
4378 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4380 while ((bp->b_flags & B_DONE) == 0)
4381 msleep(bp, mtxp, pri, wchan, 0);
4386 bufsync(struct bufobj *bo, int waitfor)
4389 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4393 bufstrategy(struct bufobj *bo, struct buf *bp)
4399 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4400 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4401 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4402 i = VOP_STRATEGY(vp, bp);
4403 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4407 bufobj_wrefl(struct bufobj *bo)
4410 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4411 ASSERT_BO_WLOCKED(bo);
4416 bufobj_wref(struct bufobj *bo)
4419 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4426 bufobj_wdrop(struct bufobj *bo)
4429 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4431 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4432 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4433 bo->bo_flag &= ~BO_WWAIT;
4434 wakeup(&bo->bo_numoutput);
4440 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4444 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4445 ASSERT_BO_WLOCKED(bo);
4447 while (bo->bo_numoutput) {
4448 bo->bo_flag |= BO_WWAIT;
4449 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4450 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4458 bpin(struct buf *bp)
4462 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4469 bunpin(struct buf *bp)
4473 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4475 if (--bp->b_pin_count == 0)
4481 bunpin_wait(struct buf *bp)
4485 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4487 while (bp->b_pin_count > 0)
4488 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4493 * Set bio_data or bio_ma for struct bio from the struct buf.
4496 bdata2bio(struct buf *bp, struct bio *bip)
4499 if ((bp->b_flags & B_UNMAPPED) != 0) {
4500 KASSERT(unmapped_buf_allowed, ("unmapped"));
4501 bip->bio_ma = bp->b_pages;
4502 bip->bio_ma_n = bp->b_npages;
4503 bip->bio_data = unmapped_buf;
4504 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4505 bip->bio_flags |= BIO_UNMAPPED;
4506 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4507 PAGE_SIZE == bp->b_npages,
4508 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4509 (long long)bip->bio_length, bip->bio_ma_n));
4511 bip->bio_data = bp->b_data;
4516 #include "opt_ddb.h"
4518 #include <ddb/ddb.h>
4520 /* DDB command to show buffer data */
4521 DB_SHOW_COMMAND(buffer, db_show_buffer)
4524 struct buf *bp = (struct buf *)addr;
4527 db_printf("usage: show buffer <addr>\n");
4531 db_printf("buf at %p\n", bp);
4532 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4533 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4534 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4536 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4537 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4539 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4540 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4541 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4544 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4545 for (i = 0; i < bp->b_npages; i++) {
4548 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4549 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4550 if ((i + 1) < bp->b_npages)
4556 BUF_LOCKPRINTINFO(bp);
4559 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4564 for (i = 0; i < nbuf; i++) {
4566 if (BUF_ISLOCKED(bp)) {
4567 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4573 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4579 db_printf("usage: show vnodebufs <addr>\n");
4582 vp = (struct vnode *)addr;
4583 db_printf("Clean buffers:\n");
4584 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4585 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4588 db_printf("Dirty buffers:\n");
4589 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4590 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4595 DB_COMMAND(countfreebufs, db_coundfreebufs)
4598 int i, used = 0, nfree = 0;
4601 db_printf("usage: countfreebufs\n");
4605 for (i = 0; i < nbuf; i++) {
4607 if ((bp->b_flags & B_INFREECNT) != 0)
4613 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4615 db_printf("numfreebuffers is %d\n", numfreebuffers);