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>
67 #include <sys/sysproto.h>
69 #include <sys/vmmeter.h>
70 #include <sys/vnode.h>
71 #include <sys/watchdog.h>
72 #include <geom/geom.h>
74 #include <vm/vm_param.h>
75 #include <vm/vm_kern.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_page.h>
78 #include <vm/vm_object.h>
79 #include <vm/vm_extern.h>
80 #include <vm/vm_map.h>
81 #include <vm/swap_pager.h>
82 #include "opt_compat.h"
85 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
87 struct bio_ops bioops; /* I/O operation notification */
89 struct buf_ops buf_ops_bio = {
90 .bop_name = "buf_ops_bio",
91 .bop_write = bufwrite,
92 .bop_strategy = bufstrategy,
94 .bop_bdflush = bufbdflush,
97 static struct buf *buf; /* buffer header pool */
98 extern struct buf *swbuf; /* Swap buffer header pool. */
101 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
102 struct proc *bufdaemonproc;
104 static int inmem(struct vnode *vp, daddr_t blkno);
105 static void vm_hold_free_pages(struct buf *bp, int newbsize);
106 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
108 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
109 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
111 static void vfs_clean_pages_dirty_buf(struct buf *bp);
112 static void vfs_setdirty_locked_object(struct buf *bp);
113 static void vfs_vmio_invalidate(struct buf *bp);
114 static void vfs_vmio_truncate(struct buf *bp, int npages);
115 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
116 static int vfs_bio_clcheck(struct vnode *vp, int size,
117 daddr_t lblkno, daddr_t blkno);
118 static int buf_flush(struct vnode *vp, int);
119 static int flushbufqueues(struct vnode *, int, int);
120 static void buf_daemon(void);
121 static void bremfreel(struct buf *bp);
122 static __inline void bd_wakeup(void);
123 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
124 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
125 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
126 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
129 int vmiodirenable = TRUE;
130 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
131 "Use the VM system for directory writes");
132 long runningbufspace;
133 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
134 "Amount of presently outstanding async buffer io");
135 static long bufspace;
136 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
137 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
138 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
139 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
141 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
142 "Physical memory used for buffers");
144 static long bufkvaspace;
145 SYSCTL_LONG(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace, 0,
146 "Kernel virtual memory used for buffers");
147 static long maxbufspace;
148 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
149 "Maximum allowed value of bufspace (including buf_daemon)");
150 static long bufmallocspace;
151 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
152 "Amount of malloced memory for buffers");
153 static long maxbufmallocspace;
154 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0,
155 "Maximum amount of malloced memory for buffers");
156 static long lobufspace;
157 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
158 "Minimum amount of buffers we want to have");
160 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
161 "Maximum allowed value of bufspace (excluding buf_daemon)");
162 static int bufreusecnt;
163 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0,
164 "Number of times we have reused a buffer");
165 static int buffreekvacnt;
166 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
167 "Number of times we have freed the KVA space from some buffer");
168 static int bufdefragcnt;
169 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
170 "Number of times we have had to repeat buffer allocation to defragment");
171 static long lorunningspace;
172 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
173 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
174 "Minimum preferred space used for in-progress I/O");
175 static long hirunningspace;
176 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
177 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
178 "Maximum amount of space to use for in-progress I/O");
179 int dirtybufferflushes;
180 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
181 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
183 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
184 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
185 int altbufferflushes;
186 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
187 0, "Number of fsync flushes to limit dirty buffers");
188 static int recursiveflushes;
189 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
190 0, "Number of flushes skipped due to being recursive");
191 static int numdirtybuffers;
192 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
193 "Number of buffers that are dirty (has unwritten changes) at the moment");
194 static int lodirtybuffers;
195 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
196 "How many buffers we want to have free before bufdaemon can sleep");
197 static int hidirtybuffers;
198 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
199 "When the number of dirty buffers is considered severe");
201 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
202 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
203 static int numfreebuffers;
204 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
205 "Number of free buffers");
206 static int lofreebuffers;
207 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
209 static int hifreebuffers;
210 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
211 "XXX Complicatedly unused");
212 static int getnewbufcalls;
213 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
214 "Number of calls to getnewbuf");
215 static int getnewbufrestarts;
216 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
217 "Number of times getnewbuf has had to restart a buffer aquisition");
218 static int mappingrestarts;
219 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
220 "Number of times getblk has had to restart a buffer mapping for "
222 static int flushbufqtarget = 100;
223 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
224 "Amount of work to do in flushbufqueues when helping bufdaemon");
225 static long notbufdflushes;
226 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 0,
227 "Number of dirty buffer flushes done by the bufdaemon helpers");
228 static long barrierwrites;
229 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
230 "Number of barrier writes");
231 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
232 &unmapped_buf_allowed, 0,
233 "Permit the use of the unmapped i/o");
236 * Lock for the non-dirty bufqueues
238 static struct mtx_padalign bqclean;
241 * Lock for the dirty queue.
243 static struct mtx_padalign bqdirty;
246 * This lock synchronizes access to bd_request.
248 static struct mtx_padalign bdlock;
251 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
252 * waitrunningbufspace().
254 static struct mtx_padalign rbreqlock;
257 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
259 static struct rwlock_padalign nblock;
262 * Lock that protects bdirtywait.
264 static struct mtx_padalign bdirtylock;
267 * Wakeup point for bufdaemon, as well as indicator of whether it is already
268 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
271 static int bd_request;
274 * Request for the buf daemon to write more buffers than is indicated by
275 * lodirtybuf. This may be necessary to push out excess dependencies or
276 * defragment the address space where a simple count of the number of dirty
277 * buffers is insufficient to characterize the demand for flushing them.
279 static int bd_speedupreq;
282 * bogus page -- for I/O to/from partially complete buffers
283 * this is a temporary solution to the problem, but it is not
284 * really that bad. it would be better to split the buffer
285 * for input in the case of buffers partially already in memory,
286 * but the code is intricate enough already.
288 vm_page_t bogus_page;
291 * Synchronization (sleep/wakeup) variable for active buffer space requests.
292 * Set when wait starts, cleared prior to wakeup().
293 * Used in runningbufwakeup() and waitrunningbufspace().
295 static int runningbufreq;
298 * Synchronization (sleep/wakeup) variable for buffer requests.
299 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
301 * Used in numdirtywakeup(), bufspacewakeup(), bufcountadd(), bwillwrite(),
302 * getnewbuf(), and getblk().
304 static volatile int needsbuffer;
307 * Synchronization for bwillwrite() waiters.
309 static int bdirtywait;
312 * Definitions for the buffer free lists.
314 #define BUFFER_QUEUES 4 /* number of free buffer queues */
316 #define QUEUE_NONE 0 /* on no queue */
317 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */
318 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
319 #define QUEUE_EMPTY 3 /* empty buffer headers */
320 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
322 /* Queues for free buffers with various properties */
323 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
325 static int bq_len[BUFFER_QUEUES];
329 * Single global constant for BUF_WMESG, to avoid getting multiple references.
330 * buf_wmesg is referred from macros.
332 const char *buf_wmesg = BUF_WMESG;
334 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
335 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
336 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
339 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
344 value = *(long *)arg1;
345 error = sysctl_handle_long(oidp, &value, 0, req);
346 if (error != 0 || req->newptr == NULL)
348 mtx_lock(&rbreqlock);
349 if (arg1 == &hirunningspace) {
350 if (value < lorunningspace)
353 hirunningspace = value;
355 KASSERT(arg1 == &lorunningspace,
356 ("%s: unknown arg1", __func__));
357 if (value > hirunningspace)
360 lorunningspace = value;
362 mtx_unlock(&rbreqlock);
366 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
367 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
369 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
374 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
375 return (sysctl_handle_long(oidp, arg1, arg2, req));
376 lvalue = *(long *)arg1;
377 if (lvalue > INT_MAX)
378 /* On overflow, still write out a long to trigger ENOMEM. */
379 return (sysctl_handle_long(oidp, &lvalue, 0, req));
381 return (sysctl_handle_int(oidp, &ivalue, 0, req));
388 * Return the appropriate queue lock based on the index.
390 static inline struct mtx *
394 if (qindex == QUEUE_DIRTY)
395 return (struct mtx *)(&bqdirty);
396 return (struct mtx *)(&bqclean);
402 * Wakeup any bwillwrite() waiters.
407 mtx_lock(&bdirtylock);
412 mtx_unlock(&bdirtylock);
418 * Decrement the numdirtybuffers count by one and wakeup any
419 * threads blocked in bwillwrite().
425 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
426 (lodirtybuffers + hidirtybuffers) / 2)
433 * Increment the numdirtybuffers count by one and wakeup the buf
441 * Only do the wakeup once as we cross the boundary. The
442 * buf daemon will keep running until the condition clears.
444 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
445 (lodirtybuffers + hidirtybuffers) / 2)
452 * Called when buffer space is potentially available for recovery.
453 * getnewbuf() will block on this flag when it is unable to free
454 * sufficient buffer space. Buffer space becomes recoverable when
455 * bp's get placed back in the queues.
463 * If someone is waiting for bufspace, wake them up. Even
464 * though we may not have freed the kva space yet, the waiting
465 * process will be able to now.
471 if ((on & VFS_BIO_NEED_BUFSPACE) == 0)
474 if (atomic_cmpset_rel_int(&needsbuffer, on,
475 on & ~VFS_BIO_NEED_BUFSPACE))
479 wakeup(__DEVOLATILE(void *, &needsbuffer));
486 * Adjust the reported bufspace for a KVA managed buffer, possibly
487 * waking any waiters.
490 bufspaceadjust(struct buf *bp, int bufsize)
494 KASSERT((bp->b_flags & B_MALLOC) == 0,
495 ("bufspaceadjust: malloc buf %p", bp));
496 diff = bufsize - bp->b_bufsize;
498 atomic_subtract_long(&bufspace, -diff);
501 atomic_add_long(&bufspace, diff);
502 bp->b_bufsize = bufsize;
508 * Adjust the reported bufspace for a malloc managed buffer, possibly
509 * waking any waiters.
512 bufmallocadjust(struct buf *bp, int bufsize)
516 KASSERT((bp->b_flags & B_MALLOC) != 0,
517 ("bufmallocadjust: non-malloc buf %p", bp));
518 diff = bufsize - bp->b_bufsize;
520 atomic_subtract_long(&bufmallocspace, -diff);
523 atomic_add_long(&bufmallocspace, diff);
524 bp->b_bufsize = bufsize;
530 * Wake up processes that are waiting on asynchronous writes to fall
531 * below lorunningspace.
537 mtx_lock(&rbreqlock);
540 wakeup(&runningbufreq);
542 mtx_unlock(&rbreqlock);
548 * Decrement the outstanding write count according.
551 runningbufwakeup(struct buf *bp)
555 bspace = bp->b_runningbufspace;
558 space = atomic_fetchadd_long(&runningbufspace, -bspace);
559 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
561 bp->b_runningbufspace = 0;
563 * Only acquire the lock and wakeup on the transition from exceeding
564 * the threshold to falling below it.
566 if (space < lorunningspace)
568 if (space - bspace > lorunningspace)
576 * Called when a buffer has been added to one of the free queues to
577 * account for the buffer and to wakeup anyone waiting for free buffers.
578 * This typically occurs when large amounts of metadata are being handled
579 * by the buffer cache ( else buffer space runs out first, usually ).
582 bufcountadd(struct buf *bp)
584 int mask, need_wakeup, old, on;
586 KASSERT((bp->b_flags & B_INFREECNT) == 0,
587 ("buf %p already counted as free", bp));
588 bp->b_flags |= B_INFREECNT;
589 old = atomic_fetchadd_int(&numfreebuffers, 1);
590 KASSERT(old >= 0 && old < nbuf,
591 ("numfreebuffers climbed to %d", old + 1));
592 mask = VFS_BIO_NEED_ANY;
593 if (numfreebuffers >= hifreebuffers)
594 mask |= VFS_BIO_NEED_FREE;
602 if (atomic_cmpset_rel_int(&needsbuffer, on, on & ~mask))
606 wakeup(__DEVOLATILE(void *, &needsbuffer));
613 * Decrement the numfreebuffers count as needed.
616 bufcountsub(struct buf *bp)
621 * Fixup numfreebuffers count. If the buffer is invalid or not
622 * delayed-write, the buffer was free and we must decrement
625 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
626 KASSERT((bp->b_flags & B_INFREECNT) != 0,
627 ("buf %p not counted in numfreebuffers", bp));
628 bp->b_flags &= ~B_INFREECNT;
629 old = atomic_fetchadd_int(&numfreebuffers, -1);
630 KASSERT(old > 0, ("numfreebuffers dropped to %d", old - 1));
635 * waitrunningbufspace()
637 * runningbufspace is a measure of the amount of I/O currently
638 * running. This routine is used in async-write situations to
639 * prevent creating huge backups of pending writes to a device.
640 * Only asynchronous writes are governed by this function.
642 * This does NOT turn an async write into a sync write. It waits
643 * for earlier writes to complete and generally returns before the
644 * caller's write has reached the device.
647 waitrunningbufspace(void)
650 mtx_lock(&rbreqlock);
651 while (runningbufspace > hirunningspace) {
653 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
655 mtx_unlock(&rbreqlock);
660 * vfs_buf_test_cache:
662 * Called when a buffer is extended. This function clears the B_CACHE
663 * bit if the newly extended portion of the buffer does not contain
667 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
668 vm_offset_t size, vm_page_t m)
671 VM_OBJECT_ASSERT_LOCKED(m->object);
672 if (bp->b_flags & B_CACHE) {
673 int base = (foff + off) & PAGE_MASK;
674 if (vm_page_is_valid(m, base, size) == 0)
675 bp->b_flags &= ~B_CACHE;
679 /* Wake up the buffer daemon if necessary */
685 if (bd_request == 0) {
693 * bd_speedup - speedup the buffer cache flushing code
702 if (bd_speedupreq == 0 || bd_request == 0)
712 #define NSWBUF_MIN 16
716 #define TRANSIENT_DENOM 5
718 #define TRANSIENT_DENOM 10
722 * Calculating buffer cache scaling values and reserve space for buffer
723 * headers. This is called during low level kernel initialization and
724 * may be called more then once. We CANNOT write to the memory area
725 * being reserved at this time.
728 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
731 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
734 * physmem_est is in pages. Convert it to kilobytes (assumes
735 * PAGE_SIZE is >= 1K)
737 physmem_est = physmem_est * (PAGE_SIZE / 1024);
740 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
741 * For the first 64MB of ram nominally allocate sufficient buffers to
742 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
743 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
744 * the buffer cache we limit the eventual kva reservation to
747 * factor represents the 1/4 x ram conversion.
750 int factor = 4 * BKVASIZE / 1024;
753 if (physmem_est > 4096)
754 nbuf += min((physmem_est - 4096) / factor,
756 if (physmem_est > 65536)
757 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
758 32 * 1024 * 1024 / (factor * 5));
760 if (maxbcache && nbuf > maxbcache / BKVASIZE)
761 nbuf = maxbcache / BKVASIZE;
766 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
767 maxbuf = (LONG_MAX / 3) / BKVASIZE;
770 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
776 * Ideal allocation size for the transient bio submap is 10%
777 * of the maximal space buffer map. This roughly corresponds
778 * to the amount of the buffer mapped for typical UFS load.
780 * Clip the buffer map to reserve space for the transient
781 * BIOs, if its extent is bigger than 90% (80% on i386) of the
782 * maximum buffer map extent on the platform.
784 * The fall-back to the maxbuf in case of maxbcache unset,
785 * allows to not trim the buffer KVA for the architectures
786 * with ample KVA space.
788 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
789 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
790 buf_sz = (long)nbuf * BKVASIZE;
791 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
792 (TRANSIENT_DENOM - 1)) {
794 * There is more KVA than memory. Do not
795 * adjust buffer map size, and assign the rest
796 * of maxbuf to transient map.
798 biotmap_sz = maxbuf_sz - buf_sz;
801 * Buffer map spans all KVA we could afford on
802 * this platform. Give 10% (20% on i386) of
803 * the buffer map to the transient bio map.
805 biotmap_sz = buf_sz / TRANSIENT_DENOM;
806 buf_sz -= biotmap_sz;
808 if (biotmap_sz / INT_MAX > MAXPHYS)
809 bio_transient_maxcnt = INT_MAX;
811 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
813 * Artifically limit to 1024 simultaneous in-flight I/Os
814 * using the transient mapping.
816 if (bio_transient_maxcnt > 1024)
817 bio_transient_maxcnt = 1024;
819 nbuf = buf_sz / BKVASIZE;
823 * swbufs are used as temporary holders for I/O, such as paging I/O.
824 * We have no less then 16 and no more then 256.
826 nswbuf = min(nbuf / 4, 256);
827 TUNABLE_INT_FETCH("kern.nswbuf", &nswbuf);
828 if (nswbuf < NSWBUF_MIN)
832 * Reserve space for the buffer cache buffers
835 v = (caddr_t)(swbuf + nswbuf);
837 v = (caddr_t)(buf + nbuf);
842 /* Initialize the buffer subsystem. Called before use of any buffers. */
849 CTASSERT(MAXBCACHEBUF >= MAXBSIZE);
850 mtx_init(&bqclean, "bufq clean lock", NULL, MTX_DEF);
851 mtx_init(&bqdirty, "bufq dirty lock", NULL, MTX_DEF);
852 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
853 rw_init(&nblock, "needsbuffer lock");
854 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
855 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
857 /* next, make a null set of free lists */
858 for (i = 0; i < BUFFER_QUEUES; i++)
859 TAILQ_INIT(&bufqueues[i]);
861 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
863 /* finally, initialize each buffer header and stick on empty q */
864 for (i = 0; i < nbuf; i++) {
866 bzero(bp, sizeof *bp);
867 bp->b_flags = B_INVAL | B_INFREECNT;
868 bp->b_rcred = NOCRED;
869 bp->b_wcred = NOCRED;
870 bp->b_qindex = QUEUE_EMPTY;
872 bp->b_data = bp->b_kvabase = unmapped_buf;
873 LIST_INIT(&bp->b_dep);
875 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
877 bq_len[QUEUE_EMPTY]++;
882 * maxbufspace is the absolute maximum amount of buffer space we are
883 * allowed to reserve in KVM and in real terms. The absolute maximum
884 * is nominally used by buf_daemon. hibufspace is the nominal maximum
885 * used by most other processes. The differential is required to
886 * ensure that buf_daemon is able to run when other processes might
887 * be blocked waiting for buffer space.
889 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
890 * this may result in KVM fragmentation which is not handled optimally
893 maxbufspace = (long)nbuf * BKVASIZE;
894 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBCACHEBUF * 10);
895 lobufspace = hibufspace - MAXBCACHEBUF;
898 * Note: The 16 MiB upper limit for hirunningspace was chosen
899 * arbitrarily and may need further tuning. It corresponds to
900 * 128 outstanding write IO requests (if IO size is 128 KiB),
901 * which fits with many RAID controllers' tagged queuing limits.
902 * The lower 1 MiB limit is the historical upper limit for
905 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBCACHEBUF),
906 16 * 1024 * 1024), 1024 * 1024);
907 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBCACHEBUF);
910 * Limit the amount of malloc memory since it is wired permanently into
911 * the kernel space. Even though this is accounted for in the buffer
912 * allocation, we don't want the malloced region to grow uncontrolled.
913 * The malloc scheme improves memory utilization significantly on average
914 * (small) directories.
916 maxbufmallocspace = hibufspace / 20;
919 * Reduce the chance of a deadlock occuring by limiting the number
920 * of delayed-write dirty buffers we allow to stack up.
922 hidirtybuffers = nbuf / 4 + 20;
923 dirtybufthresh = hidirtybuffers * 9 / 10;
926 * To support extreme low-memory systems, make sure hidirtybuffers cannot
927 * eat up all available buffer space. This occurs when our minimum cannot
928 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
929 * BKVASIZE'd buffers.
931 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
932 hidirtybuffers >>= 1;
934 lodirtybuffers = hidirtybuffers / 2;
937 * Try to keep the number of free buffers in the specified range,
938 * and give special processes (e.g. like buf_daemon) access to an
941 lofreebuffers = nbuf / 18 + 5;
942 hifreebuffers = 2 * lofreebuffers;
943 numfreebuffers = nbuf;
945 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
946 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
951 vfs_buf_check_mapped(struct buf *bp)
954 KASSERT(bp->b_kvabase != unmapped_buf,
955 ("mapped buf: b_kvabase was not updated %p", bp));
956 KASSERT(bp->b_data != unmapped_buf,
957 ("mapped buf: b_data was not updated %p", bp));
958 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
959 MAXPHYS, ("b_data + b_offset unmapped %p", bp));
963 vfs_buf_check_unmapped(struct buf *bp)
966 KASSERT(bp->b_data == unmapped_buf,
967 ("unmapped buf: corrupted b_data %p", bp));
970 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
971 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
973 #define BUF_CHECK_MAPPED(bp) do {} while (0)
974 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
978 isbufbusy(struct buf *bp)
980 if (((bp->b_flags & (B_INVAL | B_PERSISTENT)) == 0 &&
982 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
988 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
991 bufshutdown(int show_busybufs)
993 static int first_buf_printf = 1;
995 int iter, nbusy, pbusy;
1001 * Sync filesystems for shutdown
1003 wdog_kern_pat(WD_LASTVAL);
1004 sys_sync(curthread, NULL);
1007 * With soft updates, some buffers that are
1008 * written will be remarked as dirty until other
1009 * buffers are written.
1011 for (iter = pbusy = 0; iter < 20; iter++) {
1013 for (bp = &buf[nbuf]; --bp >= buf; )
1017 if (first_buf_printf)
1018 printf("All buffers synced.");
1021 if (first_buf_printf) {
1022 printf("Syncing disks, buffers remaining... ");
1023 first_buf_printf = 0;
1025 printf("%d ", nbusy);
1030 wdog_kern_pat(WD_LASTVAL);
1031 sys_sync(curthread, NULL);
1035 * Drop Giant and spin for a while to allow
1036 * interrupt threads to run.
1039 DELAY(50000 * iter);
1043 * Drop Giant and context switch several times to
1044 * allow interrupt threads to run.
1047 for (subiter = 0; subiter < 50 * iter; subiter++) {
1048 thread_lock(curthread);
1049 mi_switch(SW_VOL, NULL);
1050 thread_unlock(curthread);
1058 * Count only busy local buffers to prevent forcing
1059 * a fsck if we're just a client of a wedged NFS server
1062 for (bp = &buf[nbuf]; --bp >= buf; ) {
1063 if (isbufbusy(bp)) {
1065 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1066 if (bp->b_dev == NULL) {
1067 TAILQ_REMOVE(&mountlist,
1068 bp->b_vp->v_mount, mnt_list);
1073 if (show_busybufs > 0) {
1075 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1076 nbusy, bp, bp->b_vp, bp->b_flags,
1077 (intmax_t)bp->b_blkno,
1078 (intmax_t)bp->b_lblkno);
1079 BUF_LOCKPRINTINFO(bp);
1080 if (show_busybufs > 1)
1088 * Failed to sync all blocks. Indicate this and don't
1089 * unmount filesystems (thus forcing an fsck on reboot).
1091 printf("Giving up on %d buffers\n", nbusy);
1092 DELAY(5000000); /* 5 seconds */
1094 if (!first_buf_printf)
1095 printf("Final sync complete\n");
1097 * Unmount filesystems
1103 DELAY(100000); /* wait for console output to finish */
1107 bpmap_qenter(struct buf *bp)
1110 BUF_CHECK_MAPPED(bp);
1113 * bp->b_data is relative to bp->b_offset, but
1114 * bp->b_offset may be offset into the first page.
1116 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1117 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1118 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1119 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1125 * Insert the buffer into the appropriate free list.
1128 binsfree(struct buf *bp, int qindex)
1130 struct mtx *olock, *nlock;
1132 BUF_ASSERT_XLOCKED(bp);
1134 nlock = bqlock(qindex);
1135 /* Handle delayed bremfree() processing. */
1136 if (bp->b_flags & B_REMFREE) {
1137 olock = bqlock(bp->b_qindex);
1140 if (olock != nlock) {
1147 if (bp->b_qindex != QUEUE_NONE)
1148 panic("binsfree: free buffer onto another queue???");
1150 bp->b_qindex = qindex;
1151 if (bp->b_flags & B_AGE)
1152 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1154 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1156 bq_len[bp->b_qindex]++;
1161 * Something we can maybe free or reuse.
1163 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1166 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))
1173 * Mark the buffer for removal from the appropriate free list.
1177 bremfree(struct buf *bp)
1180 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1181 KASSERT((bp->b_flags & B_REMFREE) == 0,
1182 ("bremfree: buffer %p already marked for delayed removal.", bp));
1183 KASSERT(bp->b_qindex != QUEUE_NONE,
1184 ("bremfree: buffer %p not on a queue.", bp));
1185 BUF_ASSERT_XLOCKED(bp);
1187 bp->b_flags |= B_REMFREE;
1194 * Force an immediate removal from a free list. Used only in nfs when
1195 * it abuses the b_freelist pointer.
1198 bremfreef(struct buf *bp)
1202 qlock = bqlock(bp->b_qindex);
1211 * Removes a buffer from the free list, must be called with the
1212 * correct qlock held.
1215 bremfreel(struct buf *bp)
1218 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1219 bp, bp->b_vp, bp->b_flags);
1220 KASSERT(bp->b_qindex != QUEUE_NONE,
1221 ("bremfreel: buffer %p not on a queue.", bp));
1222 BUF_ASSERT_XLOCKED(bp);
1223 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1225 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1227 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1229 bq_len[bp->b_qindex]--;
1231 bp->b_qindex = QUEUE_NONE;
1233 * If this was a delayed bremfree() we only need to remove the buffer
1234 * from the queue and return the stats are already done.
1236 if (bp->b_flags & B_REMFREE) {
1237 bp->b_flags &= ~B_REMFREE;
1246 * Free the kva allocation for a buffer.
1250 bufkvafree(struct buf *bp)
1254 if (bp->b_kvasize == 0) {
1255 KASSERT(bp->b_kvabase == unmapped_buf &&
1256 bp->b_data == unmapped_buf,
1257 ("Leaked KVA space on %p", bp));
1258 } else if (buf_mapped(bp))
1259 BUF_CHECK_MAPPED(bp);
1261 BUF_CHECK_UNMAPPED(bp);
1263 if (bp->b_kvasize == 0)
1266 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
1267 atomic_subtract_long(&bufkvaspace, bp->b_kvasize);
1268 atomic_add_int(&buffreekvacnt, 1);
1269 bp->b_data = bp->b_kvabase = unmapped_buf;
1276 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
1279 bufkvaalloc(struct buf *bp, int maxsize, int gbflags)
1284 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
1285 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
1290 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
1293 * Buffer map is too fragmented. Request the caller
1294 * to defragment the map.
1296 atomic_add_int(&bufdefragcnt, 1);
1299 bp->b_kvabase = (caddr_t)addr;
1300 bp->b_kvasize = maxsize;
1301 atomic_add_long(&bufkvaspace, bp->b_kvasize);
1302 if ((gbflags & GB_UNMAPPED) != 0) {
1303 bp->b_data = unmapped_buf;
1304 BUF_CHECK_UNMAPPED(bp);
1306 bp->b_data = bp->b_kvabase;
1307 BUF_CHECK_MAPPED(bp);
1313 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1314 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1315 * the buffer is valid and we do not have to do anything.
1318 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1319 int cnt, struct ucred * cred)
1324 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1325 if (inmem(vp, *rablkno))
1327 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1329 if ((rabp->b_flags & B_CACHE) == 0) {
1330 if (!TD_IS_IDLETHREAD(curthread))
1331 curthread->td_ru.ru_inblock++;
1332 rabp->b_flags |= B_ASYNC;
1333 rabp->b_flags &= ~B_INVAL;
1334 rabp->b_ioflags &= ~BIO_ERROR;
1335 rabp->b_iocmd = BIO_READ;
1336 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1337 rabp->b_rcred = crhold(cred);
1338 vfs_busy_pages(rabp, 0);
1340 rabp->b_iooffset = dbtob(rabp->b_blkno);
1349 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1351 * Get a buffer with the specified data. Look in the cache first. We
1352 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1353 * is set, the buffer is valid and we do not have to do anything, see
1354 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1357 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1358 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1361 int rv = 0, readwait = 0;
1363 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1365 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1367 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1371 /* if not found in cache, do some I/O */
1372 if ((bp->b_flags & B_CACHE) == 0) {
1373 if (!TD_IS_IDLETHREAD(curthread))
1374 curthread->td_ru.ru_inblock++;
1375 bp->b_iocmd = BIO_READ;
1376 bp->b_flags &= ~B_INVAL;
1377 bp->b_ioflags &= ~BIO_ERROR;
1378 if (bp->b_rcred == NOCRED && cred != NOCRED)
1379 bp->b_rcred = crhold(cred);
1380 vfs_busy_pages(bp, 0);
1381 bp->b_iooffset = dbtob(bp->b_blkno);
1386 breada(vp, rablkno, rabsize, cnt, cred);
1395 * Write, release buffer on completion. (Done by iodone
1396 * if async). Do not bother writing anything if the buffer
1399 * Note that we set B_CACHE here, indicating that buffer is
1400 * fully valid and thus cacheable. This is true even of NFS
1401 * now so we set it generally. This could be set either here
1402 * or in biodone() since the I/O is synchronous. We put it
1406 bufwrite(struct buf *bp)
1413 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1414 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
1415 bp->b_flags |= B_INVAL | B_RELBUF;
1416 bp->b_flags &= ~B_CACHE;
1420 if (bp->b_flags & B_INVAL) {
1425 if (bp->b_flags & B_BARRIER)
1428 oldflags = bp->b_flags;
1430 BUF_ASSERT_HELD(bp);
1432 if (bp->b_pin_count > 0)
1435 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1436 ("FFS background buffer should not get here %p", bp));
1440 vp_md = vp->v_vflag & VV_MD;
1445 * Mark the buffer clean. Increment the bufobj write count
1446 * before bundirty() call, to prevent other thread from seeing
1447 * empty dirty list and zero counter for writes in progress,
1448 * falsely indicating that the bufobj is clean.
1450 bufobj_wref(bp->b_bufobj);
1453 bp->b_flags &= ~B_DONE;
1454 bp->b_ioflags &= ~BIO_ERROR;
1455 bp->b_flags |= B_CACHE;
1456 bp->b_iocmd = BIO_WRITE;
1458 vfs_busy_pages(bp, 1);
1461 * Normal bwrites pipeline writes
1463 bp->b_runningbufspace = bp->b_bufsize;
1464 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1466 if (!TD_IS_IDLETHREAD(curthread))
1467 curthread->td_ru.ru_oublock++;
1468 if (oldflags & B_ASYNC)
1470 bp->b_iooffset = dbtob(bp->b_blkno);
1473 if ((oldflags & B_ASYNC) == 0) {
1474 int rtval = bufwait(bp);
1477 } else if (space > hirunningspace) {
1479 * don't allow the async write to saturate the I/O
1480 * system. We will not deadlock here because
1481 * we are blocking waiting for I/O that is already in-progress
1482 * to complete. We do not block here if it is the update
1483 * or syncer daemon trying to clean up as that can lead
1486 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1487 waitrunningbufspace();
1494 bufbdflush(struct bufobj *bo, struct buf *bp)
1498 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1499 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1501 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1504 * Try to find a buffer to flush.
1506 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1507 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1509 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1512 panic("bdwrite: found ourselves");
1514 /* Don't countdeps with the bo lock held. */
1515 if (buf_countdeps(nbp, 0)) {
1520 if (nbp->b_flags & B_CLUSTEROK) {
1521 vfs_bio_awrite(nbp);
1526 dirtybufferflushes++;
1535 * Delayed write. (Buffer is marked dirty). Do not bother writing
1536 * anything if the buffer is marked invalid.
1538 * Note that since the buffer must be completely valid, we can safely
1539 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1540 * biodone() in order to prevent getblk from writing the buffer
1541 * out synchronously.
1544 bdwrite(struct buf *bp)
1546 struct thread *td = curthread;
1550 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1551 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1552 KASSERT((bp->b_flags & B_BARRIER) == 0,
1553 ("Barrier request in delayed write %p", bp));
1554 BUF_ASSERT_HELD(bp);
1556 if (bp->b_flags & B_INVAL) {
1562 * If we have too many dirty buffers, don't create any more.
1563 * If we are wildly over our limit, then force a complete
1564 * cleanup. Otherwise, just keep the situation from getting
1565 * out of control. Note that we have to avoid a recursive
1566 * disaster and not try to clean up after our own cleanup!
1570 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
1571 td->td_pflags |= TDP_INBDFLUSH;
1573 td->td_pflags &= ~TDP_INBDFLUSH;
1579 * Set B_CACHE, indicating that the buffer is fully valid. This is
1580 * true even of NFS now.
1582 bp->b_flags |= B_CACHE;
1585 * This bmap keeps the system from needing to do the bmap later,
1586 * perhaps when the system is attempting to do a sync. Since it
1587 * is likely that the indirect block -- or whatever other datastructure
1588 * that the filesystem needs is still in memory now, it is a good
1589 * thing to do this. Note also, that if the pageout daemon is
1590 * requesting a sync -- there might not be enough memory to do
1591 * the bmap then... So, this is important to do.
1593 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
1594 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
1598 * Set the *dirty* buffer range based upon the VM system dirty
1601 * Mark the buffer pages as clean. We need to do this here to
1602 * satisfy the vnode_pager and the pageout daemon, so that it
1603 * thinks that the pages have been "cleaned". Note that since
1604 * the pages are in a delayed write buffer -- the VFS layer
1605 * "will" see that the pages get written out on the next sync,
1606 * or perhaps the cluster will be completed.
1608 vfs_clean_pages_dirty_buf(bp);
1612 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1613 * due to the softdep code.
1620 * Turn buffer into delayed write request. We must clear BIO_READ and
1621 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
1622 * itself to properly update it in the dirty/clean lists. We mark it
1623 * B_DONE to ensure that any asynchronization of the buffer properly
1624 * clears B_DONE ( else a panic will occur later ).
1626 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
1627 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
1628 * should only be called if the buffer is known-good.
1630 * Since the buffer is not on a queue, we do not update the numfreebuffers
1633 * The buffer must be on QUEUE_NONE.
1636 bdirty(struct buf *bp)
1639 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
1640 bp, bp->b_vp, bp->b_flags);
1641 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1642 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1643 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1644 BUF_ASSERT_HELD(bp);
1645 bp->b_flags &= ~(B_RELBUF);
1646 bp->b_iocmd = BIO_WRITE;
1648 if ((bp->b_flags & B_DELWRI) == 0) {
1649 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
1658 * Clear B_DELWRI for buffer.
1660 * Since the buffer is not on a queue, we do not update the numfreebuffers
1663 * The buffer must be on QUEUE_NONE.
1667 bundirty(struct buf *bp)
1670 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1671 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1672 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
1673 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
1674 BUF_ASSERT_HELD(bp);
1676 if (bp->b_flags & B_DELWRI) {
1677 bp->b_flags &= ~B_DELWRI;
1682 * Since it is now being written, we can clear its deferred write flag.
1684 bp->b_flags &= ~B_DEFERRED;
1690 * Asynchronous write. Start output on a buffer, but do not wait for
1691 * it to complete. The buffer is released when the output completes.
1693 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1694 * B_INVAL buffers. Not us.
1697 bawrite(struct buf *bp)
1700 bp->b_flags |= B_ASYNC;
1707 * Asynchronous barrier write. Start output on a buffer, but do not
1708 * wait for it to complete. Place a write barrier after this write so
1709 * that this buffer and all buffers written before it are committed to
1710 * the disk before any buffers written after this write are committed
1711 * to the disk. The buffer is released when the output completes.
1714 babarrierwrite(struct buf *bp)
1717 bp->b_flags |= B_ASYNC | B_BARRIER;
1724 * Synchronous barrier write. Start output on a buffer and wait for
1725 * it to complete. Place a write barrier after this write so that
1726 * this buffer and all buffers written before it are committed to
1727 * the disk before any buffers written after this write are committed
1728 * to the disk. The buffer is released when the output completes.
1731 bbarrierwrite(struct buf *bp)
1734 bp->b_flags |= B_BARRIER;
1735 return (bwrite(bp));
1741 * Called prior to the locking of any vnodes when we are expecting to
1742 * write. We do not want to starve the buffer cache with too many
1743 * dirty buffers so we block here. By blocking prior to the locking
1744 * of any vnodes we attempt to avoid the situation where a locked vnode
1745 * prevents the various system daemons from flushing related buffers.
1751 if (numdirtybuffers >= hidirtybuffers) {
1752 mtx_lock(&bdirtylock);
1753 while (numdirtybuffers >= hidirtybuffers) {
1755 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
1758 mtx_unlock(&bdirtylock);
1763 * Return true if we have too many dirty buffers.
1766 buf_dirty_count_severe(void)
1769 return(numdirtybuffers >= hidirtybuffers);
1775 * Release a busy buffer and, if requested, free its resources. The
1776 * buffer will be stashed in the appropriate bufqueue[] allowing it
1777 * to be accessed later as a cache entity or reused for other purposes.
1780 brelse(struct buf *bp)
1784 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
1785 bp, bp->b_vp, bp->b_flags);
1786 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1787 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1788 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
1789 ("brelse: non-VMIO buffer marked NOREUSE"));
1791 if (BUF_LOCKRECURSED(bp)) {
1793 * Do not process, in particular, do not handle the
1794 * B_INVAL/B_RELBUF and do not release to free list.
1800 if (bp->b_flags & B_MANAGED) {
1805 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
1806 BO_LOCK(bp->b_bufobj);
1807 bp->b_vflags &= ~BV_BKGRDERR;
1808 BO_UNLOCK(bp->b_bufobj);
1811 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
1812 bp->b_error == EIO && !(bp->b_flags & B_INVAL)) {
1814 * Failed write, redirty. Must clear BIO_ERROR to prevent
1815 * pages from being scrapped. If the error is anything
1816 * other than an I/O error (EIO), assume that retrying
1819 bp->b_ioflags &= ~BIO_ERROR;
1821 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
1822 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
1824 * Either a failed I/O or we were asked to free or not
1827 bp->b_flags |= B_INVAL;
1828 if (!LIST_EMPTY(&bp->b_dep))
1830 if (bp->b_flags & B_DELWRI)
1832 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1833 if ((bp->b_flags & B_VMIO) == 0) {
1841 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
1842 * is called with B_DELWRI set, the underlying pages may wind up
1843 * getting freed causing a previous write (bdwrite()) to get 'lost'
1844 * because pages associated with a B_DELWRI bp are marked clean.
1846 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
1847 * if B_DELWRI is set.
1849 if (bp->b_flags & B_DELWRI)
1850 bp->b_flags &= ~B_RELBUF;
1853 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1854 * constituted, not even NFS buffers now. Two flags effect this. If
1855 * B_INVAL, the struct buf is invalidated but the VM object is kept
1856 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1858 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
1859 * invalidated. BIO_ERROR cannot be set for a failed write unless the
1860 * buffer is also B_INVAL because it hits the re-dirtying code above.
1862 * Normally we can do this whether a buffer is B_DELWRI or not. If
1863 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1864 * the commit state and we cannot afford to lose the buffer. If the
1865 * buffer has a background write in progress, we need to keep it
1866 * around to prevent it from being reconstituted and starting a second
1869 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
1870 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
1871 !(bp->b_vp->v_mount != NULL &&
1872 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
1873 !vn_isdisk(bp->b_vp, NULL) && (bp->b_flags & B_DELWRI))) {
1874 vfs_vmio_invalidate(bp);
1878 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
1879 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
1881 bp->b_flags &= ~B_NOREUSE;
1882 if (bp->b_vp != NULL)
1887 * If the buffer has junk contents signal it and eventually
1888 * clean up B_DELWRI and diassociate the vnode so that gbincore()
1891 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
1892 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
1893 bp->b_flags |= B_INVAL;
1894 if (bp->b_flags & B_INVAL) {
1895 if (bp->b_flags & B_DELWRI)
1901 /* buffers with no memory */
1902 if (bp->b_bufsize == 0) {
1903 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1904 if (bp->b_vflags & BV_BKGRDINPROG)
1905 panic("losing buffer 1");
1907 qindex = QUEUE_EMPTY;
1908 bp->b_flags |= B_AGE;
1909 /* buffers with junk contents */
1910 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
1911 (bp->b_ioflags & BIO_ERROR)) {
1912 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
1913 if (bp->b_vflags & BV_BKGRDINPROG)
1914 panic("losing buffer 2");
1915 qindex = QUEUE_CLEAN;
1916 bp->b_flags |= B_AGE;
1917 /* remaining buffers */
1918 } else if (bp->b_flags & B_DELWRI)
1919 qindex = QUEUE_DIRTY;
1921 qindex = QUEUE_CLEAN;
1923 binsfree(bp, qindex);
1925 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
1926 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
1927 panic("brelse: not dirty");
1933 * Release a buffer back to the appropriate queue but do not try to free
1934 * it. The buffer is expected to be used again soon.
1936 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1937 * biodone() to requeue an async I/O on completion. It is also used when
1938 * known good buffers need to be requeued but we think we may need the data
1941 * XXX we should be able to leave the B_RELBUF hint set on completion.
1944 bqrelse(struct buf *bp)
1948 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1949 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1950 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1952 if (BUF_LOCKRECURSED(bp)) {
1953 /* do not release to free list */
1957 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1959 if (bp->b_flags & B_MANAGED) {
1960 if (bp->b_flags & B_REMFREE)
1965 /* buffers with stale but valid contents */
1966 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
1967 BV_BKGRDERR)) == BV_BKGRDERR) {
1968 BO_LOCK(bp->b_bufobj);
1969 bp->b_vflags &= ~BV_BKGRDERR;
1970 BO_UNLOCK(bp->b_bufobj);
1971 qindex = QUEUE_DIRTY;
1973 if ((bp->b_flags & B_DELWRI) == 0 &&
1974 (bp->b_xflags & BX_VNDIRTY))
1975 panic("bqrelse: not dirty");
1976 if ((bp->b_flags & B_NOREUSE) != 0) {
1980 qindex = QUEUE_CLEAN;
1982 binsfree(bp, qindex);
1990 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
1991 * restore bogus pages.
1994 vfs_vmio_iodone(struct buf *bp)
2000 int bogus, i, iosize;
2002 obj = bp->b_bufobj->bo_object;
2003 KASSERT(obj->paging_in_progress >= bp->b_npages,
2004 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2005 obj->paging_in_progress, bp->b_npages));
2008 KASSERT(vp->v_holdcnt > 0,
2009 ("vfs_vmio_iodone: vnode %p has zero hold count", vp));
2010 KASSERT(vp->v_object != NULL,
2011 ("vfs_vmio_iodone: vnode %p has no vm_object", vp));
2013 foff = bp->b_offset;
2014 KASSERT(bp->b_offset != NOOFFSET,
2015 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2018 iosize = bp->b_bcount - bp->b_resid;
2019 VM_OBJECT_WLOCK(obj);
2020 for (i = 0; i < bp->b_npages; i++) {
2023 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2028 * cleanup bogus pages, restoring the originals
2031 if (m == bogus_page) {
2033 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2035 panic("biodone: page disappeared!");
2037 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2039 * In the write case, the valid and clean bits are
2040 * already changed correctly ( see bdwrite() ), so we
2041 * only need to do this here in the read case.
2043 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2044 resid)) == 0, ("vfs_vmio_iodone: page %p "
2045 "has unexpected dirty bits", m));
2046 vfs_page_set_valid(bp, foff, m);
2048 KASSERT(OFF_TO_IDX(foff) == m->pindex,
2049 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
2050 (intmax_t)foff, (uintmax_t)m->pindex));
2053 vm_object_pip_subtract(obj, 1);
2054 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2057 vm_object_pip_wakeupn(obj, 0);
2058 VM_OBJECT_WUNLOCK(obj);
2059 if (bogus && buf_mapped(bp)) {
2060 BUF_CHECK_MAPPED(bp);
2061 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2062 bp->b_pages, bp->b_npages);
2067 * Unwire a page held by a buf and place it on the appropriate vm queue.
2070 vfs_vmio_unwire(struct buf *bp, vm_page_t m)
2075 if (vm_page_unwire(m, PQ_NONE)) {
2077 * Determine if the page should be freed before adding
2078 * it to the inactive queue.
2080 if (m->valid == 0) {
2081 freed = !vm_page_busied(m);
2084 } else if ((bp->b_flags & B_DIRECT) != 0)
2085 freed = vm_page_try_to_free(m);
2090 * If the page is unlikely to be reused, let the
2091 * VM know. Otherwise, maintain LRU page
2092 * ordering and put the page at the tail of the
2095 if ((bp->b_flags & B_NOREUSE) != 0)
2096 vm_page_deactivate_noreuse(m);
2098 vm_page_deactivate(m);
2105 * Perform page invalidation when a buffer is released. The fully invalid
2106 * pages will be reclaimed later in vfs_vmio_truncate().
2109 vfs_vmio_invalidate(struct buf *bp)
2113 int i, resid, poffset, presid;
2115 if (buf_mapped(bp)) {
2116 BUF_CHECK_MAPPED(bp);
2117 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
2119 BUF_CHECK_UNMAPPED(bp);
2121 * Get the base offset and length of the buffer. Note that
2122 * in the VMIO case if the buffer block size is not
2123 * page-aligned then b_data pointer may not be page-aligned.
2124 * But our b_pages[] array *IS* page aligned.
2126 * block sizes less then DEV_BSIZE (usually 512) are not
2127 * supported due to the page granularity bits (m->valid,
2128 * m->dirty, etc...).
2130 * See man buf(9) for more information
2132 obj = bp->b_bufobj->bo_object;
2133 resid = bp->b_bufsize;
2134 poffset = bp->b_offset & PAGE_MASK;
2135 VM_OBJECT_WLOCK(obj);
2136 for (i = 0; i < bp->b_npages; i++) {
2138 if (m == bogus_page)
2139 panic("vfs_vmio_invalidate: Unexpected bogus page.");
2140 bp->b_pages[i] = NULL;
2142 presid = resid > (PAGE_SIZE - poffset) ?
2143 (PAGE_SIZE - poffset) : resid;
2144 KASSERT(presid >= 0, ("brelse: extra page"));
2145 while (vm_page_xbusied(m)) {
2147 VM_OBJECT_WUNLOCK(obj);
2148 vm_page_busy_sleep(m, "mbncsh");
2149 VM_OBJECT_WLOCK(obj);
2151 if (pmap_page_wired_mappings(m) == 0)
2152 vm_page_set_invalid(m, poffset, presid);
2153 vfs_vmio_unwire(bp, m);
2157 VM_OBJECT_WUNLOCK(obj);
2162 * Page-granular truncation of an existing VMIO buffer.
2165 vfs_vmio_truncate(struct buf *bp, int desiredpages)
2171 if (bp->b_npages == desiredpages)
2174 if (buf_mapped(bp)) {
2175 BUF_CHECK_MAPPED(bp);
2176 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
2177 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
2179 BUF_CHECK_UNMAPPED(bp);
2180 obj = bp->b_bufobj->bo_object;
2182 VM_OBJECT_WLOCK(obj);
2183 for (i = desiredpages; i < bp->b_npages; i++) {
2185 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
2186 bp->b_pages[i] = NULL;
2187 vfs_vmio_unwire(bp, m);
2190 VM_OBJECT_WUNLOCK(obj);
2191 bp->b_npages = desiredpages;
2195 * Byte granular extension of VMIO buffers.
2198 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
2201 * We are growing the buffer, possibly in a
2202 * byte-granular fashion.
2210 * Step 1, bring in the VM pages from the object, allocating
2211 * them if necessary. We must clear B_CACHE if these pages
2212 * are not valid for the range covered by the buffer.
2214 obj = bp->b_bufobj->bo_object;
2215 VM_OBJECT_WLOCK(obj);
2216 while (bp->b_npages < desiredpages) {
2218 * We must allocate system pages since blocking
2219 * here could interfere with paging I/O, no
2220 * matter which process we are.
2222 * Only exclusive busy can be tested here.
2223 * Blocking on shared busy might lead to
2224 * deadlocks once allocbuf() is called after
2225 * pages are vfs_busy_pages().
2227 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) + bp->b_npages,
2228 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2229 VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY |
2230 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
2232 bp->b_flags &= ~B_CACHE;
2233 bp->b_pages[bp->b_npages] = m;
2238 * Step 2. We've loaded the pages into the buffer,
2239 * we have to figure out if we can still have B_CACHE
2240 * set. Note that B_CACHE is set according to the
2241 * byte-granular range ( bcount and size ), not the
2242 * aligned range ( newbsize ).
2244 * The VM test is against m->valid, which is DEV_BSIZE
2245 * aligned. Needless to say, the validity of the data
2246 * needs to also be DEV_BSIZE aligned. Note that this
2247 * fails with NFS if the server or some other client
2248 * extends the file's EOF. If our buffer is resized,
2249 * B_CACHE may remain set! XXX
2251 toff = bp->b_bcount;
2252 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2253 while ((bp->b_flags & B_CACHE) && toff < size) {
2256 if (tinc > (size - toff))
2258 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
2259 m = bp->b_pages[pi];
2260 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
2264 VM_OBJECT_WUNLOCK(obj);
2267 * Step 3, fixup the KVA pmap.
2272 BUF_CHECK_UNMAPPED(bp);
2276 * Check to see if a block at a particular lbn is available for a clustered
2280 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
2287 /* If the buf isn't in core skip it */
2288 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
2291 /* If the buf is busy we don't want to wait for it */
2292 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2295 /* Only cluster with valid clusterable delayed write buffers */
2296 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
2297 (B_DELWRI | B_CLUSTEROK))
2300 if (bpa->b_bufsize != size)
2304 * Check to see if it is in the expected place on disk and that the
2305 * block has been mapped.
2307 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
2317 * Implement clustered async writes for clearing out B_DELWRI buffers.
2318 * This is much better then the old way of writing only one buffer at
2319 * a time. Note that we may not be presented with the buffers in the
2320 * correct order, so we search for the cluster in both directions.
2323 vfs_bio_awrite(struct buf *bp)
2328 daddr_t lblkno = bp->b_lblkno;
2329 struct vnode *vp = bp->b_vp;
2337 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
2339 * right now we support clustered writing only to regular files. If
2340 * we find a clusterable block we could be in the middle of a cluster
2341 * rather then at the beginning.
2343 if ((vp->v_type == VREG) &&
2344 (vp->v_mount != 0) && /* Only on nodes that have the size info */
2345 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2347 size = vp->v_mount->mnt_stat.f_iosize;
2348 maxcl = MAXPHYS / size;
2351 for (i = 1; i < maxcl; i++)
2352 if (vfs_bio_clcheck(vp, size, lblkno + i,
2353 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2356 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2357 if (vfs_bio_clcheck(vp, size, lblkno - j,
2358 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2364 * this is a possible cluster write
2368 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2374 bp->b_flags |= B_ASYNC;
2376 * default (old) behavior, writing out only one block
2378 * XXX returns b_bufsize instead of b_bcount for nwritten?
2380 nwritten = bp->b_bufsize;
2387 * Ask the bufdaemon for help, or act as bufdaemon itself, when a
2388 * locked vnode is supplied.
2391 getnewbuf_bufd_help(struct vnode *vp, int gbflags, int slpflag, int slptimeo,
2396 int error, fl, flags, norunbuf;
2398 mtx_assert(&bqclean, MA_OWNED);
2401 flags = VFS_BIO_NEED_BUFSPACE;
2403 } else if (bufspace >= hibufspace) {
2405 flags = VFS_BIO_NEED_BUFSPACE;
2408 flags = VFS_BIO_NEED_ANY;
2410 atomic_set_int(&needsbuffer, flags);
2411 mtx_unlock(&bqclean);
2413 bd_speedup(); /* heeeelp */
2414 if ((gbflags & GB_NOWAIT_BD) != 0)
2419 while ((needsbuffer & flags) != 0) {
2420 if (vp != NULL && vp->v_type != VCHR &&
2421 (td->td_pflags & TDP_BUFNEED) == 0) {
2422 rw_wunlock(&nblock);
2424 * getblk() is called with a vnode locked, and
2425 * some majority of the dirty buffers may as
2426 * well belong to the vnode. Flushing the
2427 * buffers there would make a progress that
2428 * cannot be achieved by the buf_daemon, that
2429 * cannot lock the vnode.
2431 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
2432 (td->td_pflags & TDP_NORUNNINGBUF);
2435 * Play bufdaemon. The getnewbuf() function
2436 * may be called while the thread owns lock
2437 * for another dirty buffer for the same
2438 * vnode, which makes it impossible to use
2439 * VOP_FSYNC() there, due to the buffer lock
2442 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
2443 fl = buf_flush(vp, flushbufqtarget);
2444 td->td_pflags &= norunbuf;
2448 if ((needsbuffer & flags) == 0)
2451 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
2452 (PRIBIO + 4) | slpflag, waitmsg, slptimeo);
2456 rw_wunlock(&nblock);
2460 getnewbuf_reuse_bp(struct buf *bp, int qindex)
2463 CTR6(KTR_BUF, "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d "
2464 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags,
2465 bp->b_kvasize, bp->b_bufsize, qindex);
2466 mtx_assert(&bqclean, MA_NOTOWNED);
2469 * Note: we no longer distinguish between VMIO and non-VMIO
2472 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
2473 ("invalid buffer %p flags %#x found in queue %d", bp, bp->b_flags,
2477 * When recycling a clean buffer we have to truncate it and
2478 * release the vnode.
2480 if (qindex == QUEUE_CLEAN) {
2482 if (bp->b_vp != NULL)
2487 * Get the rest of the buffer freed up. b_kva* is still valid
2488 * after this operation.
2490 if (bp->b_rcred != NOCRED) {
2491 crfree(bp->b_rcred);
2492 bp->b_rcred = NOCRED;
2494 if (bp->b_wcred != NOCRED) {
2495 crfree(bp->b_wcred);
2496 bp->b_wcred = NOCRED;
2498 if (!LIST_EMPTY(&bp->b_dep))
2500 if (bp->b_vflags & BV_BKGRDINPROG)
2501 panic("losing buffer 3");
2502 KASSERT(bp->b_vp == NULL, ("bp: %p still has vnode %p. qindex: %d",
2503 bp, bp->b_vp, qindex));
2504 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
2505 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
2506 KASSERT(bp->b_npages == 0,
2507 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
2512 KASSERT((bp->b_flags & B_INFREECNT) == 0,
2513 ("buf %p still counted as free?", bp));
2516 bp->b_blkno = bp->b_lblkno = 0;
2517 bp->b_offset = NOOFFSET;
2523 bp->b_dirtyoff = bp->b_dirtyend = 0;
2524 bp->b_bufobj = NULL;
2525 bp->b_pin_count = 0;
2526 bp->b_data = bp->b_kvabase;
2527 bp->b_fsprivate1 = NULL;
2528 bp->b_fsprivate2 = NULL;
2529 bp->b_fsprivate3 = NULL;
2531 LIST_INIT(&bp->b_dep);
2535 getnewbuf_scan(int maxsize, int defrag, int unmapped, int metadata)
2537 struct buf *bp, *nbp;
2538 int nqindex, qindex, pass;
2540 KASSERT(!unmapped || !defrag, ("both unmapped and defrag"));
2545 atomic_add_int(&getnewbufrestarts, 1);
2550 * If we're not defragging or low on bufspace attempt to make a new
2551 * buf from a header.
2553 if (defrag == 0 && bufspace + maxsize < hibufspace) {
2554 nqindex = QUEUE_EMPTY;
2555 nbp = TAILQ_FIRST(&bufqueues[nqindex]);
2558 * All available buffers might be clean or we need to start recycling.
2561 nqindex = QUEUE_CLEAN;
2562 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
2566 * Run scan, possibly freeing data and/or kva mappings on the fly
2569 while ((bp = nbp) != NULL) {
2573 * Calculate next bp (we can only use it if we do not
2574 * release the bqlock)
2576 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
2579 nqindex = QUEUE_CLEAN;
2580 nbp = TAILQ_FIRST(&bufqueues[nqindex]);
2585 if (metadata && pass == 0) {
2587 nqindex = QUEUE_EMPTY;
2588 nbp = TAILQ_FIRST(&bufqueues[nqindex]);
2597 * If we are defragging then we need a buffer with
2598 * b_kvasize != 0. This situation occurs when we
2599 * have many unmapped bufs.
2601 if (defrag && bp->b_kvasize == 0)
2605 * Start freeing the bp. This is somewhat involved. nbp
2606 * remains valid only for QUEUE_EMPTY[KVA] bp's.
2608 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2611 * BKGRDINPROG can only be set with the buf and bufobj
2612 * locks both held. We tolerate a race to clear it here.
2614 if (bp->b_vflags & BV_BKGRDINPROG) {
2620 * Requeue the background write buffer with error.
2622 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
2624 mtx_unlock(&bqclean);
2629 KASSERT(bp->b_qindex == qindex,
2630 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2633 mtx_unlock(&bqclean);
2636 * NOTE: nbp is now entirely invalid. We can only restart
2637 * the scan from this point on.
2639 getnewbuf_reuse_bp(bp, qindex);
2640 mtx_assert(&bqclean, MA_NOTOWNED);
2643 * If we are defragging then free the buffer.
2646 bp->b_flags |= B_INVAL;
2653 * Notify any waiters for the buffer lock about
2654 * identity change by freeing the buffer.
2656 if (qindex == QUEUE_CLEAN && BUF_LOCKWAITERS(bp)) {
2657 bp->b_flags |= B_INVAL;
2666 * If we are overcomitted then recover the buffer and its
2667 * KVM space. This occurs in rare situations when multiple
2668 * processes are blocked in getnewbuf() or allocbuf().
2670 if (bufspace >= hibufspace && bp->b_kvasize != 0) {
2671 bp->b_flags |= B_INVAL;
2683 * Find and initialize a new buffer header, freeing up existing buffers
2684 * in the bufqueues as necessary. The new buffer is returned locked.
2686 * Important: B_INVAL is not set. If the caller wishes to throw the
2687 * buffer away, the caller must set B_INVAL prior to calling brelse().
2690 * We have insufficient buffer headers
2691 * We have insufficient buffer space
2692 * buffer_arena is too fragmented ( space reservation fails )
2693 * If we have to flush dirty buffers ( but we try to avoid this )
2696 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int size, int maxsize,
2700 int defrag, metadata;
2702 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2703 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2704 if (!unmapped_buf_allowed)
2705 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2708 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2714 * We can't afford to block since we might be holding a vnode lock,
2715 * which may prevent system daemons from running. We deal with
2716 * low-memory situations by proactively returning memory and running
2717 * async I/O rather then sync I/O.
2719 atomic_add_int(&getnewbufcalls, 1);
2721 bp = getnewbuf_scan(maxsize, defrag, (gbflags & (GB_UNMAPPED |
2722 GB_KVAALLOC)) == GB_UNMAPPED, metadata);
2727 * If we exhausted our list, sleep as appropriate. We may have to
2728 * wakeup various daemons and write out some dirty buffers.
2730 * Generally we are sleeping due to insufficient buffer space.
2733 mtx_assert(&bqclean, MA_OWNED);
2734 getnewbuf_bufd_help(vp, gbflags, slpflag, slptimeo, defrag);
2735 mtx_assert(&bqclean, MA_NOTOWNED);
2736 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) == GB_UNMAPPED) {
2737 mtx_assert(&bqclean, MA_NOTOWNED);
2740 atomic_add_int(&bufreusecnt, 1);
2742 mtx_assert(&bqclean, MA_NOTOWNED);
2745 * We finally have a valid bp. We aren't quite out of the
2746 * woods, we still have to reserve kva space. In order to
2747 * keep fragmentation sane we only allocate kva in BKVASIZE
2750 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2752 if (maxsize != bp->b_kvasize &&
2753 bufkvaalloc(bp, maxsize, gbflags)) {
2755 bp->b_flags |= B_INVAL;
2758 } else if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) ==
2759 (GB_UNMAPPED | GB_KVAALLOC)) {
2760 bp->b_data = unmapped_buf;
2761 BUF_CHECK_UNMAPPED(bp);
2763 atomic_add_int(&bufreusecnt, 1);
2771 * buffer flushing daemon. Buffers are normally flushed by the
2772 * update daemon but if it cannot keep up this process starts to
2773 * take the load in an attempt to prevent getnewbuf() from blocking.
2776 static struct kproc_desc buf_kp = {
2781 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2784 buf_flush(struct vnode *vp, int target)
2788 flushed = flushbufqueues(vp, target, 0);
2791 * Could not find any buffers without rollback
2792 * dependencies, so just write the first one
2793 * in the hopes of eventually making progress.
2795 if (vp != NULL && target > 2)
2797 flushbufqueues(vp, target, 1);
2808 * This process needs to be suspended prior to shutdown sync.
2810 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2814 * This process is allowed to take the buffer cache to the limit
2816 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
2820 mtx_unlock(&bdlock);
2822 kproc_suspend_check(bufdaemonproc);
2823 lodirty = lodirtybuffers;
2824 if (bd_speedupreq) {
2825 lodirty = numdirtybuffers / 2;
2829 * Do the flush. Limit the amount of in-transit I/O we
2830 * allow to build up, otherwise we would completely saturate
2833 while (numdirtybuffers > lodirty) {
2834 if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
2836 kern_yield(PRI_USER);
2840 * Only clear bd_request if we have reached our low water
2841 * mark. The buf_daemon normally waits 1 second and
2842 * then incrementally flushes any dirty buffers that have
2843 * built up, within reason.
2845 * If we were unable to hit our low water mark and couldn't
2846 * find any flushable buffers, we sleep for a short period
2847 * to avoid endless loops on unlockable buffers.
2850 if (numdirtybuffers <= lodirtybuffers) {
2852 * We reached our low water mark, reset the
2853 * request and sleep until we are needed again.
2854 * The sleep is just so the suspend code works.
2858 * Do an extra wakeup in case dirty threshold
2859 * changed via sysctl and the explicit transition
2860 * out of shortfall was missed.
2863 if (runningbufspace <= lorunningspace)
2865 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
2868 * We couldn't find any flushable dirty buffers but
2869 * still have too many dirty buffers, we
2870 * have to sleep and try again. (rare)
2872 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
2880 * Try to flush a buffer in the dirty queue. We must be careful to
2881 * free up B_INVAL buffers instead of write them, which NFS is
2882 * particularly sensitive to.
2884 static int flushwithdeps = 0;
2885 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
2886 0, "Number of buffers flushed with dependecies that require rollbacks");
2889 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
2891 struct buf *sentinel;
2902 queue = QUEUE_DIRTY;
2904 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
2905 sentinel->b_qindex = QUEUE_SENTINEL;
2907 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
2908 mtx_unlock(&bqdirty);
2909 while (flushed != target) {
2912 bp = TAILQ_NEXT(sentinel, b_freelist);
2914 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
2915 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
2918 mtx_unlock(&bqdirty);
2922 * Skip sentinels inserted by other invocations of the
2923 * flushbufqueues(), taking care to not reorder them.
2925 * Only flush the buffers that belong to the
2926 * vnode locked by the curthread.
2928 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
2930 mtx_unlock(&bqdirty);
2933 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
2934 mtx_unlock(&bqdirty);
2937 if (bp->b_pin_count > 0) {
2942 * BKGRDINPROG can only be set with the buf and bufobj
2943 * locks both held. We tolerate a race to clear it here.
2945 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
2946 (bp->b_flags & B_DELWRI) == 0) {
2950 if (bp->b_flags & B_INVAL) {
2957 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
2958 if (flushdeps == 0) {
2966 * We must hold the lock on a vnode before writing
2967 * one of its buffers. Otherwise we may confuse, or
2968 * in the case of a snapshot vnode, deadlock the
2971 * The lock order here is the reverse of the normal
2972 * of vnode followed by buf lock. This is ok because
2973 * the NOWAIT will prevent deadlock.
2976 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2982 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
2984 ASSERT_VOP_LOCKED(vp, "getbuf");
2986 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
2987 vn_lock(vp, LK_TRYUPGRADE);
2990 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
2991 bp, bp->b_vp, bp->b_flags);
2992 if (curproc == bufdaemonproc) {
2999 vn_finished_write(mp);
3002 flushwithdeps += hasdeps;
3006 * Sleeping on runningbufspace while holding
3007 * vnode lock leads to deadlock.
3009 if (curproc == bufdaemonproc &&
3010 runningbufspace > hirunningspace)
3011 waitrunningbufspace();
3014 vn_finished_write(mp);
3018 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3019 mtx_unlock(&bqdirty);
3020 free(sentinel, M_TEMP);
3025 * Check to see if a block is currently memory resident.
3028 incore(struct bufobj *bo, daddr_t blkno)
3033 bp = gbincore(bo, blkno);
3039 * Returns true if no I/O is needed to access the
3040 * associated VM object. This is like incore except
3041 * it also hunts around in the VM system for the data.
3045 inmem(struct vnode * vp, daddr_t blkno)
3048 vm_offset_t toff, tinc, size;
3052 ASSERT_VOP_LOCKED(vp, "inmem");
3054 if (incore(&vp->v_bufobj, blkno))
3056 if (vp->v_mount == NULL)
3063 if (size > vp->v_mount->mnt_stat.f_iosize)
3064 size = vp->v_mount->mnt_stat.f_iosize;
3065 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3067 VM_OBJECT_RLOCK(obj);
3068 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3069 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
3073 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3074 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3075 if (vm_page_is_valid(m,
3076 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
3079 VM_OBJECT_RUNLOCK(obj);
3083 VM_OBJECT_RUNLOCK(obj);
3088 * Set the dirty range for a buffer based on the status of the dirty
3089 * bits in the pages comprising the buffer. The range is limited
3090 * to the size of the buffer.
3092 * Tell the VM system that the pages associated with this buffer
3093 * are clean. This is used for delayed writes where the data is
3094 * going to go to disk eventually without additional VM intevention.
3096 * Note that while we only really need to clean through to b_bcount, we
3097 * just go ahead and clean through to b_bufsize.
3100 vfs_clean_pages_dirty_buf(struct buf *bp)
3102 vm_ooffset_t foff, noff, eoff;
3106 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3109 foff = bp->b_offset;
3110 KASSERT(bp->b_offset != NOOFFSET,
3111 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3113 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3114 vfs_drain_busy_pages(bp);
3115 vfs_setdirty_locked_object(bp);
3116 for (i = 0; i < bp->b_npages; i++) {
3117 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3119 if (eoff > bp->b_offset + bp->b_bufsize)
3120 eoff = bp->b_offset + bp->b_bufsize;
3122 vfs_page_set_validclean(bp, foff, m);
3123 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3126 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3130 vfs_setdirty_locked_object(struct buf *bp)
3135 object = bp->b_bufobj->bo_object;
3136 VM_OBJECT_ASSERT_WLOCKED(object);
3139 * We qualify the scan for modified pages on whether the
3140 * object has been flushed yet.
3142 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
3143 vm_offset_t boffset;
3144 vm_offset_t eoffset;
3147 * test the pages to see if they have been modified directly
3148 * by users through the VM system.
3150 for (i = 0; i < bp->b_npages; i++)
3151 vm_page_test_dirty(bp->b_pages[i]);
3154 * Calculate the encompassing dirty range, boffset and eoffset,
3155 * (eoffset - boffset) bytes.
3158 for (i = 0; i < bp->b_npages; i++) {
3159 if (bp->b_pages[i]->dirty)
3162 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3164 for (i = bp->b_npages - 1; i >= 0; --i) {
3165 if (bp->b_pages[i]->dirty) {
3169 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3172 * Fit it to the buffer.
3175 if (eoffset > bp->b_bcount)
3176 eoffset = bp->b_bcount;
3179 * If we have a good dirty range, merge with the existing
3183 if (boffset < eoffset) {
3184 if (bp->b_dirtyoff > boffset)
3185 bp->b_dirtyoff = boffset;
3186 if (bp->b_dirtyend < eoffset)
3187 bp->b_dirtyend = eoffset;
3193 * Allocate the KVA mapping for an existing buffer.
3194 * If an unmapped buffer is provided but a mapped buffer is requested, take
3195 * also care to properly setup mappings between pages and KVA.
3198 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3200 struct buf *scratch_bp;
3201 int bsize, maxsize, need_mapping, need_kva;
3204 need_mapping = bp->b_data == unmapped_buf &&
3205 (gbflags & GB_UNMAPPED) == 0;
3206 need_kva = bp->b_kvabase == unmapped_buf &&
3207 bp->b_data == unmapped_buf &&
3208 (gbflags & GB_KVAALLOC) != 0;
3209 if (!need_mapping && !need_kva)
3212 BUF_CHECK_UNMAPPED(bp);
3214 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3216 * Buffer is not mapped, but the KVA was already
3217 * reserved at the time of the instantiation. Use the
3224 * Calculate the amount of the address space we would reserve
3225 * if the buffer was mapped.
3227 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3228 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3229 offset = blkno * bsize;
3230 maxsize = size + (offset & PAGE_MASK);
3231 maxsize = imax(maxsize, bsize);
3234 if (bufkvaalloc(bp, maxsize, gbflags)) {
3236 * Request defragmentation. getnewbuf() returns us the
3237 * allocated space by the scratch buffer KVA.
3239 scratch_bp = getnewbuf(bp->b_vp, 0, 0, size, maxsize, gbflags |
3240 (GB_UNMAPPED | GB_KVAALLOC));
3241 if (scratch_bp == NULL) {
3242 if ((gbflags & GB_NOWAIT_BD) != 0) {
3244 * XXXKIB: defragmentation cannot
3245 * succeed, not sure what else to do.
3247 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3249 atomic_add_int(&mappingrestarts, 1);
3252 KASSERT(scratch_bp->b_kvabase != unmapped_buf,
3253 ("scratch bp has no KVA %p", scratch_bp));
3254 /* Grab pointers. */
3255 bp->b_kvabase = scratch_bp->b_kvabase;
3256 bp->b_kvasize = scratch_bp->b_kvasize;
3257 bp->b_data = scratch_bp->b_data;
3259 /* Get rid of the scratch buffer. */
3260 scratch_bp->b_kvasize = 0;
3261 scratch_bp->b_flags |= B_INVAL;
3262 scratch_bp->b_data = scratch_bp->b_kvabase = unmapped_buf;
3267 /* b_offset is handled by bpmap_qenter. */
3268 bp->b_data = bp->b_kvabase;
3269 BUF_CHECK_MAPPED(bp);
3277 * Get a block given a specified block and offset into a file/device.
3278 * The buffers B_DONE bit will be cleared on return, making it almost
3279 * ready for an I/O initiation. B_INVAL may or may not be set on
3280 * return. The caller should clear B_INVAL prior to initiating a
3283 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3284 * an existing buffer.
3286 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3287 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3288 * and then cleared based on the backing VM. If the previous buffer is
3289 * non-0-sized but invalid, B_CACHE will be cleared.
3291 * If getblk() must create a new buffer, the new buffer is returned with
3292 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3293 * case it is returned with B_INVAL clear and B_CACHE set based on the
3296 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3297 * B_CACHE bit is clear.
3299 * What this means, basically, is that the caller should use B_CACHE to
3300 * determine whether the buffer is fully valid or not and should clear
3301 * B_INVAL prior to issuing a read. If the caller intends to validate
3302 * the buffer by loading its data area with something, the caller needs
3303 * to clear B_INVAL. If the caller does this without issuing an I/O,
3304 * the caller should set B_CACHE ( as an optimization ), else the caller
3305 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3306 * a write attempt or if it was a successfull read. If the caller
3307 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3308 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3311 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3316 int bsize, error, maxsize, vmio;
3319 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3320 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3321 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3322 ASSERT_VOP_LOCKED(vp, "getblk");
3323 if (size > MAXBCACHEBUF)
3324 panic("getblk: size(%d) > MAXBCACHEBUF(%d)\n", size,
3326 if (!unmapped_buf_allowed)
3327 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3332 bp = gbincore(bo, blkno);
3336 * Buffer is in-core. If the buffer is not busy nor managed,
3337 * it must be on a queue.
3339 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3341 if (flags & GB_LOCK_NOWAIT)
3342 lockflags |= LK_NOWAIT;
3344 error = BUF_TIMELOCK(bp, lockflags,
3345 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3348 * If we slept and got the lock we have to restart in case
3349 * the buffer changed identities.
3351 if (error == ENOLCK)
3353 /* We timed out or were interrupted. */
3356 /* If recursed, assume caller knows the rules. */
3357 else if (BUF_LOCKRECURSED(bp))
3361 * The buffer is locked. B_CACHE is cleared if the buffer is
3362 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3363 * and for a VMIO buffer B_CACHE is adjusted according to the
3366 if (bp->b_flags & B_INVAL)
3367 bp->b_flags &= ~B_CACHE;
3368 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3369 bp->b_flags |= B_CACHE;
3370 if (bp->b_flags & B_MANAGED)
3371 MPASS(bp->b_qindex == QUEUE_NONE);
3376 * check for size inconsistencies for non-VMIO case.
3378 if (bp->b_bcount != size) {
3379 if ((bp->b_flags & B_VMIO) == 0 ||
3380 (size > bp->b_kvasize)) {
3381 if (bp->b_flags & B_DELWRI) {
3383 * If buffer is pinned and caller does
3384 * not want sleep waiting for it to be
3385 * unpinned, bail out
3387 if (bp->b_pin_count > 0) {
3388 if (flags & GB_LOCK_NOWAIT) {
3395 bp->b_flags |= B_NOCACHE;
3398 if (LIST_EMPTY(&bp->b_dep)) {
3399 bp->b_flags |= B_RELBUF;
3402 bp->b_flags |= B_NOCACHE;
3411 * Handle the case of unmapped buffer which should
3412 * become mapped, or the buffer for which KVA
3413 * reservation is requested.
3415 bp_unmapped_get_kva(bp, blkno, size, flags);
3418 * If the size is inconsistant in the VMIO case, we can resize
3419 * the buffer. This might lead to B_CACHE getting set or
3420 * cleared. If the size has not changed, B_CACHE remains
3421 * unchanged from its previous state.
3425 KASSERT(bp->b_offset != NOOFFSET,
3426 ("getblk: no buffer offset"));
3429 * A buffer with B_DELWRI set and B_CACHE clear must
3430 * be committed before we can return the buffer in
3431 * order to prevent the caller from issuing a read
3432 * ( due to B_CACHE not being set ) and overwriting
3435 * Most callers, including NFS and FFS, need this to
3436 * operate properly either because they assume they
3437 * can issue a read if B_CACHE is not set, or because
3438 * ( for example ) an uncached B_DELWRI might loop due
3439 * to softupdates re-dirtying the buffer. In the latter
3440 * case, B_CACHE is set after the first write completes,
3441 * preventing further loops.
3442 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3443 * above while extending the buffer, we cannot allow the
3444 * buffer to remain with B_CACHE set after the write
3445 * completes or it will represent a corrupt state. To
3446 * deal with this we set B_NOCACHE to scrap the buffer
3449 * We might be able to do something fancy, like setting
3450 * B_CACHE in bwrite() except if B_DELWRI is already set,
3451 * so the below call doesn't set B_CACHE, but that gets real
3452 * confusing. This is much easier.
3455 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3456 bp->b_flags |= B_NOCACHE;
3460 bp->b_flags &= ~B_DONE;
3463 * Buffer is not in-core, create new buffer. The buffer
3464 * returned by getnewbuf() is locked. Note that the returned
3465 * buffer is also considered valid (not marked B_INVAL).
3469 * If the user does not want us to create the buffer, bail out
3472 if (flags & GB_NOCREAT)
3474 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3477 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3478 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3479 offset = blkno * bsize;
3480 vmio = vp->v_object != NULL;
3482 maxsize = size + (offset & PAGE_MASK);
3485 /* Do not allow non-VMIO notmapped buffers. */
3486 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3488 maxsize = imax(maxsize, bsize);
3490 bp = getnewbuf(vp, slpflag, slptimeo, size, maxsize, flags);
3492 if (slpflag || slptimeo)
3498 * This code is used to make sure that a buffer is not
3499 * created while the getnewbuf routine is blocked.
3500 * This can be a problem whether the vnode is locked or not.
3501 * If the buffer is created out from under us, we have to
3502 * throw away the one we just created.
3504 * Note: this must occur before we associate the buffer
3505 * with the vp especially considering limitations in
3506 * the splay tree implementation when dealing with duplicate
3510 if (gbincore(bo, blkno)) {
3512 bp->b_flags |= B_INVAL;
3518 * Insert the buffer into the hash, so that it can
3519 * be found by incore.
3521 bp->b_blkno = bp->b_lblkno = blkno;
3522 bp->b_offset = offset;
3527 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3528 * buffer size starts out as 0, B_CACHE will be set by
3529 * allocbuf() for the VMIO case prior to it testing the
3530 * backing store for validity.
3534 bp->b_flags |= B_VMIO;
3535 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3536 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3537 bp, vp->v_object, bp->b_bufobj->bo_object));
3539 bp->b_flags &= ~B_VMIO;
3540 KASSERT(bp->b_bufobj->bo_object == NULL,
3541 ("ARGH! has b_bufobj->bo_object %p %p\n",
3542 bp, bp->b_bufobj->bo_object));
3543 BUF_CHECK_MAPPED(bp);
3547 bp->b_flags &= ~B_DONE;
3549 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3550 BUF_ASSERT_HELD(bp);
3552 KASSERT(bp->b_bufobj == bo,
3553 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3558 * Get an empty, disassociated buffer of given size. The buffer is initially
3562 geteblk(int size, int flags)
3567 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3568 while ((bp = getnewbuf(NULL, 0, 0, size, maxsize, flags)) == NULL) {
3569 if ((flags & GB_NOWAIT_BD) &&
3570 (curthread->td_pflags & TDP_BUFNEED) != 0)
3574 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3575 BUF_ASSERT_HELD(bp);
3580 * Truncate the backing store for a non-vmio buffer.
3583 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
3586 if (bp->b_flags & B_MALLOC) {
3588 * malloced buffers are not shrunk
3590 if (newbsize == 0) {
3591 bufmallocadjust(bp, 0);
3592 free(bp->b_data, M_BIOBUF);
3593 bp->b_data = bp->b_kvabase;
3594 bp->b_flags &= ~B_MALLOC;
3598 vm_hold_free_pages(bp, newbsize);
3599 bufspaceadjust(bp, newbsize);
3603 * Extend the backing for a non-VMIO buffer.
3606 vfs_nonvmio_extend(struct buf *bp, int newbsize)
3612 * We only use malloced memory on the first allocation.
3613 * and revert to page-allocated memory when the buffer
3616 * There is a potential smp race here that could lead
3617 * to bufmallocspace slightly passing the max. It
3618 * is probably extremely rare and not worth worrying
3621 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
3622 bufmallocspace < maxbufmallocspace) {
3623 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
3624 bp->b_flags |= B_MALLOC;
3625 bufmallocadjust(bp, newbsize);
3630 * If the buffer is growing on its other-than-first
3631 * allocation then we revert to the page-allocation
3636 if (bp->b_flags & B_MALLOC) {
3637 origbuf = bp->b_data;
3638 origbufsize = bp->b_bufsize;
3639 bp->b_data = bp->b_kvabase;
3640 bufmallocadjust(bp, 0);
3641 bp->b_flags &= ~B_MALLOC;
3642 newbsize = round_page(newbsize);
3644 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
3645 (vm_offset_t) bp->b_data + newbsize);
3646 if (origbuf != NULL) {
3647 bcopy(origbuf, bp->b_data, origbufsize);
3648 free(origbuf, M_BIOBUF);
3650 bufspaceadjust(bp, newbsize);
3654 * This code constitutes the buffer memory from either anonymous system
3655 * memory (in the case of non-VMIO operations) or from an associated
3656 * VM object (in the case of VMIO operations). This code is able to
3657 * resize a buffer up or down.
3659 * Note that this code is tricky, and has many complications to resolve
3660 * deadlock or inconsistant data situations. Tread lightly!!!
3661 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3662 * the caller. Calling this code willy nilly can result in the loss of data.
3664 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3665 * B_CACHE for the non-VMIO case.
3668 allocbuf(struct buf *bp, int size)
3672 BUF_ASSERT_HELD(bp);
3674 if (bp->b_bcount == size)
3677 if (bp->b_kvasize != 0 && bp->b_kvasize < size)
3678 panic("allocbuf: buffer too small");
3680 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3681 if ((bp->b_flags & B_VMIO) == 0) {
3682 if ((bp->b_flags & B_MALLOC) == 0)
3683 newbsize = round_page(newbsize);
3685 * Just get anonymous memory from the kernel. Don't
3686 * mess with B_CACHE.
3688 if (newbsize < bp->b_bufsize)
3689 vfs_nonvmio_truncate(bp, newbsize);
3690 else if (newbsize > bp->b_bufsize)
3691 vfs_nonvmio_extend(bp, newbsize);
3695 desiredpages = (size == 0) ? 0 :
3696 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3698 if (bp->b_flags & B_MALLOC)
3699 panic("allocbuf: VMIO buffer can't be malloced");
3701 * Set B_CACHE initially if buffer is 0 length or will become
3704 if (size == 0 || bp->b_bufsize == 0)
3705 bp->b_flags |= B_CACHE;
3707 if (newbsize < bp->b_bufsize)
3708 vfs_vmio_truncate(bp, desiredpages);
3709 /* XXX This looks as if it should be newbsize > b_bufsize */
3710 else if (size > bp->b_bcount)
3711 vfs_vmio_extend(bp, desiredpages, size);
3712 bufspaceadjust(bp, newbsize);
3714 bp->b_bcount = size; /* requested buffer size. */
3718 extern int inflight_transient_maps;
3721 biodone(struct bio *bp)
3724 void (*done)(struct bio *);
3725 vm_offset_t start, end;
3727 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3728 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3729 bp->bio_flags |= BIO_UNMAPPED;
3730 start = trunc_page((vm_offset_t)bp->bio_data);
3731 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3732 bp->bio_data = unmapped_buf;
3733 pmap_qremove(start, OFF_TO_IDX(end - start));
3734 vmem_free(transient_arena, start, end - start);
3735 atomic_add_int(&inflight_transient_maps, -1);
3737 done = bp->bio_done;
3739 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3741 bp->bio_flags |= BIO_DONE;
3745 bp->bio_flags |= BIO_DONE;
3751 * Wait for a BIO to finish.
3754 biowait(struct bio *bp, const char *wchan)
3758 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3760 while ((bp->bio_flags & BIO_DONE) == 0)
3761 msleep(bp, mtxp, PRIBIO, wchan, 0);
3763 if (bp->bio_error != 0)
3764 return (bp->bio_error);
3765 if (!(bp->bio_flags & BIO_ERROR))
3771 biofinish(struct bio *bp, struct devstat *stat, int error)
3775 bp->bio_error = error;
3776 bp->bio_flags |= BIO_ERROR;
3779 devstat_end_transaction_bio(stat, bp);
3786 * Wait for buffer I/O completion, returning error status. The buffer
3787 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3788 * error and cleared.
3791 bufwait(struct buf *bp)
3793 if (bp->b_iocmd == BIO_READ)
3794 bwait(bp, PRIBIO, "biord");
3796 bwait(bp, PRIBIO, "biowr");
3797 if (bp->b_flags & B_EINTR) {
3798 bp->b_flags &= ~B_EINTR;
3801 if (bp->b_ioflags & BIO_ERROR) {
3802 return (bp->b_error ? bp->b_error : EIO);
3811 * Finish I/O on a buffer, optionally calling a completion function.
3812 * This is usually called from an interrupt so process blocking is
3815 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3816 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3817 * assuming B_INVAL is clear.
3819 * For the VMIO case, we set B_CACHE if the op was a read and no
3820 * read error occured, or if the op was a write. B_CACHE is never
3821 * set if the buffer is invalid or otherwise uncacheable.
3823 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3824 * initiator to leave B_INVAL set to brelse the buffer out of existance
3825 * in the biodone routine.
3828 bufdone(struct buf *bp)
3830 struct bufobj *dropobj;
3831 void (*biodone)(struct buf *);
3833 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
3836 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
3837 BUF_ASSERT_HELD(bp);
3839 runningbufwakeup(bp);
3840 if (bp->b_iocmd == BIO_WRITE)
3841 dropobj = bp->b_bufobj;
3842 /* call optional completion function if requested */
3843 if (bp->b_iodone != NULL) {
3844 biodone = bp->b_iodone;
3845 bp->b_iodone = NULL;
3848 bufobj_wdrop(dropobj);
3855 bufobj_wdrop(dropobj);
3859 bufdone_finish(struct buf *bp)
3861 BUF_ASSERT_HELD(bp);
3863 if (!LIST_EMPTY(&bp->b_dep))
3866 if (bp->b_flags & B_VMIO) {
3868 * Set B_CACHE if the op was a normal read and no error
3869 * occured. B_CACHE is set for writes in the b*write()
3872 if (bp->b_iocmd == BIO_READ &&
3873 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
3874 !(bp->b_ioflags & BIO_ERROR))
3875 bp->b_flags |= B_CACHE;
3876 vfs_vmio_iodone(bp);
3880 * For asynchronous completions, release the buffer now. The brelse
3881 * will do a wakeup there if necessary - so no need to do a wakeup
3882 * here in the async case. The sync case always needs to do a wakeup.
3884 if (bp->b_flags & B_ASYNC) {
3885 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
3886 (bp->b_ioflags & BIO_ERROR))
3895 * This routine is called in lieu of iodone in the case of
3896 * incomplete I/O. This keeps the busy status for pages
3900 vfs_unbusy_pages(struct buf *bp)
3906 runningbufwakeup(bp);
3907 if (!(bp->b_flags & B_VMIO))
3910 obj = bp->b_bufobj->bo_object;
3911 VM_OBJECT_WLOCK(obj);
3912 for (i = 0; i < bp->b_npages; i++) {
3914 if (m == bogus_page) {
3915 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3917 panic("vfs_unbusy_pages: page missing\n");
3919 if (buf_mapped(bp)) {
3920 BUF_CHECK_MAPPED(bp);
3921 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3922 bp->b_pages, bp->b_npages);
3924 BUF_CHECK_UNMAPPED(bp);
3926 vm_object_pip_subtract(obj, 1);
3929 vm_object_pip_wakeupn(obj, 0);
3930 VM_OBJECT_WUNLOCK(obj);
3934 * vfs_page_set_valid:
3936 * Set the valid bits in a page based on the supplied offset. The
3937 * range is restricted to the buffer's size.
3939 * This routine is typically called after a read completes.
3942 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3947 * Compute the end offset, eoff, such that [off, eoff) does not span a
3948 * page boundary and eoff is not greater than the end of the buffer.
3949 * The end of the buffer, in this case, is our file EOF, not the
3950 * allocation size of the buffer.
3952 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
3953 if (eoff > bp->b_offset + bp->b_bcount)
3954 eoff = bp->b_offset + bp->b_bcount;
3957 * Set valid range. This is typically the entire buffer and thus the
3961 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
3965 * vfs_page_set_validclean:
3967 * Set the valid bits and clear the dirty bits in a page based on the
3968 * supplied offset. The range is restricted to the buffer's size.
3971 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
3973 vm_ooffset_t soff, eoff;
3976 * Start and end offsets in buffer. eoff - soff may not cross a
3977 * page boundry or cross the end of the buffer. The end of the
3978 * buffer, in this case, is our file EOF, not the allocation size
3982 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3983 if (eoff > bp->b_offset + bp->b_bcount)
3984 eoff = bp->b_offset + bp->b_bcount;
3987 * Set valid range. This is typically the entire buffer and thus the
3991 vm_page_set_validclean(
3993 (vm_offset_t) (soff & PAGE_MASK),
3994 (vm_offset_t) (eoff - soff)
4000 * Ensure that all buffer pages are not exclusive busied. If any page is
4001 * exclusive busy, drain it.
4004 vfs_drain_busy_pages(struct buf *bp)
4009 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4011 for (i = 0; i < bp->b_npages; i++) {
4013 if (vm_page_xbusied(m)) {
4014 for (; last_busied < i; last_busied++)
4015 vm_page_sbusy(bp->b_pages[last_busied]);
4016 while (vm_page_xbusied(m)) {
4018 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4019 vm_page_busy_sleep(m, "vbpage");
4020 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4024 for (i = 0; i < last_busied; i++)
4025 vm_page_sunbusy(bp->b_pages[i]);
4029 * This routine is called before a device strategy routine.
4030 * It is used to tell the VM system that paging I/O is in
4031 * progress, and treat the pages associated with the buffer
4032 * almost as being exclusive busy. Also the object paging_in_progress
4033 * flag is handled to make sure that the object doesn't become
4036 * Since I/O has not been initiated yet, certain buffer flags
4037 * such as BIO_ERROR or B_INVAL may be in an inconsistant state
4038 * and should be ignored.
4041 vfs_busy_pages(struct buf *bp, int clear_modify)
4048 if (!(bp->b_flags & B_VMIO))
4051 obj = bp->b_bufobj->bo_object;
4052 foff = bp->b_offset;
4053 KASSERT(bp->b_offset != NOOFFSET,
4054 ("vfs_busy_pages: no buffer offset"));
4055 VM_OBJECT_WLOCK(obj);
4056 vfs_drain_busy_pages(bp);
4057 if (bp->b_bufsize != 0)
4058 vfs_setdirty_locked_object(bp);
4060 for (i = 0; i < bp->b_npages; i++) {
4063 if ((bp->b_flags & B_CLUSTER) == 0) {
4064 vm_object_pip_add(obj, 1);
4068 * When readying a buffer for a read ( i.e
4069 * clear_modify == 0 ), it is important to do
4070 * bogus_page replacement for valid pages in
4071 * partially instantiated buffers. Partially
4072 * instantiated buffers can, in turn, occur when
4073 * reconstituting a buffer from its VM backing store
4074 * base. We only have to do this if B_CACHE is
4075 * clear ( which causes the I/O to occur in the
4076 * first place ). The replacement prevents the read
4077 * I/O from overwriting potentially dirty VM-backed
4078 * pages. XXX bogus page replacement is, uh, bogus.
4079 * It may not work properly with small-block devices.
4080 * We need to find a better way.
4083 pmap_remove_write(m);
4084 vfs_page_set_validclean(bp, foff, m);
4085 } else if (m->valid == VM_PAGE_BITS_ALL &&
4086 (bp->b_flags & B_CACHE) == 0) {
4087 bp->b_pages[i] = bogus_page;
4090 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4092 VM_OBJECT_WUNLOCK(obj);
4093 if (bogus && buf_mapped(bp)) {
4094 BUF_CHECK_MAPPED(bp);
4095 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4096 bp->b_pages, bp->b_npages);
4101 * vfs_bio_set_valid:
4103 * Set the range within the buffer to valid. The range is
4104 * relative to the beginning of the buffer, b_offset. Note that
4105 * b_offset itself may be offset from the beginning of the first
4109 vfs_bio_set_valid(struct buf *bp, int base, int size)
4114 if (!(bp->b_flags & B_VMIO))
4118 * Fixup base to be relative to beginning of first page.
4119 * Set initial n to be the maximum number of bytes in the
4120 * first page that can be validated.
4122 base += (bp->b_offset & PAGE_MASK);
4123 n = PAGE_SIZE - (base & PAGE_MASK);
4125 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4126 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4130 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4135 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4141 * If the specified buffer is a non-VMIO buffer, clear the entire
4142 * buffer. If the specified buffer is a VMIO buffer, clear and
4143 * validate only the previously invalid portions of the buffer.
4144 * This routine essentially fakes an I/O, so we need to clear
4145 * BIO_ERROR and B_INVAL.
4147 * Note that while we only theoretically need to clear through b_bcount,
4148 * we go ahead and clear through b_bufsize.
4151 vfs_bio_clrbuf(struct buf *bp)
4153 int i, j, mask, sa, ea, slide;
4155 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4159 bp->b_flags &= ~B_INVAL;
4160 bp->b_ioflags &= ~BIO_ERROR;
4161 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4162 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4163 (bp->b_offset & PAGE_MASK) == 0) {
4164 if (bp->b_pages[0] == bogus_page)
4166 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4167 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4168 if ((bp->b_pages[0]->valid & mask) == mask)
4170 if ((bp->b_pages[0]->valid & mask) == 0) {
4171 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4172 bp->b_pages[0]->valid |= mask;
4176 sa = bp->b_offset & PAGE_MASK;
4178 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4179 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4180 ea = slide & PAGE_MASK;
4183 if (bp->b_pages[i] == bogus_page)
4186 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4187 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4188 if ((bp->b_pages[i]->valid & mask) == mask)
4190 if ((bp->b_pages[i]->valid & mask) == 0)
4191 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4193 for (; sa < ea; sa += DEV_BSIZE, j++) {
4194 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4195 pmap_zero_page_area(bp->b_pages[i],
4200 bp->b_pages[i]->valid |= mask;
4203 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4208 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4213 if (buf_mapped(bp)) {
4214 BUF_CHECK_MAPPED(bp);
4215 bzero(bp->b_data + base, size);
4217 BUF_CHECK_UNMAPPED(bp);
4218 n = PAGE_SIZE - (base & PAGE_MASK);
4219 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4223 pmap_zero_page_area(m, base & PAGE_MASK, n);
4232 * vm_hold_load_pages and vm_hold_free_pages get pages into
4233 * a buffers address space. The pages are anonymous and are
4234 * not associated with a file object.
4237 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4243 BUF_CHECK_MAPPED(bp);
4245 to = round_page(to);
4246 from = round_page(from);
4247 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4249 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4252 * note: must allocate system pages since blocking here
4253 * could interfere with paging I/O, no matter which
4256 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4257 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4262 pmap_qenter(pg, &p, 1);
4263 bp->b_pages[index] = p;
4265 bp->b_npages = index;
4268 /* Return pages associated with this buf to the vm system */
4270 vm_hold_free_pages(struct buf *bp, int newbsize)
4274 int index, newnpages;
4276 BUF_CHECK_MAPPED(bp);
4278 from = round_page((vm_offset_t)bp->b_data + newbsize);
4279 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4280 if (bp->b_npages > newnpages)
4281 pmap_qremove(from, bp->b_npages - newnpages);
4282 for (index = newnpages; index < bp->b_npages; index++) {
4283 p = bp->b_pages[index];
4284 bp->b_pages[index] = NULL;
4285 if (vm_page_sbusied(p))
4286 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4287 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4290 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
4292 bp->b_npages = newnpages;
4296 * Map an IO request into kernel virtual address space.
4298 * All requests are (re)mapped into kernel VA space.
4299 * Notice that we use b_bufsize for the size of the buffer
4300 * to be mapped. b_bcount might be modified by the driver.
4302 * Note that even if the caller determines that the address space should
4303 * be valid, a race or a smaller-file mapped into a larger space may
4304 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4305 * check the return value.
4307 * This function only works with pager buffers.
4310 vmapbuf(struct buf *bp, int mapbuf)
4315 if (bp->b_bufsize < 0)
4317 prot = VM_PROT_READ;
4318 if (bp->b_iocmd == BIO_READ)
4319 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4320 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4321 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4322 btoc(MAXPHYS))) < 0)
4324 bp->b_npages = pidx;
4325 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4326 if (mapbuf || !unmapped_buf_allowed) {
4327 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
4328 bp->b_data = bp->b_kvabase + bp->b_offset;
4330 bp->b_data = unmapped_buf;
4335 * Free the io map PTEs associated with this IO operation.
4336 * We also invalidate the TLB entries and restore the original b_addr.
4338 * This function only works with pager buffers.
4341 vunmapbuf(struct buf *bp)
4345 npages = bp->b_npages;
4347 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4348 vm_page_unhold_pages(bp->b_pages, npages);
4350 bp->b_data = unmapped_buf;
4354 bdone(struct buf *bp)
4358 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4360 bp->b_flags |= B_DONE;
4366 bwait(struct buf *bp, u_char pri, const char *wchan)
4370 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4372 while ((bp->b_flags & B_DONE) == 0)
4373 msleep(bp, mtxp, pri, wchan, 0);
4378 bufsync(struct bufobj *bo, int waitfor)
4381 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4385 bufstrategy(struct bufobj *bo, struct buf *bp)
4391 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4392 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4393 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4394 i = VOP_STRATEGY(vp, bp);
4395 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4399 bufobj_wrefl(struct bufobj *bo)
4402 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4403 ASSERT_BO_WLOCKED(bo);
4408 bufobj_wref(struct bufobj *bo)
4411 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4418 bufobj_wdrop(struct bufobj *bo)
4421 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4423 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4424 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4425 bo->bo_flag &= ~BO_WWAIT;
4426 wakeup(&bo->bo_numoutput);
4432 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4436 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4437 ASSERT_BO_WLOCKED(bo);
4439 while (bo->bo_numoutput) {
4440 bo->bo_flag |= BO_WWAIT;
4441 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4442 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4450 bpin(struct buf *bp)
4454 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4461 bunpin(struct buf *bp)
4465 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4467 if (--bp->b_pin_count == 0)
4473 bunpin_wait(struct buf *bp)
4477 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4479 while (bp->b_pin_count > 0)
4480 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4485 * Set bio_data or bio_ma for struct bio from the struct buf.
4488 bdata2bio(struct buf *bp, struct bio *bip)
4491 if (!buf_mapped(bp)) {
4492 KASSERT(unmapped_buf_allowed, ("unmapped"));
4493 bip->bio_ma = bp->b_pages;
4494 bip->bio_ma_n = bp->b_npages;
4495 bip->bio_data = unmapped_buf;
4496 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4497 bip->bio_flags |= BIO_UNMAPPED;
4498 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4499 PAGE_SIZE == bp->b_npages,
4500 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4501 (long long)bip->bio_length, bip->bio_ma_n));
4503 bip->bio_data = bp->b_data;
4508 #include "opt_ddb.h"
4510 #include <ddb/ddb.h>
4512 /* DDB command to show buffer data */
4513 DB_SHOW_COMMAND(buffer, db_show_buffer)
4516 struct buf *bp = (struct buf *)addr;
4519 db_printf("usage: show buffer <addr>\n");
4523 db_printf("buf at %p\n", bp);
4524 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4525 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4526 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4528 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4529 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4531 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4532 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4533 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4534 db_printf("b_kvabase = %p, b_kvasize = %d\n",
4535 bp->b_kvabase, bp->b_kvasize);
4538 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4539 for (i = 0; i < bp->b_npages; i++) {
4542 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4543 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4544 if ((i + 1) < bp->b_npages)
4550 BUF_LOCKPRINTINFO(bp);
4553 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4558 for (i = 0; i < nbuf; i++) {
4560 if (BUF_ISLOCKED(bp)) {
4561 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4567 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4573 db_printf("usage: show vnodebufs <addr>\n");
4576 vp = (struct vnode *)addr;
4577 db_printf("Clean buffers:\n");
4578 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4579 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4582 db_printf("Dirty buffers:\n");
4583 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4584 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4589 DB_COMMAND(countfreebufs, db_coundfreebufs)
4592 int i, used = 0, nfree = 0;
4595 db_printf("usage: countfreebufs\n");
4599 for (i = 0; i < nbuf; i++) {
4601 if ((bp->b_flags & B_INFREECNT) != 0)
4607 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4609 db_printf("numfreebuffers is %d\n", numfreebuffers);