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/racct.h>
65 #include <sys/resourcevar.h>
66 #include <sys/rwlock.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysproto.h>
71 #include <sys/vmmeter.h>
72 #include <sys/vnode.h>
73 #include <sys/watchdog.h>
74 #include <geom/geom.h>
76 #include <vm/vm_param.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_object.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_pageout.h>
81 #include <vm/vm_pager.h>
82 #include <vm/vm_extern.h>
83 #include <vm/vm_map.h>
84 #include <vm/swap_pager.h>
85 #include "opt_compat.h"
88 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
90 struct bio_ops bioops; /* I/O operation notification */
92 struct buf_ops buf_ops_bio = {
93 .bop_name = "buf_ops_bio",
94 .bop_write = bufwrite,
95 .bop_strategy = bufstrategy,
97 .bop_bdflush = bufbdflush,
100 static struct buf *buf; /* buffer header pool */
101 extern struct buf *swbuf; /* Swap buffer header pool. */
102 caddr_t unmapped_buf;
104 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
105 struct proc *bufdaemonproc;
106 struct proc *bufspacedaemonproc;
108 static int inmem(struct vnode *vp, daddr_t blkno);
109 static void vm_hold_free_pages(struct buf *bp, int newbsize);
110 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
112 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
113 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
115 static void vfs_clean_pages_dirty_buf(struct buf *bp);
116 static void vfs_setdirty_locked_object(struct buf *bp);
117 static void vfs_vmio_invalidate(struct buf *bp);
118 static void vfs_vmio_truncate(struct buf *bp, int npages);
119 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
120 static int vfs_bio_clcheck(struct vnode *vp, int size,
121 daddr_t lblkno, daddr_t blkno);
122 static int buf_flush(struct vnode *vp, int);
123 static int buf_recycle(bool);
124 static int buf_scan(bool);
125 static int flushbufqueues(struct vnode *, int, int);
126 static void buf_daemon(void);
127 static void bremfreel(struct buf *bp);
128 static __inline void bd_wakeup(void);
129 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
130 static void bufkva_reclaim(vmem_t *, int);
131 static void bufkva_free(struct buf *);
132 static int buf_import(void *, void **, int, int);
133 static void buf_release(void *, void **, int);
135 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
136 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
137 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
140 int vmiodirenable = TRUE;
141 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
142 "Use the VM system for directory writes");
143 long runningbufspace;
144 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
145 "Amount of presently outstanding async buffer io");
146 static long bufspace;
147 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
148 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
149 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
150 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
152 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
153 "Physical memory used for buffers");
155 static long bufkvaspace;
156 SYSCTL_LONG(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace, 0,
157 "Kernel virtual memory used for buffers");
158 static long maxbufspace;
159 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RW, &maxbufspace, 0,
160 "Maximum allowed value of bufspace (including metadata)");
161 static long bufmallocspace;
162 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
163 "Amount of malloced memory for buffers");
164 static long maxbufmallocspace;
165 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
166 0, "Maximum amount of malloced memory for buffers");
167 static long lobufspace;
168 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RW, &lobufspace, 0,
169 "Minimum amount of buffers we want to have");
171 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RW, &hibufspace, 0,
172 "Maximum allowed value of bufspace (excluding metadata)");
174 SYSCTL_LONG(_vfs, OID_AUTO, bufspacethresh, CTLFLAG_RW, &bufspacethresh,
175 0, "Bufspace consumed before waking the daemon to free some");
176 static int buffreekvacnt;
177 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
178 "Number of times we have freed the KVA space from some buffer");
179 static int bufdefragcnt;
180 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
181 "Number of times we have had to repeat buffer allocation to defragment");
182 static long lorunningspace;
183 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
184 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
185 "Minimum preferred space used for in-progress I/O");
186 static long hirunningspace;
187 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
188 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
189 "Maximum amount of space to use for in-progress I/O");
190 int dirtybufferflushes;
191 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
192 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
194 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
195 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
196 int altbufferflushes;
197 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
198 0, "Number of fsync flushes to limit dirty buffers");
199 static int recursiveflushes;
200 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
201 0, "Number of flushes skipped due to being recursive");
202 static int numdirtybuffers;
203 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
204 "Number of buffers that are dirty (has unwritten changes) at the moment");
205 static int lodirtybuffers;
206 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
207 "How many buffers we want to have free before bufdaemon can sleep");
208 static int hidirtybuffers;
209 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
210 "When the number of dirty buffers is considered severe");
212 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
213 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
214 static int numfreebuffers;
215 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
216 "Number of free buffers");
217 static int lofreebuffers;
218 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
219 "Target number of free buffers");
220 static int hifreebuffers;
221 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
222 "Threshold for clean buffer recycling");
223 static int getnewbufcalls;
224 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
225 "Number of calls to getnewbuf");
226 static int getnewbufrestarts;
227 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
228 "Number of times getnewbuf has had to restart a buffer acquisition");
229 static int mappingrestarts;
230 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
231 "Number of times getblk has had to restart a buffer mapping for "
233 static int numbufallocfails;
234 SYSCTL_INT(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW, &numbufallocfails, 0,
235 "Number of times buffer allocations failed");
236 static int flushbufqtarget = 100;
237 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
238 "Amount of work to do in flushbufqueues when helping bufdaemon");
239 static long notbufdflushes;
240 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 0,
241 "Number of dirty buffer flushes done by the bufdaemon helpers");
242 static long barrierwrites;
243 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
244 "Number of barrier writes");
245 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
246 &unmapped_buf_allowed, 0,
247 "Permit the use of the unmapped i/o");
250 * This lock synchronizes access to bd_request.
252 static struct mtx_padalign bdlock;
255 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
256 * waitrunningbufspace().
258 static struct mtx_padalign rbreqlock;
261 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
263 static struct rwlock_padalign nblock;
266 * Lock that protects bdirtywait.
268 static struct mtx_padalign bdirtylock;
271 * Wakeup point for bufdaemon, as well as indicator of whether it is already
272 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
275 static int bd_request;
278 * Request/wakeup point for the bufspace daemon.
280 static int bufspace_request;
283 * Request for the buf daemon to write more buffers than is indicated by
284 * lodirtybuf. This may be necessary to push out excess dependencies or
285 * defragment the address space where a simple count of the number of dirty
286 * buffers is insufficient to characterize the demand for flushing them.
288 static int bd_speedupreq;
291 * bogus page -- for I/O to/from partially complete buffers
292 * this is a temporary solution to the problem, but it is not
293 * really that bad. it would be better to split the buffer
294 * for input in the case of buffers partially already in memory,
295 * but the code is intricate enough already.
297 vm_page_t bogus_page;
300 * Synchronization (sleep/wakeup) variable for active buffer space requests.
301 * Set when wait starts, cleared prior to wakeup().
302 * Used in runningbufwakeup() and waitrunningbufspace().
304 static int runningbufreq;
307 * Synchronization (sleep/wakeup) variable for buffer requests.
308 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
310 * Used in numdirtywakeup(), bufspace_wakeup(), bwillwrite(),
311 * getnewbuf(), and getblk().
313 static volatile int needsbuffer;
316 * Synchronization for bwillwrite() waiters.
318 static int bdirtywait;
321 * Definitions for the buffer free lists.
323 #define QUEUE_NONE 0 /* on no queue */
324 #define QUEUE_EMPTY 1 /* empty buffer headers */
325 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
326 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
327 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
329 /* Maximum number of clean buffer queues. */
330 #define CLEAN_QUEUES 16
332 /* Configured number of clean queues. */
333 static int clean_queues;
335 /* Maximum number of buffer queues. */
336 #define BUFFER_QUEUES (QUEUE_CLEAN + CLEAN_QUEUES)
338 /* Queues for free buffers with various properties */
339 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
341 static int bq_len[BUFFER_QUEUES];
345 * Lock for each bufqueue
347 static struct mtx_padalign bqlocks[BUFFER_QUEUES];
350 * per-cpu empty buffer cache.
355 * Single global constant for BUF_WMESG, to avoid getting multiple references.
356 * buf_wmesg is referred from macros.
358 const char *buf_wmesg = BUF_WMESG;
361 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
366 value = *(long *)arg1;
367 error = sysctl_handle_long(oidp, &value, 0, req);
368 if (error != 0 || req->newptr == NULL)
370 mtx_lock(&rbreqlock);
371 if (arg1 == &hirunningspace) {
372 if (value < lorunningspace)
375 hirunningspace = value;
377 KASSERT(arg1 == &lorunningspace,
378 ("%s: unknown arg1", __func__));
379 if (value > hirunningspace)
382 lorunningspace = value;
384 mtx_unlock(&rbreqlock);
388 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
389 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
391 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
396 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
397 return (sysctl_handle_long(oidp, arg1, arg2, req));
398 lvalue = *(long *)arg1;
399 if (lvalue > INT_MAX)
400 /* On overflow, still write out a long to trigger ENOMEM. */
401 return (sysctl_handle_long(oidp, &lvalue, 0, req));
403 return (sysctl_handle_int(oidp, &ivalue, 0, req));
412 return ((atomic_fetchadd_int(&nextq, 1) % clean_queues) + QUEUE_CLEAN);
416 bqisclean(int qindex)
419 return (qindex >= QUEUE_CLEAN && qindex < QUEUE_CLEAN + CLEAN_QUEUES);
425 * Return the appropriate queue lock based on the index.
427 static inline struct mtx *
431 return (struct mtx *)&bqlocks[qindex];
437 * Wakeup any bwillwrite() waiters.
442 mtx_lock(&bdirtylock);
447 mtx_unlock(&bdirtylock);
453 * Decrement the numdirtybuffers count by one and wakeup any
454 * threads blocked in bwillwrite().
460 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
461 (lodirtybuffers + hidirtybuffers) / 2)
468 * Increment the numdirtybuffers count by one and wakeup the buf
476 * Only do the wakeup once as we cross the boundary. The
477 * buf daemon will keep running until the condition clears.
479 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
480 (lodirtybuffers + hidirtybuffers) / 2)
487 * Called when buffer space is potentially available for recovery.
488 * getnewbuf() will block on this flag when it is unable to free
489 * sufficient buffer space. Buffer space becomes recoverable when
490 * bp's get placed back in the queues.
493 bufspace_wakeup(void)
497 * If someone is waiting for bufspace, wake them up.
499 * Since needsbuffer is set prior to doing an additional queue
500 * scan it is safe to check for the flag prior to acquiring the
501 * lock. The thread that is preparing to scan again before
502 * blocking would discover the buf we released.
506 if (atomic_cmpset_int(&needsbuffer, 1, 0) == 1)
507 wakeup(__DEVOLATILE(void *, &needsbuffer));
513 * bufspace_daemonwakeup:
515 * Wakeup the daemon responsible for freeing clean bufs.
518 bufspace_daemonwakeup(void)
521 if (bufspace_request == 0) {
522 bufspace_request = 1;
523 wakeup(&bufspace_request);
531 * Adjust the reported bufspace for a KVA managed buffer, possibly
532 * waking any waiters.
535 bufspace_adjust(struct buf *bp, int bufsize)
540 KASSERT((bp->b_flags & B_MALLOC) == 0,
541 ("bufspace_adjust: malloc buf %p", bp));
542 diff = bufsize - bp->b_bufsize;
544 atomic_subtract_long(&bufspace, -diff);
547 space = atomic_fetchadd_long(&bufspace, diff);
548 /* Wake up the daemon on the transition. */
549 if (space < bufspacethresh && space + diff >= bufspacethresh)
550 bufspace_daemonwakeup();
552 bp->b_bufsize = bufsize;
558 * Reserve bufspace before calling allocbuf(). metadata has a
559 * different space limit than data.
562 bufspace_reserve(int size, bool metadata)
573 if (space + size > limit)
575 } while (atomic_cmpset_long(&bufspace, space, space + size) == 0);
577 /* Wake up the daemon on the transition. */
578 if (space < bufspacethresh && space + size >= bufspacethresh)
579 bufspace_daemonwakeup();
587 * Release reserved bufspace after bufspace_adjust() has consumed it.
590 bufspace_release(int size)
592 atomic_subtract_long(&bufspace, size);
599 * Wait for bufspace, acting as the buf daemon if a locked vnode is
600 * supplied. needsbuffer must be set in a safe fashion prior to
601 * polling for space. The operation must be re-tried on return.
604 bufspace_wait(struct vnode *vp, int gbflags, int slpflag, int slptimeo)
607 int error, fl, norunbuf;
609 if ((gbflags & GB_NOWAIT_BD) != 0)
614 while (needsbuffer != 0) {
615 if (vp != NULL && vp->v_type != VCHR &&
616 (td->td_pflags & TDP_BUFNEED) == 0) {
619 * getblk() is called with a vnode locked, and
620 * some majority of the dirty buffers may as
621 * well belong to the vnode. Flushing the
622 * buffers there would make a progress that
623 * cannot be achieved by the buf_daemon, that
624 * cannot lock the vnode.
626 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
627 (td->td_pflags & TDP_NORUNNINGBUF);
630 * Play bufdaemon. The getnewbuf() function
631 * may be called while the thread owns lock
632 * for another dirty buffer for the same
633 * vnode, which makes it impossible to use
634 * VOP_FSYNC() there, due to the buffer lock
637 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
638 fl = buf_flush(vp, flushbufqtarget);
639 td->td_pflags &= norunbuf;
643 if (needsbuffer == 0)
646 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
647 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
658 * buffer space management daemon. Tries to maintain some marginal
659 * amount of free buffer space so that requesting processes neither
660 * block nor work to reclaim buffers.
663 bufspace_daemon(void)
666 kproc_suspend_check(bufspacedaemonproc);
669 * Free buffers from the clean queue until we meet our
672 * Theory of operation: The buffer cache is most efficient
673 * when some free buffer headers and space are always
674 * available to getnewbuf(). This daemon attempts to prevent
675 * the excessive blocking and synchronization associated
676 * with shortfall. It goes through three phases according
679 * 1) The daemon wakes up voluntarily once per-second
680 * during idle periods when the counters are below
681 * the wakeup thresholds (bufspacethresh, lofreebuffers).
683 * 2) The daemon wakes up as we cross the thresholds
684 * ahead of any potential blocking. This may bounce
685 * slightly according to the rate of consumption and
688 * 3) The daemon and consumers are starved for working
689 * clean buffers. This is the 'bufspace' sleep below
690 * which will inefficiently trade bufs with bqrelse
691 * until we return to condition 2.
693 while (bufspace > lobufspace ||
694 numfreebuffers < hifreebuffers) {
695 if (buf_recycle(false) != 0) {
696 atomic_set_int(&needsbuffer, 1);
697 if (buf_recycle(false) != 0) {
700 rw_sleep(__DEVOLATILE(void *,
701 &needsbuffer), &nblock,
702 PRIBIO|PDROP, "bufspace",
712 * Re-check our limits under the exclusive nblock.
715 if (bufspace < bufspacethresh &&
716 numfreebuffers > lofreebuffers) {
717 bufspace_request = 0;
718 rw_sleep(&bufspace_request, &nblock, PRIBIO|PDROP,
725 static struct kproc_desc bufspace_kp = {
730 SYSINIT(bufspacedaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start,
736 * Adjust the reported bufspace for a malloc managed buffer, possibly
737 * waking any waiters.
740 bufmallocadjust(struct buf *bp, int bufsize)
744 KASSERT((bp->b_flags & B_MALLOC) != 0,
745 ("bufmallocadjust: non-malloc buf %p", bp));
746 diff = bufsize - bp->b_bufsize;
748 atomic_subtract_long(&bufmallocspace, -diff);
750 atomic_add_long(&bufmallocspace, diff);
751 bp->b_bufsize = bufsize;
757 * Wake up processes that are waiting on asynchronous writes to fall
758 * below lorunningspace.
764 mtx_lock(&rbreqlock);
767 wakeup(&runningbufreq);
769 mtx_unlock(&rbreqlock);
775 * Decrement the outstanding write count according.
778 runningbufwakeup(struct buf *bp)
782 bspace = bp->b_runningbufspace;
785 space = atomic_fetchadd_long(&runningbufspace, -bspace);
786 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
788 bp->b_runningbufspace = 0;
790 * Only acquire the lock and wakeup on the transition from exceeding
791 * the threshold to falling below it.
793 if (space < lorunningspace)
795 if (space - bspace > lorunningspace)
801 * waitrunningbufspace()
803 * runningbufspace is a measure of the amount of I/O currently
804 * running. This routine is used in async-write situations to
805 * prevent creating huge backups of pending writes to a device.
806 * Only asynchronous writes are governed by this function.
808 * This does NOT turn an async write into a sync write. It waits
809 * for earlier writes to complete and generally returns before the
810 * caller's write has reached the device.
813 waitrunningbufspace(void)
816 mtx_lock(&rbreqlock);
817 while (runningbufspace > hirunningspace) {
819 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
821 mtx_unlock(&rbreqlock);
826 * vfs_buf_test_cache:
828 * Called when a buffer is extended. This function clears the B_CACHE
829 * bit if the newly extended portion of the buffer does not contain
833 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
834 vm_offset_t size, vm_page_t m)
837 VM_OBJECT_ASSERT_LOCKED(m->object);
838 if (bp->b_flags & B_CACHE) {
839 int base = (foff + off) & PAGE_MASK;
840 if (vm_page_is_valid(m, base, size) == 0)
841 bp->b_flags &= ~B_CACHE;
845 /* Wake up the buffer daemon if necessary */
851 if (bd_request == 0) {
859 * bd_speedup - speedup the buffer cache flushing code
868 if (bd_speedupreq == 0 || bd_request == 0)
878 #define NSWBUF_MIN 16
882 #define TRANSIENT_DENOM 5
884 #define TRANSIENT_DENOM 10
888 * Calculating buffer cache scaling values and reserve space for buffer
889 * headers. This is called during low level kernel initialization and
890 * may be called more then once. We CANNOT write to the memory area
891 * being reserved at this time.
894 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
897 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
900 * physmem_est is in pages. Convert it to kilobytes (assumes
901 * PAGE_SIZE is >= 1K)
903 physmem_est = physmem_est * (PAGE_SIZE / 1024);
906 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
907 * For the first 64MB of ram nominally allocate sufficient buffers to
908 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
909 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
910 * the buffer cache we limit the eventual kva reservation to
913 * factor represents the 1/4 x ram conversion.
916 int factor = 4 * BKVASIZE / 1024;
919 if (physmem_est > 4096)
920 nbuf += min((physmem_est - 4096) / factor,
922 if (physmem_est > 65536)
923 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
924 32 * 1024 * 1024 / (factor * 5));
926 if (maxbcache && nbuf > maxbcache / BKVASIZE)
927 nbuf = maxbcache / BKVASIZE;
932 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
933 maxbuf = (LONG_MAX / 3) / BKVASIZE;
936 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
942 * Ideal allocation size for the transient bio submap is 10%
943 * of the maximal space buffer map. This roughly corresponds
944 * to the amount of the buffer mapped for typical UFS load.
946 * Clip the buffer map to reserve space for the transient
947 * BIOs, if its extent is bigger than 90% (80% on i386) of the
948 * maximum buffer map extent on the platform.
950 * The fall-back to the maxbuf in case of maxbcache unset,
951 * allows to not trim the buffer KVA for the architectures
952 * with ample KVA space.
954 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
955 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
956 buf_sz = (long)nbuf * BKVASIZE;
957 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
958 (TRANSIENT_DENOM - 1)) {
960 * There is more KVA than memory. Do not
961 * adjust buffer map size, and assign the rest
962 * of maxbuf to transient map.
964 biotmap_sz = maxbuf_sz - buf_sz;
967 * Buffer map spans all KVA we could afford on
968 * this platform. Give 10% (20% on i386) of
969 * the buffer map to the transient bio map.
971 biotmap_sz = buf_sz / TRANSIENT_DENOM;
972 buf_sz -= biotmap_sz;
974 if (biotmap_sz / INT_MAX > MAXPHYS)
975 bio_transient_maxcnt = INT_MAX;
977 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
979 * Artificially limit to 1024 simultaneous in-flight I/Os
980 * using the transient mapping.
982 if (bio_transient_maxcnt > 1024)
983 bio_transient_maxcnt = 1024;
985 nbuf = buf_sz / BKVASIZE;
989 * swbufs are used as temporary holders for I/O, such as paging I/O.
990 * We have no less then 16 and no more then 256.
992 nswbuf = min(nbuf / 4, 256);
993 TUNABLE_INT_FETCH("kern.nswbuf", &nswbuf);
994 if (nswbuf < NSWBUF_MIN)
998 * Reserve space for the buffer cache buffers
1001 v = (caddr_t)(swbuf + nswbuf);
1003 v = (caddr_t)(buf + nbuf);
1008 /* Initialize the buffer subsystem. Called before use of any buffers. */
1015 CTASSERT(MAXBCACHEBUF >= MAXBSIZE);
1016 mtx_init(&bqlocks[QUEUE_DIRTY], "bufq dirty lock", NULL, MTX_DEF);
1017 mtx_init(&bqlocks[QUEUE_EMPTY], "bufq empty lock", NULL, MTX_DEF);
1018 for (i = QUEUE_CLEAN; i < QUEUE_CLEAN + CLEAN_QUEUES; i++)
1019 mtx_init(&bqlocks[i], "bufq clean lock", NULL, MTX_DEF);
1020 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1021 rw_init(&nblock, "needsbuffer lock");
1022 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1023 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1025 /* next, make a null set of free lists */
1026 for (i = 0; i < BUFFER_QUEUES; i++)
1027 TAILQ_INIT(&bufqueues[i]);
1029 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
1031 /* finally, initialize each buffer header and stick on empty q */
1032 for (i = 0; i < nbuf; i++) {
1034 bzero(bp, sizeof *bp);
1035 bp->b_flags = B_INVAL;
1036 bp->b_rcred = NOCRED;
1037 bp->b_wcred = NOCRED;
1038 bp->b_qindex = QUEUE_EMPTY;
1040 bp->b_data = bp->b_kvabase = unmapped_buf;
1041 LIST_INIT(&bp->b_dep);
1043 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
1045 bq_len[QUEUE_EMPTY]++;
1050 * maxbufspace is the absolute maximum amount of buffer space we are
1051 * allowed to reserve in KVM and in real terms. The absolute maximum
1052 * is nominally used by metadata. hibufspace is the nominal maximum
1053 * used by most other requests. The differential is required to
1054 * ensure that metadata deadlocks don't occur.
1056 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1057 * this may result in KVM fragmentation which is not handled optimally
1058 * by the system. XXX This is less true with vmem. We could use
1061 maxbufspace = (long)nbuf * BKVASIZE;
1062 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBCACHEBUF * 10);
1063 lobufspace = (hibufspace / 20) * 19; /* 95% */
1064 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1067 * Note: The 16 MiB upper limit for hirunningspace was chosen
1068 * arbitrarily and may need further tuning. It corresponds to
1069 * 128 outstanding write IO requests (if IO size is 128 KiB),
1070 * which fits with many RAID controllers' tagged queuing limits.
1071 * The lower 1 MiB limit is the historical upper limit for
1074 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBCACHEBUF),
1075 16 * 1024 * 1024), 1024 * 1024);
1076 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBCACHEBUF);
1079 * Limit the amount of malloc memory since it is wired permanently into
1080 * the kernel space. Even though this is accounted for in the buffer
1081 * allocation, we don't want the malloced region to grow uncontrolled.
1082 * The malloc scheme improves memory utilization significantly on
1083 * average (small) directories.
1085 maxbufmallocspace = hibufspace / 20;
1088 * Reduce the chance of a deadlock occurring by limiting the number
1089 * of delayed-write dirty buffers we allow to stack up.
1091 hidirtybuffers = nbuf / 4 + 20;
1092 dirtybufthresh = hidirtybuffers * 9 / 10;
1093 numdirtybuffers = 0;
1095 * To support extreme low-memory systems, make sure hidirtybuffers
1096 * cannot eat up all available buffer space. This occurs when our
1097 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1098 * buffer space assuming BKVASIZE'd buffers.
1100 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1101 hidirtybuffers >>= 1;
1103 lodirtybuffers = hidirtybuffers / 2;
1106 * lofreebuffers should be sufficient to avoid stalling waiting on
1107 * buf headers under heavy utilization. The bufs in per-cpu caches
1108 * are counted as free but will be unavailable to threads executing
1111 * hifreebuffers is the free target for the bufspace daemon. This
1112 * should be set appropriately to limit work per-iteration.
1114 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1115 hifreebuffers = (3 * lofreebuffers) / 2;
1116 numfreebuffers = nbuf;
1118 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
1119 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
1121 /* Setup the kva and free list allocators. */
1122 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1123 buf_zone = uma_zcache_create("buf free cache", sizeof(struct buf),
1124 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1127 * Size the clean queue according to the amount of buffer space.
1128 * One queue per-256mb up to the max. More queues gives better
1129 * concurrency but less accurate LRU.
1131 clean_queues = MIN(howmany(maxbufspace, 256*1024*1024), CLEAN_QUEUES);
1137 vfs_buf_check_mapped(struct buf *bp)
1140 KASSERT(bp->b_kvabase != unmapped_buf,
1141 ("mapped buf: b_kvabase was not updated %p", bp));
1142 KASSERT(bp->b_data != unmapped_buf,
1143 ("mapped buf: b_data was not updated %p", bp));
1144 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1145 MAXPHYS, ("b_data + b_offset unmapped %p", bp));
1149 vfs_buf_check_unmapped(struct buf *bp)
1152 KASSERT(bp->b_data == unmapped_buf,
1153 ("unmapped buf: corrupted b_data %p", bp));
1156 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1157 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1159 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1160 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1164 isbufbusy(struct buf *bp)
1166 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1167 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1173 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1176 bufshutdown(int show_busybufs)
1178 static int first_buf_printf = 1;
1180 int iter, nbusy, pbusy;
1186 * Sync filesystems for shutdown
1188 wdog_kern_pat(WD_LASTVAL);
1189 sys_sync(curthread, NULL);
1192 * With soft updates, some buffers that are
1193 * written will be remarked as dirty until other
1194 * buffers are written.
1196 for (iter = pbusy = 0; iter < 20; iter++) {
1198 for (bp = &buf[nbuf]; --bp >= buf; )
1202 if (first_buf_printf)
1203 printf("All buffers synced.");
1206 if (first_buf_printf) {
1207 printf("Syncing disks, buffers remaining... ");
1208 first_buf_printf = 0;
1210 printf("%d ", nbusy);
1215 wdog_kern_pat(WD_LASTVAL);
1216 sys_sync(curthread, NULL);
1220 * Drop Giant and spin for a while to allow
1221 * interrupt threads to run.
1224 DELAY(50000 * iter);
1228 * Drop Giant and context switch several times to
1229 * allow interrupt threads to run.
1232 for (subiter = 0; subiter < 50 * iter; subiter++) {
1233 thread_lock(curthread);
1234 mi_switch(SW_VOL, NULL);
1235 thread_unlock(curthread);
1243 * Count only busy local buffers to prevent forcing
1244 * a fsck if we're just a client of a wedged NFS server
1247 for (bp = &buf[nbuf]; --bp >= buf; ) {
1248 if (isbufbusy(bp)) {
1250 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1251 if (bp->b_dev == NULL) {
1252 TAILQ_REMOVE(&mountlist,
1253 bp->b_vp->v_mount, mnt_list);
1258 if (show_busybufs > 0) {
1260 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1261 nbusy, bp, bp->b_vp, bp->b_flags,
1262 (intmax_t)bp->b_blkno,
1263 (intmax_t)bp->b_lblkno);
1264 BUF_LOCKPRINTINFO(bp);
1265 if (show_busybufs > 1)
1273 * Failed to sync all blocks. Indicate this and don't
1274 * unmount filesystems (thus forcing an fsck on reboot).
1276 printf("Giving up on %d buffers\n", nbusy);
1277 DELAY(5000000); /* 5 seconds */
1279 if (!first_buf_printf)
1280 printf("Final sync complete\n");
1282 * Unmount filesystems
1284 if (panicstr == NULL)
1288 DELAY(100000); /* wait for console output to finish */
1292 bpmap_qenter(struct buf *bp)
1295 BUF_CHECK_MAPPED(bp);
1298 * bp->b_data is relative to bp->b_offset, but
1299 * bp->b_offset may be offset into the first page.
1301 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1302 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1303 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1304 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1310 * Insert the buffer into the appropriate free list.
1313 binsfree(struct buf *bp, int qindex)
1315 struct mtx *olock, *nlock;
1317 if (qindex != QUEUE_EMPTY) {
1318 BUF_ASSERT_XLOCKED(bp);
1322 * Stick to the same clean queue for the lifetime of the buf to
1323 * limit locking below. Otherwise pick ont sequentially.
1325 if (qindex == QUEUE_CLEAN) {
1326 if (bqisclean(bp->b_qindex))
1327 qindex = bp->b_qindex;
1329 qindex = bqcleanq();
1333 * Handle delayed bremfree() processing.
1335 nlock = bqlock(qindex);
1336 if (bp->b_flags & B_REMFREE) {
1337 olock = bqlock(bp->b_qindex);
1340 if (olock != nlock) {
1347 if (bp->b_qindex != QUEUE_NONE)
1348 panic("binsfree: free buffer onto another queue???");
1350 bp->b_qindex = qindex;
1351 if (bp->b_flags & B_AGE)
1352 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1354 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1356 bq_len[bp->b_qindex]++;
1364 * Free a buffer to the buf zone once it no longer has valid contents.
1367 buf_free(struct buf *bp)
1370 if (bp->b_flags & B_REMFREE)
1372 if (bp->b_vflags & BV_BKGRDINPROG)
1373 panic("losing buffer 1");
1374 if (bp->b_rcred != NOCRED) {
1375 crfree(bp->b_rcred);
1376 bp->b_rcred = NOCRED;
1378 if (bp->b_wcred != NOCRED) {
1379 crfree(bp->b_wcred);
1380 bp->b_wcred = NOCRED;
1382 if (!LIST_EMPTY(&bp->b_dep))
1386 uma_zfree(buf_zone, bp);
1387 atomic_add_int(&numfreebuffers, 1);
1394 * Import bufs into the uma cache from the buf list. The system still
1395 * expects a static array of bufs and much of the synchronization
1396 * around bufs assumes type stable storage. As a result, UMA is used
1397 * only as a per-cpu cache of bufs still maintained on a global list.
1400 buf_import(void *arg, void **store, int cnt, int flags)
1405 mtx_lock(&bqlocks[QUEUE_EMPTY]);
1406 for (i = 0; i < cnt; i++) {
1407 bp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1413 mtx_unlock(&bqlocks[QUEUE_EMPTY]);
1421 * Release bufs from the uma cache back to the buffer queues.
1424 buf_release(void *arg, void **store, int cnt)
1428 for (i = 0; i < cnt; i++)
1429 binsfree(store[i], QUEUE_EMPTY);
1435 * Allocate an empty buffer header.
1442 bp = uma_zalloc(buf_zone, M_NOWAIT);
1444 bufspace_daemonwakeup();
1445 atomic_add_int(&numbufallocfails, 1);
1450 * Wake-up the bufspace daemon on transition.
1452 if (atomic_fetchadd_int(&numfreebuffers, -1) == lofreebuffers)
1453 bufspace_daemonwakeup();
1455 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1456 panic("getnewbuf_empty: Locked buf %p on free queue.", bp);
1458 KASSERT(bp->b_vp == NULL,
1459 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1460 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1461 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1462 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1463 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1464 KASSERT(bp->b_npages == 0,
1465 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1466 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1467 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1474 bp->b_blkno = bp->b_lblkno = 0;
1475 bp->b_offset = NOOFFSET;
1481 bp->b_dirtyoff = bp->b_dirtyend = 0;
1482 bp->b_bufobj = NULL;
1483 bp->b_pin_count = 0;
1484 bp->b_data = bp->b_kvabase = unmapped_buf;
1485 bp->b_fsprivate1 = NULL;
1486 bp->b_fsprivate2 = NULL;
1487 bp->b_fsprivate3 = NULL;
1488 LIST_INIT(&bp->b_dep);
1496 * Free a buffer from the given bufqueue. kva controls whether the
1497 * freed buf must own some kva resources. This is used for
1501 buf_qrecycle(int qindex, bool kva)
1503 struct buf *bp, *nbp;
1506 atomic_add_int(&bufdefragcnt, 1);
1508 mtx_lock(&bqlocks[qindex]);
1509 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1512 * Run scan, possibly freeing data and/or kva mappings on the fly
1515 while ((bp = nbp) != NULL) {
1517 * Calculate next bp (we can only use it if we do not
1518 * release the bqlock).
1520 nbp = TAILQ_NEXT(bp, b_freelist);
1523 * If we are defragging then we need a buffer with
1524 * some kva to reclaim.
1526 if (kva && bp->b_kvasize == 0)
1529 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1533 * Skip buffers with background writes in progress.
1535 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1540 KASSERT(bp->b_qindex == qindex,
1541 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1543 * NOTE: nbp is now entirely invalid. We can only restart
1544 * the scan from this point on.
1547 mtx_unlock(&bqlocks[qindex]);
1550 * Requeue the background write buffer with error and
1553 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1555 mtx_lock(&bqlocks[qindex]);
1556 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1559 bp->b_flags |= B_INVAL;
1563 mtx_unlock(&bqlocks[qindex]);
1571 * Iterate through all clean queues until we find a buf to recycle or
1572 * exhaust the search.
1575 buf_recycle(bool kva)
1577 int qindex, first_qindex;
1579 qindex = first_qindex = bqcleanq();
1581 if (buf_qrecycle(qindex, kva) == 0)
1583 if (++qindex == QUEUE_CLEAN + clean_queues)
1584 qindex = QUEUE_CLEAN;
1585 } while (qindex != first_qindex);
1593 * Scan the clean queues looking for a buffer to recycle. needsbuffer
1594 * is set on failure so that the caller may optionally bufspace_wait()
1595 * in a race-free fashion.
1598 buf_scan(bool defrag)
1603 * To avoid heavy synchronization and wakeup races we set
1604 * needsbuffer and re-poll before failing. This ensures that
1605 * no frees can be missed between an unsuccessful poll and
1606 * going to sleep in a synchronized fashion.
1608 if ((error = buf_recycle(defrag)) != 0) {
1609 atomic_set_int(&needsbuffer, 1);
1610 bufspace_daemonwakeup();
1611 error = buf_recycle(defrag);
1614 atomic_add_int(&getnewbufrestarts, 1);
1621 * Mark the buffer for removal from the appropriate free list.
1625 bremfree(struct buf *bp)
1628 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1629 KASSERT((bp->b_flags & B_REMFREE) == 0,
1630 ("bremfree: buffer %p already marked for delayed removal.", bp));
1631 KASSERT(bp->b_qindex != QUEUE_NONE,
1632 ("bremfree: buffer %p not on a queue.", bp));
1633 BUF_ASSERT_XLOCKED(bp);
1635 bp->b_flags |= B_REMFREE;
1641 * Force an immediate removal from a free list. Used only in nfs when
1642 * it abuses the b_freelist pointer.
1645 bremfreef(struct buf *bp)
1649 qlock = bqlock(bp->b_qindex);
1658 * Removes a buffer from the free list, must be called with the
1659 * correct qlock held.
1662 bremfreel(struct buf *bp)
1665 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1666 bp, bp->b_vp, bp->b_flags);
1667 KASSERT(bp->b_qindex != QUEUE_NONE,
1668 ("bremfreel: buffer %p not on a queue.", bp));
1669 if (bp->b_qindex != QUEUE_EMPTY) {
1670 BUF_ASSERT_XLOCKED(bp);
1672 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1674 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1676 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1678 bq_len[bp->b_qindex]--;
1680 bp->b_qindex = QUEUE_NONE;
1681 bp->b_flags &= ~B_REMFREE;
1687 * Free the kva allocation for a buffer.
1691 bufkva_free(struct buf *bp)
1695 if (bp->b_kvasize == 0) {
1696 KASSERT(bp->b_kvabase == unmapped_buf &&
1697 bp->b_data == unmapped_buf,
1698 ("Leaked KVA space on %p", bp));
1699 } else if (buf_mapped(bp))
1700 BUF_CHECK_MAPPED(bp);
1702 BUF_CHECK_UNMAPPED(bp);
1704 if (bp->b_kvasize == 0)
1707 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
1708 atomic_subtract_long(&bufkvaspace, bp->b_kvasize);
1709 atomic_add_int(&buffreekvacnt, 1);
1710 bp->b_data = bp->b_kvabase = unmapped_buf;
1717 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
1720 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
1725 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
1726 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
1731 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
1734 * Buffer map is too fragmented. Request the caller
1735 * to defragment the map.
1739 bp->b_kvabase = (caddr_t)addr;
1740 bp->b_kvasize = maxsize;
1741 atomic_add_long(&bufkvaspace, bp->b_kvasize);
1742 if ((gbflags & GB_UNMAPPED) != 0) {
1743 bp->b_data = unmapped_buf;
1744 BUF_CHECK_UNMAPPED(bp);
1746 bp->b_data = bp->b_kvabase;
1747 BUF_CHECK_MAPPED(bp);
1755 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
1756 * callback that fires to avoid returning failure.
1759 bufkva_reclaim(vmem_t *vmem, int flags)
1763 for (i = 0; i < 5; i++)
1764 if (buf_scan(true) != 0)
1771 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1772 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1773 * the buffer is valid and we do not have to do anything.
1776 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1777 int cnt, struct ucred * cred)
1782 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1783 if (inmem(vp, *rablkno))
1785 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1787 if ((rabp->b_flags & B_CACHE) == 0) {
1788 if (!TD_IS_IDLETHREAD(curthread)) {
1792 racct_add_buf(curproc, rabp, 0);
1793 PROC_UNLOCK(curproc);
1796 curthread->td_ru.ru_inblock++;
1798 rabp->b_flags |= B_ASYNC;
1799 rabp->b_flags &= ~B_INVAL;
1800 rabp->b_ioflags &= ~BIO_ERROR;
1801 rabp->b_iocmd = BIO_READ;
1802 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1803 rabp->b_rcred = crhold(cred);
1804 vfs_busy_pages(rabp, 0);
1806 rabp->b_iooffset = dbtob(rabp->b_blkno);
1815 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1817 * Get a buffer with the specified data. Look in the cache first. We
1818 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1819 * is set, the buffer is valid and we do not have to do anything, see
1820 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1822 * Always return a NULL buffer pointer (in bpp) when returning an error.
1825 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1826 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1829 int rv = 0, readwait = 0;
1831 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1833 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1835 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1839 /* if not found in cache, do some I/O */
1840 if ((bp->b_flags & B_CACHE) == 0) {
1841 if (!TD_IS_IDLETHREAD(curthread)) {
1845 racct_add_buf(curproc, bp, 0);
1846 PROC_UNLOCK(curproc);
1849 curthread->td_ru.ru_inblock++;
1851 bp->b_iocmd = BIO_READ;
1852 bp->b_flags &= ~B_INVAL;
1853 bp->b_ioflags &= ~BIO_ERROR;
1854 if (bp->b_rcred == NOCRED && cred != NOCRED)
1855 bp->b_rcred = crhold(cred);
1856 vfs_busy_pages(bp, 0);
1857 bp->b_iooffset = dbtob(bp->b_blkno);
1862 breada(vp, rablkno, rabsize, cnt, cred);
1875 * Write, release buffer on completion. (Done by iodone
1876 * if async). Do not bother writing anything if the buffer
1879 * Note that we set B_CACHE here, indicating that buffer is
1880 * fully valid and thus cacheable. This is true even of NFS
1881 * now so we set it generally. This could be set either here
1882 * or in biodone() since the I/O is synchronous. We put it
1886 bufwrite(struct buf *bp)
1893 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1894 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
1895 bp->b_flags |= B_INVAL | B_RELBUF;
1896 bp->b_flags &= ~B_CACHE;
1900 if (bp->b_flags & B_INVAL) {
1905 if (bp->b_flags & B_BARRIER)
1908 oldflags = bp->b_flags;
1910 BUF_ASSERT_HELD(bp);
1912 if (bp->b_pin_count > 0)
1915 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1916 ("FFS background buffer should not get here %p", bp));
1920 vp_md = vp->v_vflag & VV_MD;
1925 * Mark the buffer clean. Increment the bufobj write count
1926 * before bundirty() call, to prevent other thread from seeing
1927 * empty dirty list and zero counter for writes in progress,
1928 * falsely indicating that the bufobj is clean.
1930 bufobj_wref(bp->b_bufobj);
1933 bp->b_flags &= ~B_DONE;
1934 bp->b_ioflags &= ~BIO_ERROR;
1935 bp->b_flags |= B_CACHE;
1936 bp->b_iocmd = BIO_WRITE;
1938 vfs_busy_pages(bp, 1);
1941 * Normal bwrites pipeline writes
1943 bp->b_runningbufspace = bp->b_bufsize;
1944 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1946 if (!TD_IS_IDLETHREAD(curthread)) {
1950 racct_add_buf(curproc, bp, 1);
1951 PROC_UNLOCK(curproc);
1954 curthread->td_ru.ru_oublock++;
1956 if (oldflags & B_ASYNC)
1958 bp->b_iooffset = dbtob(bp->b_blkno);
1961 if ((oldflags & B_ASYNC) == 0) {
1962 int rtval = bufwait(bp);
1965 } else if (space > hirunningspace) {
1967 * don't allow the async write to saturate the I/O
1968 * system. We will not deadlock here because
1969 * we are blocking waiting for I/O that is already in-progress
1970 * to complete. We do not block here if it is the update
1971 * or syncer daemon trying to clean up as that can lead
1974 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1975 waitrunningbufspace();
1982 bufbdflush(struct bufobj *bo, struct buf *bp)
1986 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1987 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1989 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1992 * Try to find a buffer to flush.
1994 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1995 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1997 LK_EXCLUSIVE | LK_NOWAIT, NULL))
2000 panic("bdwrite: found ourselves");
2002 /* Don't countdeps with the bo lock held. */
2003 if (buf_countdeps(nbp, 0)) {
2008 if (nbp->b_flags & B_CLUSTEROK) {
2009 vfs_bio_awrite(nbp);
2014 dirtybufferflushes++;
2023 * Delayed write. (Buffer is marked dirty). Do not bother writing
2024 * anything if the buffer is marked invalid.
2026 * Note that since the buffer must be completely valid, we can safely
2027 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2028 * biodone() in order to prevent getblk from writing the buffer
2029 * out synchronously.
2032 bdwrite(struct buf *bp)
2034 struct thread *td = curthread;
2038 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2039 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2040 KASSERT((bp->b_flags & B_BARRIER) == 0,
2041 ("Barrier request in delayed write %p", bp));
2042 BUF_ASSERT_HELD(bp);
2044 if (bp->b_flags & B_INVAL) {
2050 * If we have too many dirty buffers, don't create any more.
2051 * If we are wildly over our limit, then force a complete
2052 * cleanup. Otherwise, just keep the situation from getting
2053 * out of control. Note that we have to avoid a recursive
2054 * disaster and not try to clean up after our own cleanup!
2058 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2059 td->td_pflags |= TDP_INBDFLUSH;
2061 td->td_pflags &= ~TDP_INBDFLUSH;
2067 * Set B_CACHE, indicating that the buffer is fully valid. This is
2068 * true even of NFS now.
2070 bp->b_flags |= B_CACHE;
2073 * This bmap keeps the system from needing to do the bmap later,
2074 * perhaps when the system is attempting to do a sync. Since it
2075 * is likely that the indirect block -- or whatever other datastructure
2076 * that the filesystem needs is still in memory now, it is a good
2077 * thing to do this. Note also, that if the pageout daemon is
2078 * requesting a sync -- there might not be enough memory to do
2079 * the bmap then... So, this is important to do.
2081 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2082 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2086 * Set the *dirty* buffer range based upon the VM system dirty
2089 * Mark the buffer pages as clean. We need to do this here to
2090 * satisfy the vnode_pager and the pageout daemon, so that it
2091 * thinks that the pages have been "cleaned". Note that since
2092 * the pages are in a delayed write buffer -- the VFS layer
2093 * "will" see that the pages get written out on the next sync,
2094 * or perhaps the cluster will be completed.
2096 vfs_clean_pages_dirty_buf(bp);
2100 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2101 * due to the softdep code.
2108 * Turn buffer into delayed write request. We must clear BIO_READ and
2109 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2110 * itself to properly update it in the dirty/clean lists. We mark it
2111 * B_DONE to ensure that any asynchronization of the buffer properly
2112 * clears B_DONE ( else a panic will occur later ).
2114 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2115 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2116 * should only be called if the buffer is known-good.
2118 * Since the buffer is not on a queue, we do not update the numfreebuffers
2121 * The buffer must be on QUEUE_NONE.
2124 bdirty(struct buf *bp)
2127 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2128 bp, bp->b_vp, bp->b_flags);
2129 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2130 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2131 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2132 BUF_ASSERT_HELD(bp);
2133 bp->b_flags &= ~(B_RELBUF);
2134 bp->b_iocmd = BIO_WRITE;
2136 if ((bp->b_flags & B_DELWRI) == 0) {
2137 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2146 * Clear B_DELWRI for buffer.
2148 * Since the buffer is not on a queue, we do not update the numfreebuffers
2151 * The buffer must be on QUEUE_NONE.
2155 bundirty(struct buf *bp)
2158 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2159 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2160 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2161 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2162 BUF_ASSERT_HELD(bp);
2164 if (bp->b_flags & B_DELWRI) {
2165 bp->b_flags &= ~B_DELWRI;
2170 * Since it is now being written, we can clear its deferred write flag.
2172 bp->b_flags &= ~B_DEFERRED;
2178 * Asynchronous write. Start output on a buffer, but do not wait for
2179 * it to complete. The buffer is released when the output completes.
2181 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2182 * B_INVAL buffers. Not us.
2185 bawrite(struct buf *bp)
2188 bp->b_flags |= B_ASYNC;
2195 * Asynchronous barrier write. Start output on a buffer, but do not
2196 * wait for it to complete. Place a write barrier after this write so
2197 * that this buffer and all buffers written before it are committed to
2198 * the disk before any buffers written after this write are committed
2199 * to the disk. The buffer is released when the output completes.
2202 babarrierwrite(struct buf *bp)
2205 bp->b_flags |= B_ASYNC | B_BARRIER;
2212 * Synchronous barrier write. Start output on a buffer and wait for
2213 * it to complete. Place a write barrier after this write so that
2214 * this buffer and all buffers written before it are committed to
2215 * the disk before any buffers written after this write are committed
2216 * to the disk. The buffer is released when the output completes.
2219 bbarrierwrite(struct buf *bp)
2222 bp->b_flags |= B_BARRIER;
2223 return (bwrite(bp));
2229 * Called prior to the locking of any vnodes when we are expecting to
2230 * write. We do not want to starve the buffer cache with too many
2231 * dirty buffers so we block here. By blocking prior to the locking
2232 * of any vnodes we attempt to avoid the situation where a locked vnode
2233 * prevents the various system daemons from flushing related buffers.
2239 if (numdirtybuffers >= hidirtybuffers) {
2240 mtx_lock(&bdirtylock);
2241 while (numdirtybuffers >= hidirtybuffers) {
2243 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2246 mtx_unlock(&bdirtylock);
2251 * Return true if we have too many dirty buffers.
2254 buf_dirty_count_severe(void)
2257 return(numdirtybuffers >= hidirtybuffers);
2263 * Release a busy buffer and, if requested, free its resources. The
2264 * buffer will be stashed in the appropriate bufqueue[] allowing it
2265 * to be accessed later as a cache entity or reused for other purposes.
2268 brelse(struct buf *bp)
2273 * Many functions erroneously call brelse with a NULL bp under rare
2274 * error conditions. Simply return when called with a NULL bp.
2278 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2279 bp, bp->b_vp, bp->b_flags);
2280 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2281 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2282 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2283 ("brelse: non-VMIO buffer marked NOREUSE"));
2285 if (BUF_LOCKRECURSED(bp)) {
2287 * Do not process, in particular, do not handle the
2288 * B_INVAL/B_RELBUF and do not release to free list.
2294 if (bp->b_flags & B_MANAGED) {
2299 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2300 BO_LOCK(bp->b_bufobj);
2301 bp->b_vflags &= ~BV_BKGRDERR;
2302 BO_UNLOCK(bp->b_bufobj);
2305 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2306 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2307 !(bp->b_flags & B_INVAL)) {
2309 * Failed write, redirty. All errors except ENXIO (which
2310 * means the device is gone) are expected to be potentially
2311 * transient - underlying media might work if tried again
2312 * after EIO, and memory might be available after an ENOMEM.
2314 * Do this also for buffers that failed with ENXIO, but have
2315 * non-empty dependencies - the soft updates code might need
2316 * to access the buffer to untangle them.
2318 * Must clear BIO_ERROR to prevent pages from being scrapped.
2320 bp->b_ioflags &= ~BIO_ERROR;
2322 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2323 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2325 * Either a failed read I/O, or we were asked to free or not
2326 * cache the buffer, or we failed to write to a device that's
2327 * no longer present.
2329 bp->b_flags |= B_INVAL;
2330 if (!LIST_EMPTY(&bp->b_dep))
2332 if (bp->b_flags & B_DELWRI)
2334 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2335 if ((bp->b_flags & B_VMIO) == 0) {
2343 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2344 * is called with B_DELWRI set, the underlying pages may wind up
2345 * getting freed causing a previous write (bdwrite()) to get 'lost'
2346 * because pages associated with a B_DELWRI bp are marked clean.
2348 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2349 * if B_DELWRI is set.
2351 if (bp->b_flags & B_DELWRI)
2352 bp->b_flags &= ~B_RELBUF;
2355 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2356 * constituted, not even NFS buffers now. Two flags effect this. If
2357 * B_INVAL, the struct buf is invalidated but the VM object is kept
2358 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2360 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2361 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2362 * buffer is also B_INVAL because it hits the re-dirtying code above.
2364 * Normally we can do this whether a buffer is B_DELWRI or not. If
2365 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2366 * the commit state and we cannot afford to lose the buffer. If the
2367 * buffer has a background write in progress, we need to keep it
2368 * around to prevent it from being reconstituted and starting a second
2371 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2372 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2373 !(bp->b_vp->v_mount != NULL &&
2374 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2375 !vn_isdisk(bp->b_vp, NULL) && (bp->b_flags & B_DELWRI))) {
2376 vfs_vmio_invalidate(bp);
2380 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2381 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2383 bp->b_flags &= ~B_NOREUSE;
2384 if (bp->b_vp != NULL)
2389 * If the buffer has junk contents signal it and eventually
2390 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2393 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2394 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2395 bp->b_flags |= B_INVAL;
2396 if (bp->b_flags & B_INVAL) {
2397 if (bp->b_flags & B_DELWRI)
2403 /* buffers with no memory */
2404 if (bp->b_bufsize == 0) {
2408 /* buffers with junk contents */
2409 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2410 (bp->b_ioflags & BIO_ERROR)) {
2411 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2412 if (bp->b_vflags & BV_BKGRDINPROG)
2413 panic("losing buffer 2");
2414 qindex = QUEUE_CLEAN;
2415 bp->b_flags |= B_AGE;
2416 /* remaining buffers */
2417 } else if (bp->b_flags & B_DELWRI)
2418 qindex = QUEUE_DIRTY;
2420 qindex = QUEUE_CLEAN;
2422 binsfree(bp, qindex);
2424 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
2425 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2426 panic("brelse: not dirty");
2429 if (qindex == QUEUE_CLEAN)
2434 * Release a buffer back to the appropriate queue but do not try to free
2435 * it. The buffer is expected to be used again soon.
2437 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2438 * biodone() to requeue an async I/O on completion. It is also used when
2439 * known good buffers need to be requeued but we think we may need the data
2442 * XXX we should be able to leave the B_RELBUF hint set on completion.
2445 bqrelse(struct buf *bp)
2449 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2450 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2451 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2453 qindex = QUEUE_NONE;
2454 if (BUF_LOCKRECURSED(bp)) {
2455 /* do not release to free list */
2459 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2461 if (bp->b_flags & B_MANAGED) {
2462 if (bp->b_flags & B_REMFREE)
2467 /* buffers with stale but valid contents */
2468 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2469 BV_BKGRDERR)) == BV_BKGRDERR) {
2470 BO_LOCK(bp->b_bufobj);
2471 bp->b_vflags &= ~BV_BKGRDERR;
2472 BO_UNLOCK(bp->b_bufobj);
2473 qindex = QUEUE_DIRTY;
2475 if ((bp->b_flags & B_DELWRI) == 0 &&
2476 (bp->b_xflags & BX_VNDIRTY))
2477 panic("bqrelse: not dirty");
2478 if ((bp->b_flags & B_NOREUSE) != 0) {
2482 qindex = QUEUE_CLEAN;
2484 binsfree(bp, qindex);
2489 if (qindex == QUEUE_CLEAN)
2494 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2495 * restore bogus pages.
2498 vfs_vmio_iodone(struct buf *bp)
2504 int bogus, i, iosize;
2506 obj = bp->b_bufobj->bo_object;
2507 KASSERT(obj->paging_in_progress >= bp->b_npages,
2508 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2509 obj->paging_in_progress, bp->b_npages));
2512 KASSERT(vp->v_holdcnt > 0,
2513 ("vfs_vmio_iodone: vnode %p has zero hold count", vp));
2514 KASSERT(vp->v_object != NULL,
2515 ("vfs_vmio_iodone: vnode %p has no vm_object", vp));
2517 foff = bp->b_offset;
2518 KASSERT(bp->b_offset != NOOFFSET,
2519 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2522 iosize = bp->b_bcount - bp->b_resid;
2523 VM_OBJECT_WLOCK(obj);
2524 for (i = 0; i < bp->b_npages; i++) {
2527 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2532 * cleanup bogus pages, restoring the originals
2535 if (m == bogus_page) {
2537 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2539 panic("biodone: page disappeared!");
2541 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2543 * In the write case, the valid and clean bits are
2544 * already changed correctly ( see bdwrite() ), so we
2545 * only need to do this here in the read case.
2547 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2548 resid)) == 0, ("vfs_vmio_iodone: page %p "
2549 "has unexpected dirty bits", m));
2550 vfs_page_set_valid(bp, foff, m);
2552 KASSERT(OFF_TO_IDX(foff) == m->pindex,
2553 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
2554 (intmax_t)foff, (uintmax_t)m->pindex));
2557 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2560 vm_object_pip_wakeupn(obj, bp->b_npages);
2561 VM_OBJECT_WUNLOCK(obj);
2562 if (bogus && buf_mapped(bp)) {
2563 BUF_CHECK_MAPPED(bp);
2564 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2565 bp->b_pages, bp->b_npages);
2570 * Unwire a page held by a buf and place it on the appropriate vm queue.
2573 vfs_vmio_unwire(struct buf *bp, vm_page_t m)
2578 if (vm_page_unwire(m, PQ_NONE)) {
2580 * Determine if the page should be freed before adding
2581 * it to the inactive queue.
2583 if (m->valid == 0) {
2584 freed = !vm_page_busied(m);
2587 } else if ((bp->b_flags & B_DIRECT) != 0)
2588 freed = vm_page_try_to_free(m);
2593 * If the page is unlikely to be reused, let the
2594 * VM know. Otherwise, maintain LRU page
2595 * ordering and put the page at the tail of the
2598 if ((bp->b_flags & B_NOREUSE) != 0)
2599 vm_page_deactivate_noreuse(m);
2601 vm_page_deactivate(m);
2608 * Perform page invalidation when a buffer is released. The fully invalid
2609 * pages will be reclaimed later in vfs_vmio_truncate().
2612 vfs_vmio_invalidate(struct buf *bp)
2616 int i, resid, poffset, presid;
2618 if (buf_mapped(bp)) {
2619 BUF_CHECK_MAPPED(bp);
2620 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
2622 BUF_CHECK_UNMAPPED(bp);
2624 * Get the base offset and length of the buffer. Note that
2625 * in the VMIO case if the buffer block size is not
2626 * page-aligned then b_data pointer may not be page-aligned.
2627 * But our b_pages[] array *IS* page aligned.
2629 * block sizes less then DEV_BSIZE (usually 512) are not
2630 * supported due to the page granularity bits (m->valid,
2631 * m->dirty, etc...).
2633 * See man buf(9) for more information
2635 obj = bp->b_bufobj->bo_object;
2636 resid = bp->b_bufsize;
2637 poffset = bp->b_offset & PAGE_MASK;
2638 VM_OBJECT_WLOCK(obj);
2639 for (i = 0; i < bp->b_npages; i++) {
2641 if (m == bogus_page)
2642 panic("vfs_vmio_invalidate: Unexpected bogus page.");
2643 bp->b_pages[i] = NULL;
2645 presid = resid > (PAGE_SIZE - poffset) ?
2646 (PAGE_SIZE - poffset) : resid;
2647 KASSERT(presid >= 0, ("brelse: extra page"));
2648 while (vm_page_xbusied(m)) {
2650 VM_OBJECT_WUNLOCK(obj);
2651 vm_page_busy_sleep(m, "mbncsh", true);
2652 VM_OBJECT_WLOCK(obj);
2654 if (pmap_page_wired_mappings(m) == 0)
2655 vm_page_set_invalid(m, poffset, presid);
2656 vfs_vmio_unwire(bp, m);
2660 VM_OBJECT_WUNLOCK(obj);
2665 * Page-granular truncation of an existing VMIO buffer.
2668 vfs_vmio_truncate(struct buf *bp, int desiredpages)
2674 if (bp->b_npages == desiredpages)
2677 if (buf_mapped(bp)) {
2678 BUF_CHECK_MAPPED(bp);
2679 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
2680 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
2682 BUF_CHECK_UNMAPPED(bp);
2683 obj = bp->b_bufobj->bo_object;
2685 VM_OBJECT_WLOCK(obj);
2686 for (i = desiredpages; i < bp->b_npages; i++) {
2688 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
2689 bp->b_pages[i] = NULL;
2690 vfs_vmio_unwire(bp, m);
2693 VM_OBJECT_WUNLOCK(obj);
2694 bp->b_npages = desiredpages;
2698 * Byte granular extension of VMIO buffers.
2701 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
2704 * We are growing the buffer, possibly in a
2705 * byte-granular fashion.
2713 * Step 1, bring in the VM pages from the object, allocating
2714 * them if necessary. We must clear B_CACHE if these pages
2715 * are not valid for the range covered by the buffer.
2717 obj = bp->b_bufobj->bo_object;
2718 VM_OBJECT_WLOCK(obj);
2719 while (bp->b_npages < desiredpages) {
2721 * We must allocate system pages since blocking
2722 * here could interfere with paging I/O, no
2723 * matter which process we are.
2725 * Only exclusive busy can be tested here.
2726 * Blocking on shared busy might lead to
2727 * deadlocks once allocbuf() is called after
2728 * pages are vfs_busy_pages().
2730 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) + bp->b_npages,
2731 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2732 VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY |
2733 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
2735 bp->b_flags &= ~B_CACHE;
2736 bp->b_pages[bp->b_npages] = m;
2741 * Step 2. We've loaded the pages into the buffer,
2742 * we have to figure out if we can still have B_CACHE
2743 * set. Note that B_CACHE is set according to the
2744 * byte-granular range ( bcount and size ), not the
2745 * aligned range ( newbsize ).
2747 * The VM test is against m->valid, which is DEV_BSIZE
2748 * aligned. Needless to say, the validity of the data
2749 * needs to also be DEV_BSIZE aligned. Note that this
2750 * fails with NFS if the server or some other client
2751 * extends the file's EOF. If our buffer is resized,
2752 * B_CACHE may remain set! XXX
2754 toff = bp->b_bcount;
2755 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2756 while ((bp->b_flags & B_CACHE) && toff < size) {
2759 if (tinc > (size - toff))
2761 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
2762 m = bp->b_pages[pi];
2763 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
2767 VM_OBJECT_WUNLOCK(obj);
2770 * Step 3, fixup the KVA pmap.
2775 BUF_CHECK_UNMAPPED(bp);
2779 * Check to see if a block at a particular lbn is available for a clustered
2783 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
2790 /* If the buf isn't in core skip it */
2791 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
2794 /* If the buf is busy we don't want to wait for it */
2795 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2798 /* Only cluster with valid clusterable delayed write buffers */
2799 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
2800 (B_DELWRI | B_CLUSTEROK))
2803 if (bpa->b_bufsize != size)
2807 * Check to see if it is in the expected place on disk and that the
2808 * block has been mapped.
2810 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
2820 * Implement clustered async writes for clearing out B_DELWRI buffers.
2821 * This is much better then the old way of writing only one buffer at
2822 * a time. Note that we may not be presented with the buffers in the
2823 * correct order, so we search for the cluster in both directions.
2826 vfs_bio_awrite(struct buf *bp)
2831 daddr_t lblkno = bp->b_lblkno;
2832 struct vnode *vp = bp->b_vp;
2840 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
2842 * right now we support clustered writing only to regular files. If
2843 * we find a clusterable block we could be in the middle of a cluster
2844 * rather then at the beginning.
2846 if ((vp->v_type == VREG) &&
2847 (vp->v_mount != 0) && /* Only on nodes that have the size info */
2848 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2850 size = vp->v_mount->mnt_stat.f_iosize;
2851 maxcl = MAXPHYS / size;
2854 for (i = 1; i < maxcl; i++)
2855 if (vfs_bio_clcheck(vp, size, lblkno + i,
2856 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2859 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2860 if (vfs_bio_clcheck(vp, size, lblkno - j,
2861 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2867 * this is a possible cluster write
2871 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2877 bp->b_flags |= B_ASYNC;
2879 * default (old) behavior, writing out only one block
2881 * XXX returns b_bufsize instead of b_bcount for nwritten?
2883 nwritten = bp->b_bufsize;
2892 * Allocate KVA for an empty buf header according to gbflags.
2895 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
2898 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
2900 * In order to keep fragmentation sane we only allocate kva
2901 * in BKVASIZE chunks. XXX with vmem we can do page size.
2903 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2905 if (maxsize != bp->b_kvasize &&
2906 bufkva_alloc(bp, maxsize, gbflags))
2915 * Find and initialize a new buffer header, freeing up existing buffers
2916 * in the bufqueues as necessary. The new buffer is returned locked.
2919 * We have insufficient buffer headers
2920 * We have insufficient buffer space
2921 * buffer_arena is too fragmented ( space reservation fails )
2922 * If we have to flush dirty buffers ( but we try to avoid this )
2924 * The caller is responsible for releasing the reserved bufspace after
2925 * allocbuf() is called.
2928 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
2931 bool metadata, reserved;
2934 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2935 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2936 if (!unmapped_buf_allowed)
2937 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2939 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2944 atomic_add_int(&getnewbufcalls, 1);
2947 if (reserved == false &&
2948 bufspace_reserve(maxsize, metadata) != 0)
2951 if ((bp = buf_alloc()) == NULL)
2953 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
2956 } while(buf_scan(false) == 0);
2959 atomic_subtract_long(&bufspace, maxsize);
2961 bp->b_flags |= B_INVAL;
2964 bufspace_wait(vp, gbflags, slpflag, slptimeo);
2972 * buffer flushing daemon. Buffers are normally flushed by the
2973 * update daemon but if it cannot keep up this process starts to
2974 * take the load in an attempt to prevent getnewbuf() from blocking.
2976 static struct kproc_desc buf_kp = {
2981 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2984 buf_flush(struct vnode *vp, int target)
2988 flushed = flushbufqueues(vp, target, 0);
2991 * Could not find any buffers without rollback
2992 * dependencies, so just write the first one
2993 * in the hopes of eventually making progress.
2995 if (vp != NULL && target > 2)
2997 flushbufqueues(vp, target, 1);
3008 * This process needs to be suspended prior to shutdown sync.
3010 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
3014 * This process is allowed to take the buffer cache to the limit
3016 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3020 mtx_unlock(&bdlock);
3022 kproc_suspend_check(bufdaemonproc);
3023 lodirty = lodirtybuffers;
3024 if (bd_speedupreq) {
3025 lodirty = numdirtybuffers / 2;
3029 * Do the flush. Limit the amount of in-transit I/O we
3030 * allow to build up, otherwise we would completely saturate
3033 while (numdirtybuffers > lodirty) {
3034 if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
3036 kern_yield(PRI_USER);
3040 * Only clear bd_request if we have reached our low water
3041 * mark. The buf_daemon normally waits 1 second and
3042 * then incrementally flushes any dirty buffers that have
3043 * built up, within reason.
3045 * If we were unable to hit our low water mark and couldn't
3046 * find any flushable buffers, we sleep for a short period
3047 * to avoid endless loops on unlockable buffers.
3050 if (numdirtybuffers <= lodirtybuffers) {
3052 * We reached our low water mark, reset the
3053 * request and sleep until we are needed again.
3054 * The sleep is just so the suspend code works.
3058 * Do an extra wakeup in case dirty threshold
3059 * changed via sysctl and the explicit transition
3060 * out of shortfall was missed.
3063 if (runningbufspace <= lorunningspace)
3065 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3068 * We couldn't find any flushable dirty buffers but
3069 * still have too many dirty buffers, we
3070 * have to sleep and try again. (rare)
3072 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3080 * Try to flush a buffer in the dirty queue. We must be careful to
3081 * free up B_INVAL buffers instead of write them, which NFS is
3082 * particularly sensitive to.
3084 static int flushwithdeps = 0;
3085 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
3086 0, "Number of buffers flushed with dependecies that require rollbacks");
3089 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
3091 struct buf *sentinel;
3102 queue = QUEUE_DIRTY;
3104 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3105 sentinel->b_qindex = QUEUE_SENTINEL;
3106 mtx_lock(&bqlocks[queue]);
3107 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
3108 mtx_unlock(&bqlocks[queue]);
3109 while (flushed != target) {
3111 mtx_lock(&bqlocks[queue]);
3112 bp = TAILQ_NEXT(sentinel, b_freelist);
3114 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3115 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
3118 mtx_unlock(&bqlocks[queue]);
3122 * Skip sentinels inserted by other invocations of the
3123 * flushbufqueues(), taking care to not reorder them.
3125 * Only flush the buffers that belong to the
3126 * vnode locked by the curthread.
3128 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3130 mtx_unlock(&bqlocks[queue]);
3133 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3134 mtx_unlock(&bqlocks[queue]);
3137 if (bp->b_pin_count > 0) {
3142 * BKGRDINPROG can only be set with the buf and bufobj
3143 * locks both held. We tolerate a race to clear it here.
3145 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3146 (bp->b_flags & B_DELWRI) == 0) {
3150 if (bp->b_flags & B_INVAL) {
3157 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3158 if (flushdeps == 0) {
3166 * We must hold the lock on a vnode before writing
3167 * one of its buffers. Otherwise we may confuse, or
3168 * in the case of a snapshot vnode, deadlock the
3171 * The lock order here is the reverse of the normal
3172 * of vnode followed by buf lock. This is ok because
3173 * the NOWAIT will prevent deadlock.
3176 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3182 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3184 ASSERT_VOP_LOCKED(vp, "getbuf");
3186 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3187 vn_lock(vp, LK_TRYUPGRADE);
3190 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3191 bp, bp->b_vp, bp->b_flags);
3192 if (curproc == bufdaemonproc) {
3199 vn_finished_write(mp);
3202 flushwithdeps += hasdeps;
3206 * Sleeping on runningbufspace while holding
3207 * vnode lock leads to deadlock.
3209 if (curproc == bufdaemonproc &&
3210 runningbufspace > hirunningspace)
3211 waitrunningbufspace();
3214 vn_finished_write(mp);
3217 mtx_lock(&bqlocks[queue]);
3218 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3219 mtx_unlock(&bqlocks[queue]);
3220 free(sentinel, M_TEMP);
3225 * Check to see if a block is currently memory resident.
3228 incore(struct bufobj *bo, daddr_t blkno)
3233 bp = gbincore(bo, blkno);
3239 * Returns true if no I/O is needed to access the
3240 * associated VM object. This is like incore except
3241 * it also hunts around in the VM system for the data.
3245 inmem(struct vnode * vp, daddr_t blkno)
3248 vm_offset_t toff, tinc, size;
3252 ASSERT_VOP_LOCKED(vp, "inmem");
3254 if (incore(&vp->v_bufobj, blkno))
3256 if (vp->v_mount == NULL)
3263 if (size > vp->v_mount->mnt_stat.f_iosize)
3264 size = vp->v_mount->mnt_stat.f_iosize;
3265 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3267 VM_OBJECT_RLOCK(obj);
3268 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3269 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
3273 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3274 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3275 if (vm_page_is_valid(m,
3276 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
3279 VM_OBJECT_RUNLOCK(obj);
3283 VM_OBJECT_RUNLOCK(obj);
3288 * Set the dirty range for a buffer based on the status of the dirty
3289 * bits in the pages comprising the buffer. The range is limited
3290 * to the size of the buffer.
3292 * Tell the VM system that the pages associated with this buffer
3293 * are clean. This is used for delayed writes where the data is
3294 * going to go to disk eventually without additional VM intevention.
3296 * Note that while we only really need to clean through to b_bcount, we
3297 * just go ahead and clean through to b_bufsize.
3300 vfs_clean_pages_dirty_buf(struct buf *bp)
3302 vm_ooffset_t foff, noff, eoff;
3306 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3309 foff = bp->b_offset;
3310 KASSERT(bp->b_offset != NOOFFSET,
3311 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3313 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3314 vfs_drain_busy_pages(bp);
3315 vfs_setdirty_locked_object(bp);
3316 for (i = 0; i < bp->b_npages; i++) {
3317 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3319 if (eoff > bp->b_offset + bp->b_bufsize)
3320 eoff = bp->b_offset + bp->b_bufsize;
3322 vfs_page_set_validclean(bp, foff, m);
3323 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3326 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3330 vfs_setdirty_locked_object(struct buf *bp)
3335 object = bp->b_bufobj->bo_object;
3336 VM_OBJECT_ASSERT_WLOCKED(object);
3339 * We qualify the scan for modified pages on whether the
3340 * object has been flushed yet.
3342 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
3343 vm_offset_t boffset;
3344 vm_offset_t eoffset;
3347 * test the pages to see if they have been modified directly
3348 * by users through the VM system.
3350 for (i = 0; i < bp->b_npages; i++)
3351 vm_page_test_dirty(bp->b_pages[i]);
3354 * Calculate the encompassing dirty range, boffset and eoffset,
3355 * (eoffset - boffset) bytes.
3358 for (i = 0; i < bp->b_npages; i++) {
3359 if (bp->b_pages[i]->dirty)
3362 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3364 for (i = bp->b_npages - 1; i >= 0; --i) {
3365 if (bp->b_pages[i]->dirty) {
3369 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3372 * Fit it to the buffer.
3375 if (eoffset > bp->b_bcount)
3376 eoffset = bp->b_bcount;
3379 * If we have a good dirty range, merge with the existing
3383 if (boffset < eoffset) {
3384 if (bp->b_dirtyoff > boffset)
3385 bp->b_dirtyoff = boffset;
3386 if (bp->b_dirtyend < eoffset)
3387 bp->b_dirtyend = eoffset;
3393 * Allocate the KVA mapping for an existing buffer.
3394 * If an unmapped buffer is provided but a mapped buffer is requested, take
3395 * also care to properly setup mappings between pages and KVA.
3398 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3400 int bsize, maxsize, need_mapping, need_kva;
3403 need_mapping = bp->b_data == unmapped_buf &&
3404 (gbflags & GB_UNMAPPED) == 0;
3405 need_kva = bp->b_kvabase == unmapped_buf &&
3406 bp->b_data == unmapped_buf &&
3407 (gbflags & GB_KVAALLOC) != 0;
3408 if (!need_mapping && !need_kva)
3411 BUF_CHECK_UNMAPPED(bp);
3413 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3415 * Buffer is not mapped, but the KVA was already
3416 * reserved at the time of the instantiation. Use the
3423 * Calculate the amount of the address space we would reserve
3424 * if the buffer was mapped.
3426 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3427 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3428 offset = blkno * bsize;
3429 maxsize = size + (offset & PAGE_MASK);
3430 maxsize = imax(maxsize, bsize);
3432 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3433 if ((gbflags & GB_NOWAIT_BD) != 0) {
3435 * XXXKIB: defragmentation cannot
3436 * succeed, not sure what else to do.
3438 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3440 atomic_add_int(&mappingrestarts, 1);
3441 bufspace_wait(bp->b_vp, gbflags, 0, 0);
3445 /* b_offset is handled by bpmap_qenter. */
3446 bp->b_data = bp->b_kvabase;
3447 BUF_CHECK_MAPPED(bp);
3455 * Get a block given a specified block and offset into a file/device.
3456 * The buffers B_DONE bit will be cleared on return, making it almost
3457 * ready for an I/O initiation. B_INVAL may or may not be set on
3458 * return. The caller should clear B_INVAL prior to initiating a
3461 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3462 * an existing buffer.
3464 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3465 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3466 * and then cleared based on the backing VM. If the previous buffer is
3467 * non-0-sized but invalid, B_CACHE will be cleared.
3469 * If getblk() must create a new buffer, the new buffer is returned with
3470 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3471 * case it is returned with B_INVAL clear and B_CACHE set based on the
3474 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3475 * B_CACHE bit is clear.
3477 * What this means, basically, is that the caller should use B_CACHE to
3478 * determine whether the buffer is fully valid or not and should clear
3479 * B_INVAL prior to issuing a read. If the caller intends to validate
3480 * the buffer by loading its data area with something, the caller needs
3481 * to clear B_INVAL. If the caller does this without issuing an I/O,
3482 * the caller should set B_CACHE ( as an optimization ), else the caller
3483 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3484 * a write attempt or if it was a successful read. If the caller
3485 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3486 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3489 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3494 int bsize, error, maxsize, vmio;
3497 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3498 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3499 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3500 ASSERT_VOP_LOCKED(vp, "getblk");
3501 if (size > MAXBCACHEBUF)
3502 panic("getblk: size(%d) > MAXBCACHEBUF(%d)\n", size,
3504 if (!unmapped_buf_allowed)
3505 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3510 bp = gbincore(bo, blkno);
3514 * Buffer is in-core. If the buffer is not busy nor managed,
3515 * it must be on a queue.
3517 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3519 if (flags & GB_LOCK_NOWAIT)
3520 lockflags |= LK_NOWAIT;
3522 error = BUF_TIMELOCK(bp, lockflags,
3523 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3526 * If we slept and got the lock we have to restart in case
3527 * the buffer changed identities.
3529 if (error == ENOLCK)
3531 /* We timed out or were interrupted. */
3534 /* If recursed, assume caller knows the rules. */
3535 else if (BUF_LOCKRECURSED(bp))
3539 * The buffer is locked. B_CACHE is cleared if the buffer is
3540 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3541 * and for a VMIO buffer B_CACHE is adjusted according to the
3544 if (bp->b_flags & B_INVAL)
3545 bp->b_flags &= ~B_CACHE;
3546 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3547 bp->b_flags |= B_CACHE;
3548 if (bp->b_flags & B_MANAGED)
3549 MPASS(bp->b_qindex == QUEUE_NONE);
3554 * check for size inconsistencies for non-VMIO case.
3556 if (bp->b_bcount != size) {
3557 if ((bp->b_flags & B_VMIO) == 0 ||
3558 (size > bp->b_kvasize)) {
3559 if (bp->b_flags & B_DELWRI) {
3561 * If buffer is pinned and caller does
3562 * not want sleep waiting for it to be
3563 * unpinned, bail out
3565 if (bp->b_pin_count > 0) {
3566 if (flags & GB_LOCK_NOWAIT) {
3573 bp->b_flags |= B_NOCACHE;
3576 if (LIST_EMPTY(&bp->b_dep)) {
3577 bp->b_flags |= B_RELBUF;
3580 bp->b_flags |= B_NOCACHE;
3589 * Handle the case of unmapped buffer which should
3590 * become mapped, or the buffer for which KVA
3591 * reservation is requested.
3593 bp_unmapped_get_kva(bp, blkno, size, flags);
3596 * If the size is inconsistent in the VMIO case, we can resize
3597 * the buffer. This might lead to B_CACHE getting set or
3598 * cleared. If the size has not changed, B_CACHE remains
3599 * unchanged from its previous state.
3603 KASSERT(bp->b_offset != NOOFFSET,
3604 ("getblk: no buffer offset"));
3607 * A buffer with B_DELWRI set and B_CACHE clear must
3608 * be committed before we can return the buffer in
3609 * order to prevent the caller from issuing a read
3610 * ( due to B_CACHE not being set ) and overwriting
3613 * Most callers, including NFS and FFS, need this to
3614 * operate properly either because they assume they
3615 * can issue a read if B_CACHE is not set, or because
3616 * ( for example ) an uncached B_DELWRI might loop due
3617 * to softupdates re-dirtying the buffer. In the latter
3618 * case, B_CACHE is set after the first write completes,
3619 * preventing further loops.
3620 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3621 * above while extending the buffer, we cannot allow the
3622 * buffer to remain with B_CACHE set after the write
3623 * completes or it will represent a corrupt state. To
3624 * deal with this we set B_NOCACHE to scrap the buffer
3627 * We might be able to do something fancy, like setting
3628 * B_CACHE in bwrite() except if B_DELWRI is already set,
3629 * so the below call doesn't set B_CACHE, but that gets real
3630 * confusing. This is much easier.
3633 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3634 bp->b_flags |= B_NOCACHE;
3638 bp->b_flags &= ~B_DONE;
3641 * Buffer is not in-core, create new buffer. The buffer
3642 * returned by getnewbuf() is locked. Note that the returned
3643 * buffer is also considered valid (not marked B_INVAL).
3647 * If the user does not want us to create the buffer, bail out
3650 if (flags & GB_NOCREAT)
3652 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3655 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3656 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3657 offset = blkno * bsize;
3658 vmio = vp->v_object != NULL;
3660 maxsize = size + (offset & PAGE_MASK);
3663 /* Do not allow non-VMIO notmapped buffers. */
3664 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3666 maxsize = imax(maxsize, bsize);
3668 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
3670 if (slpflag || slptimeo)
3673 * XXX This is here until the sleep path is diagnosed
3674 * enough to work under very low memory conditions.
3676 * There's an issue on low memory, 4BSD+non-preempt
3677 * systems (eg MIPS routers with 32MB RAM) where buffer
3678 * exhaustion occurs without sleeping for buffer
3679 * reclaimation. This just sticks in a loop and
3680 * constantly attempts to allocate a buffer, which
3681 * hits exhaustion and tries to wakeup bufdaemon.
3682 * This never happens because we never yield.
3684 * The real solution is to identify and fix these cases
3685 * so we aren't effectively busy-waiting in a loop
3686 * until the reclaimation path has cycles to run.
3688 kern_yield(PRI_USER);
3693 * This code is used to make sure that a buffer is not
3694 * created while the getnewbuf routine is blocked.
3695 * This can be a problem whether the vnode is locked or not.
3696 * If the buffer is created out from under us, we have to
3697 * throw away the one we just created.
3699 * Note: this must occur before we associate the buffer
3700 * with the vp especially considering limitations in
3701 * the splay tree implementation when dealing with duplicate
3705 if (gbincore(bo, blkno)) {
3707 bp->b_flags |= B_INVAL;
3709 bufspace_release(maxsize);
3714 * Insert the buffer into the hash, so that it can
3715 * be found by incore.
3717 bp->b_blkno = bp->b_lblkno = blkno;
3718 bp->b_offset = offset;
3723 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3724 * buffer size starts out as 0, B_CACHE will be set by
3725 * allocbuf() for the VMIO case prior to it testing the
3726 * backing store for validity.
3730 bp->b_flags |= B_VMIO;
3731 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3732 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3733 bp, vp->v_object, bp->b_bufobj->bo_object));
3735 bp->b_flags &= ~B_VMIO;
3736 KASSERT(bp->b_bufobj->bo_object == NULL,
3737 ("ARGH! has b_bufobj->bo_object %p %p\n",
3738 bp, bp->b_bufobj->bo_object));
3739 BUF_CHECK_MAPPED(bp);
3743 bufspace_release(maxsize);
3744 bp->b_flags &= ~B_DONE;
3746 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3747 BUF_ASSERT_HELD(bp);
3749 KASSERT(bp->b_bufobj == bo,
3750 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3755 * Get an empty, disassociated buffer of given size. The buffer is initially
3759 geteblk(int size, int flags)
3764 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3765 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
3766 if ((flags & GB_NOWAIT_BD) &&
3767 (curthread->td_pflags & TDP_BUFNEED) != 0)
3771 bufspace_release(maxsize);
3772 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3773 BUF_ASSERT_HELD(bp);
3778 * Truncate the backing store for a non-vmio buffer.
3781 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
3784 if (bp->b_flags & B_MALLOC) {
3786 * malloced buffers are not shrunk
3788 if (newbsize == 0) {
3789 bufmallocadjust(bp, 0);
3790 free(bp->b_data, M_BIOBUF);
3791 bp->b_data = bp->b_kvabase;
3792 bp->b_flags &= ~B_MALLOC;
3796 vm_hold_free_pages(bp, newbsize);
3797 bufspace_adjust(bp, newbsize);
3801 * Extend the backing for a non-VMIO buffer.
3804 vfs_nonvmio_extend(struct buf *bp, int newbsize)
3810 * We only use malloced memory on the first allocation.
3811 * and revert to page-allocated memory when the buffer
3814 * There is a potential smp race here that could lead
3815 * to bufmallocspace slightly passing the max. It
3816 * is probably extremely rare and not worth worrying
3819 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
3820 bufmallocspace < maxbufmallocspace) {
3821 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
3822 bp->b_flags |= B_MALLOC;
3823 bufmallocadjust(bp, newbsize);
3828 * If the buffer is growing on its other-than-first
3829 * allocation then we revert to the page-allocation
3834 if (bp->b_flags & B_MALLOC) {
3835 origbuf = bp->b_data;
3836 origbufsize = bp->b_bufsize;
3837 bp->b_data = bp->b_kvabase;
3838 bufmallocadjust(bp, 0);
3839 bp->b_flags &= ~B_MALLOC;
3840 newbsize = round_page(newbsize);
3842 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
3843 (vm_offset_t) bp->b_data + newbsize);
3844 if (origbuf != NULL) {
3845 bcopy(origbuf, bp->b_data, origbufsize);
3846 free(origbuf, M_BIOBUF);
3848 bufspace_adjust(bp, newbsize);
3852 * This code constitutes the buffer memory from either anonymous system
3853 * memory (in the case of non-VMIO operations) or from an associated
3854 * VM object (in the case of VMIO operations). This code is able to
3855 * resize a buffer up or down.
3857 * Note that this code is tricky, and has many complications to resolve
3858 * deadlock or inconsistent data situations. Tread lightly!!!
3859 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3860 * the caller. Calling this code willy nilly can result in the loss of data.
3862 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3863 * B_CACHE for the non-VMIO case.
3866 allocbuf(struct buf *bp, int size)
3870 BUF_ASSERT_HELD(bp);
3872 if (bp->b_bcount == size)
3875 if (bp->b_kvasize != 0 && bp->b_kvasize < size)
3876 panic("allocbuf: buffer too small");
3878 newbsize = roundup2(size, DEV_BSIZE);
3879 if ((bp->b_flags & B_VMIO) == 0) {
3880 if ((bp->b_flags & B_MALLOC) == 0)
3881 newbsize = round_page(newbsize);
3883 * Just get anonymous memory from the kernel. Don't
3884 * mess with B_CACHE.
3886 if (newbsize < bp->b_bufsize)
3887 vfs_nonvmio_truncate(bp, newbsize);
3888 else if (newbsize > bp->b_bufsize)
3889 vfs_nonvmio_extend(bp, newbsize);
3893 desiredpages = (size == 0) ? 0 :
3894 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3896 if (bp->b_flags & B_MALLOC)
3897 panic("allocbuf: VMIO buffer can't be malloced");
3899 * Set B_CACHE initially if buffer is 0 length or will become
3902 if (size == 0 || bp->b_bufsize == 0)
3903 bp->b_flags |= B_CACHE;
3905 if (newbsize < bp->b_bufsize)
3906 vfs_vmio_truncate(bp, desiredpages);
3907 /* XXX This looks as if it should be newbsize > b_bufsize */
3908 else if (size > bp->b_bcount)
3909 vfs_vmio_extend(bp, desiredpages, size);
3910 bufspace_adjust(bp, newbsize);
3912 bp->b_bcount = size; /* requested buffer size. */
3916 extern int inflight_transient_maps;
3919 biodone(struct bio *bp)
3922 void (*done)(struct bio *);
3923 vm_offset_t start, end;
3925 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3926 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3927 bp->bio_flags |= BIO_UNMAPPED;
3928 start = trunc_page((vm_offset_t)bp->bio_data);
3929 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3930 bp->bio_data = unmapped_buf;
3931 pmap_qremove(start, atop(end - start));
3932 vmem_free(transient_arena, start, end - start);
3933 atomic_add_int(&inflight_transient_maps, -1);
3935 done = bp->bio_done;
3937 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3939 bp->bio_flags |= BIO_DONE;
3947 * Wait for a BIO to finish.
3950 biowait(struct bio *bp, const char *wchan)
3954 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3956 while ((bp->bio_flags & BIO_DONE) == 0)
3957 msleep(bp, mtxp, PRIBIO, wchan, 0);
3959 if (bp->bio_error != 0)
3960 return (bp->bio_error);
3961 if (!(bp->bio_flags & BIO_ERROR))
3967 biofinish(struct bio *bp, struct devstat *stat, int error)
3971 bp->bio_error = error;
3972 bp->bio_flags |= BIO_ERROR;
3975 devstat_end_transaction_bio(stat, bp);
3982 * Wait for buffer I/O completion, returning error status. The buffer
3983 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3984 * error and cleared.
3987 bufwait(struct buf *bp)
3989 if (bp->b_iocmd == BIO_READ)
3990 bwait(bp, PRIBIO, "biord");
3992 bwait(bp, PRIBIO, "biowr");
3993 if (bp->b_flags & B_EINTR) {
3994 bp->b_flags &= ~B_EINTR;
3997 if (bp->b_ioflags & BIO_ERROR) {
3998 return (bp->b_error ? bp->b_error : EIO);
4007 * Finish I/O on a buffer, optionally calling a completion function.
4008 * This is usually called from an interrupt so process blocking is
4011 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4012 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
4013 * assuming B_INVAL is clear.
4015 * For the VMIO case, we set B_CACHE if the op was a read and no
4016 * read error occurred, or if the op was a write. B_CACHE is never
4017 * set if the buffer is invalid or otherwise uncacheable.
4019 * biodone does not mess with B_INVAL, allowing the I/O routine or the
4020 * initiator to leave B_INVAL set to brelse the buffer out of existence
4021 * in the biodone routine.
4024 bufdone(struct buf *bp)
4026 struct bufobj *dropobj;
4027 void (*biodone)(struct buf *);
4029 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4032 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4033 BUF_ASSERT_HELD(bp);
4035 runningbufwakeup(bp);
4036 if (bp->b_iocmd == BIO_WRITE)
4037 dropobj = bp->b_bufobj;
4038 /* call optional completion function if requested */
4039 if (bp->b_iodone != NULL) {
4040 biodone = bp->b_iodone;
4041 bp->b_iodone = NULL;
4044 bufobj_wdrop(dropobj);
4051 bufobj_wdrop(dropobj);
4055 bufdone_finish(struct buf *bp)
4057 BUF_ASSERT_HELD(bp);
4059 if (!LIST_EMPTY(&bp->b_dep))
4062 if (bp->b_flags & B_VMIO) {
4064 * Set B_CACHE if the op was a normal read and no error
4065 * occurred. B_CACHE is set for writes in the b*write()
4068 if (bp->b_iocmd == BIO_READ &&
4069 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4070 !(bp->b_ioflags & BIO_ERROR))
4071 bp->b_flags |= B_CACHE;
4072 vfs_vmio_iodone(bp);
4076 * For asynchronous completions, release the buffer now. The brelse
4077 * will do a wakeup there if necessary - so no need to do a wakeup
4078 * here in the async case. The sync case always needs to do a wakeup.
4080 if (bp->b_flags & B_ASYNC) {
4081 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4082 (bp->b_ioflags & BIO_ERROR))
4091 * This routine is called in lieu of iodone in the case of
4092 * incomplete I/O. This keeps the busy status for pages
4096 vfs_unbusy_pages(struct buf *bp)
4102 runningbufwakeup(bp);
4103 if (!(bp->b_flags & B_VMIO))
4106 obj = bp->b_bufobj->bo_object;
4107 VM_OBJECT_WLOCK(obj);
4108 for (i = 0; i < bp->b_npages; i++) {
4110 if (m == bogus_page) {
4111 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4113 panic("vfs_unbusy_pages: page missing\n");
4115 if (buf_mapped(bp)) {
4116 BUF_CHECK_MAPPED(bp);
4117 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4118 bp->b_pages, bp->b_npages);
4120 BUF_CHECK_UNMAPPED(bp);
4124 vm_object_pip_wakeupn(obj, bp->b_npages);
4125 VM_OBJECT_WUNLOCK(obj);
4129 * vfs_page_set_valid:
4131 * Set the valid bits in a page based on the supplied offset. The
4132 * range is restricted to the buffer's size.
4134 * This routine is typically called after a read completes.
4137 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4142 * Compute the end offset, eoff, such that [off, eoff) does not span a
4143 * page boundary and eoff is not greater than the end of the buffer.
4144 * The end of the buffer, in this case, is our file EOF, not the
4145 * allocation size of the buffer.
4147 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4148 if (eoff > bp->b_offset + bp->b_bcount)
4149 eoff = bp->b_offset + bp->b_bcount;
4152 * Set valid range. This is typically the entire buffer and thus the
4156 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4160 * vfs_page_set_validclean:
4162 * Set the valid bits and clear the dirty bits in a page based on the
4163 * supplied offset. The range is restricted to the buffer's size.
4166 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4168 vm_ooffset_t soff, eoff;
4171 * Start and end offsets in buffer. eoff - soff may not cross a
4172 * page boundary or cross the end of the buffer. The end of the
4173 * buffer, in this case, is our file EOF, not the allocation size
4177 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4178 if (eoff > bp->b_offset + bp->b_bcount)
4179 eoff = bp->b_offset + bp->b_bcount;
4182 * Set valid range. This is typically the entire buffer and thus the
4186 vm_page_set_validclean(
4188 (vm_offset_t) (soff & PAGE_MASK),
4189 (vm_offset_t) (eoff - soff)
4195 * Ensure that all buffer pages are not exclusive busied. If any page is
4196 * exclusive busy, drain it.
4199 vfs_drain_busy_pages(struct buf *bp)
4204 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4206 for (i = 0; i < bp->b_npages; i++) {
4208 if (vm_page_xbusied(m)) {
4209 for (; last_busied < i; last_busied++)
4210 vm_page_sbusy(bp->b_pages[last_busied]);
4211 while (vm_page_xbusied(m)) {
4213 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4214 vm_page_busy_sleep(m, "vbpage", true);
4215 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4219 for (i = 0; i < last_busied; i++)
4220 vm_page_sunbusy(bp->b_pages[i]);
4224 * This routine is called before a device strategy routine.
4225 * It is used to tell the VM system that paging I/O is in
4226 * progress, and treat the pages associated with the buffer
4227 * almost as being exclusive busy. Also the object paging_in_progress
4228 * flag is handled to make sure that the object doesn't become
4231 * Since I/O has not been initiated yet, certain buffer flags
4232 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4233 * and should be ignored.
4236 vfs_busy_pages(struct buf *bp, int clear_modify)
4243 if (!(bp->b_flags & B_VMIO))
4246 obj = bp->b_bufobj->bo_object;
4247 foff = bp->b_offset;
4248 KASSERT(bp->b_offset != NOOFFSET,
4249 ("vfs_busy_pages: no buffer offset"));
4250 VM_OBJECT_WLOCK(obj);
4251 vfs_drain_busy_pages(bp);
4252 if (bp->b_bufsize != 0)
4253 vfs_setdirty_locked_object(bp);
4255 for (i = 0; i < bp->b_npages; i++) {
4258 if ((bp->b_flags & B_CLUSTER) == 0) {
4259 vm_object_pip_add(obj, 1);
4263 * When readying a buffer for a read ( i.e
4264 * clear_modify == 0 ), it is important to do
4265 * bogus_page replacement for valid pages in
4266 * partially instantiated buffers. Partially
4267 * instantiated buffers can, in turn, occur when
4268 * reconstituting a buffer from its VM backing store
4269 * base. We only have to do this if B_CACHE is
4270 * clear ( which causes the I/O to occur in the
4271 * first place ). The replacement prevents the read
4272 * I/O from overwriting potentially dirty VM-backed
4273 * pages. XXX bogus page replacement is, uh, bogus.
4274 * It may not work properly with small-block devices.
4275 * We need to find a better way.
4278 pmap_remove_write(m);
4279 vfs_page_set_validclean(bp, foff, m);
4280 } else if (m->valid == VM_PAGE_BITS_ALL &&
4281 (bp->b_flags & B_CACHE) == 0) {
4282 bp->b_pages[i] = bogus_page;
4285 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4287 VM_OBJECT_WUNLOCK(obj);
4288 if (bogus && buf_mapped(bp)) {
4289 BUF_CHECK_MAPPED(bp);
4290 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4291 bp->b_pages, bp->b_npages);
4296 * vfs_bio_set_valid:
4298 * Set the range within the buffer to valid. The range is
4299 * relative to the beginning of the buffer, b_offset. Note that
4300 * b_offset itself may be offset from the beginning of the first
4304 vfs_bio_set_valid(struct buf *bp, int base, int size)
4309 if (!(bp->b_flags & B_VMIO))
4313 * Fixup base to be relative to beginning of first page.
4314 * Set initial n to be the maximum number of bytes in the
4315 * first page that can be validated.
4317 base += (bp->b_offset & PAGE_MASK);
4318 n = PAGE_SIZE - (base & PAGE_MASK);
4320 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4321 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4325 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4330 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4336 * If the specified buffer is a non-VMIO buffer, clear the entire
4337 * buffer. If the specified buffer is a VMIO buffer, clear and
4338 * validate only the previously invalid portions of the buffer.
4339 * This routine essentially fakes an I/O, so we need to clear
4340 * BIO_ERROR and B_INVAL.
4342 * Note that while we only theoretically need to clear through b_bcount,
4343 * we go ahead and clear through b_bufsize.
4346 vfs_bio_clrbuf(struct buf *bp)
4348 int i, j, mask, sa, ea, slide;
4350 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4354 bp->b_flags &= ~B_INVAL;
4355 bp->b_ioflags &= ~BIO_ERROR;
4356 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4357 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4358 (bp->b_offset & PAGE_MASK) == 0) {
4359 if (bp->b_pages[0] == bogus_page)
4361 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4362 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4363 if ((bp->b_pages[0]->valid & mask) == mask)
4365 if ((bp->b_pages[0]->valid & mask) == 0) {
4366 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4367 bp->b_pages[0]->valid |= mask;
4371 sa = bp->b_offset & PAGE_MASK;
4373 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4374 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4375 ea = slide & PAGE_MASK;
4378 if (bp->b_pages[i] == bogus_page)
4381 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4382 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4383 if ((bp->b_pages[i]->valid & mask) == mask)
4385 if ((bp->b_pages[i]->valid & mask) == 0)
4386 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4388 for (; sa < ea; sa += DEV_BSIZE, j++) {
4389 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4390 pmap_zero_page_area(bp->b_pages[i],
4395 bp->b_pages[i]->valid |= mask;
4398 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4403 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4408 if (buf_mapped(bp)) {
4409 BUF_CHECK_MAPPED(bp);
4410 bzero(bp->b_data + base, size);
4412 BUF_CHECK_UNMAPPED(bp);
4413 n = PAGE_SIZE - (base & PAGE_MASK);
4414 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4418 pmap_zero_page_area(m, base & PAGE_MASK, n);
4427 * vm_hold_load_pages and vm_hold_free_pages get pages into
4428 * a buffers address space. The pages are anonymous and are
4429 * not associated with a file object.
4432 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4438 BUF_CHECK_MAPPED(bp);
4440 to = round_page(to);
4441 from = round_page(from);
4442 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4444 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4447 * note: must allocate system pages since blocking here
4448 * could interfere with paging I/O, no matter which
4451 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4452 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4457 pmap_qenter(pg, &p, 1);
4458 bp->b_pages[index] = p;
4460 bp->b_npages = index;
4463 /* Return pages associated with this buf to the vm system */
4465 vm_hold_free_pages(struct buf *bp, int newbsize)
4469 int index, newnpages;
4471 BUF_CHECK_MAPPED(bp);
4473 from = round_page((vm_offset_t)bp->b_data + newbsize);
4474 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4475 if (bp->b_npages > newnpages)
4476 pmap_qremove(from, bp->b_npages - newnpages);
4477 for (index = newnpages; index < bp->b_npages; index++) {
4478 p = bp->b_pages[index];
4479 bp->b_pages[index] = NULL;
4480 if (vm_page_sbusied(p))
4481 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4482 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4485 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
4487 bp->b_npages = newnpages;
4491 * Map an IO request into kernel virtual address space.
4493 * All requests are (re)mapped into kernel VA space.
4494 * Notice that we use b_bufsize for the size of the buffer
4495 * to be mapped. b_bcount might be modified by the driver.
4497 * Note that even if the caller determines that the address space should
4498 * be valid, a race or a smaller-file mapped into a larger space may
4499 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4500 * check the return value.
4502 * This function only works with pager buffers.
4505 vmapbuf(struct buf *bp, int mapbuf)
4510 if (bp->b_bufsize < 0)
4512 prot = VM_PROT_READ;
4513 if (bp->b_iocmd == BIO_READ)
4514 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4515 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4516 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4517 btoc(MAXPHYS))) < 0)
4519 bp->b_npages = pidx;
4520 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4521 if (mapbuf || !unmapped_buf_allowed) {
4522 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
4523 bp->b_data = bp->b_kvabase + bp->b_offset;
4525 bp->b_data = unmapped_buf;
4530 * Free the io map PTEs associated with this IO operation.
4531 * We also invalidate the TLB entries and restore the original b_addr.
4533 * This function only works with pager buffers.
4536 vunmapbuf(struct buf *bp)
4540 npages = bp->b_npages;
4542 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4543 vm_page_unhold_pages(bp->b_pages, npages);
4545 bp->b_data = unmapped_buf;
4549 bdone(struct buf *bp)
4553 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4555 bp->b_flags |= B_DONE;
4561 bwait(struct buf *bp, u_char pri, const char *wchan)
4565 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4567 while ((bp->b_flags & B_DONE) == 0)
4568 msleep(bp, mtxp, pri, wchan, 0);
4573 bufsync(struct bufobj *bo, int waitfor)
4576 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4580 bufstrategy(struct bufobj *bo, struct buf *bp)
4586 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4587 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4588 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4589 i = VOP_STRATEGY(vp, bp);
4590 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4594 bufobj_wrefl(struct bufobj *bo)
4597 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4598 ASSERT_BO_WLOCKED(bo);
4603 bufobj_wref(struct bufobj *bo)
4606 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4613 bufobj_wdrop(struct bufobj *bo)
4616 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4618 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4619 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4620 bo->bo_flag &= ~BO_WWAIT;
4621 wakeup(&bo->bo_numoutput);
4627 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4631 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4632 ASSERT_BO_WLOCKED(bo);
4634 while (bo->bo_numoutput) {
4635 bo->bo_flag |= BO_WWAIT;
4636 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4637 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4645 bpin(struct buf *bp)
4649 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4656 bunpin(struct buf *bp)
4660 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4662 if (--bp->b_pin_count == 0)
4668 bunpin_wait(struct buf *bp)
4672 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4674 while (bp->b_pin_count > 0)
4675 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4680 * Set bio_data or bio_ma for struct bio from the struct buf.
4683 bdata2bio(struct buf *bp, struct bio *bip)
4686 if (!buf_mapped(bp)) {
4687 KASSERT(unmapped_buf_allowed, ("unmapped"));
4688 bip->bio_ma = bp->b_pages;
4689 bip->bio_ma_n = bp->b_npages;
4690 bip->bio_data = unmapped_buf;
4691 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4692 bip->bio_flags |= BIO_UNMAPPED;
4693 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4694 PAGE_SIZE == bp->b_npages,
4695 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4696 (long long)bip->bio_length, bip->bio_ma_n));
4698 bip->bio_data = bp->b_data;
4703 static int buf_pager_relbuf;
4704 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
4705 &buf_pager_relbuf, 0,
4706 "Make buffer pager release buffers after reading");
4709 * The buffer pager. It uses buffer reads to validate pages.
4711 * In contrast to the generic local pager from vm/vnode_pager.c, this
4712 * pager correctly and easily handles volumes where the underlying
4713 * device block size is greater than the machine page size. The
4714 * buffer cache transparently extends the requested page run to be
4715 * aligned at the block boundary, and does the necessary bogus page
4716 * replacements in the addends to avoid obliterating already valid
4719 * The only non-trivial issue is that the exclusive busy state for
4720 * pages, which is assumed by the vm_pager_getpages() interface, is
4721 * incompatible with the VMIO buffer cache's desire to share-busy the
4722 * pages. This function performs a trivial downgrade of the pages'
4723 * state before reading buffers, and a less trivial upgrade from the
4724 * shared-busy to excl-busy state after the read.
4727 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
4728 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
4729 vbg_get_blksize_t get_blksize)
4736 vm_ooffset_t la, lb, poff, poffe;
4738 int bo_bs, br_flags, error, i, pgsin, pgsin_a, pgsin_b;
4741 object = vp->v_object;
4743 la = IDX_TO_OFF(ma[count - 1]->pindex);
4744 if (la >= object->un_pager.vnp.vnp_size)
4745 return (VM_PAGER_BAD);
4746 lpart = la + PAGE_SIZE > object->un_pager.vnp.vnp_size;
4747 bo_bs = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)));
4750 * Calculate read-ahead, behind and total pages.
4753 lb = IDX_TO_OFF(ma[0]->pindex);
4754 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
4756 if (rbehind != NULL)
4758 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
4759 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
4760 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
4765 PCPU_INC(cnt.v_vnodein);
4766 PCPU_ADD(cnt.v_vnodepgsin, pgsin);
4768 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
4769 != 0) ? GB_UNMAPPED : 0;
4770 VM_OBJECT_WLOCK(object);
4772 for (i = 0; i < count; i++)
4773 vm_page_busy_downgrade(ma[i]);
4774 VM_OBJECT_WUNLOCK(object);
4777 for (i = 0; i < count; i++) {
4781 * Pages are shared busy and the object lock is not
4782 * owned, which together allow for the pages'
4783 * invalidation. The racy test for validity avoids
4784 * useless creation of the buffer for the most typical
4785 * case when invalidation is not used in redo or for
4786 * parallel read. The shared->excl upgrade loop at
4787 * the end of the function catches the race in a
4788 * reliable way (protected by the object lock).
4790 if (m->valid == VM_PAGE_BITS_ALL)
4793 poff = IDX_TO_OFF(m->pindex);
4794 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
4795 for (; poff < poffe; poff += bsize) {
4796 lbn = get_lblkno(vp, poff);
4801 bsize = get_blksize(vp, lbn);
4802 error = bread_gb(vp, lbn, bsize, curthread->td_ucred,
4806 if (LIST_EMPTY(&bp->b_dep)) {
4808 * Invalidation clears m->valid, but
4809 * may leave B_CACHE flag if the
4810 * buffer existed at the invalidation
4811 * time. In this case, recycle the
4812 * buffer to do real read on next
4813 * bread() after redo.
4815 * Otherwise B_RELBUF is not strictly
4816 * necessary, enable to reduce buf
4819 if (buf_pager_relbuf ||
4820 m->valid != VM_PAGE_BITS_ALL)
4821 bp->b_flags |= B_RELBUF;
4823 bp->b_flags &= ~B_NOCACHE;
4829 KASSERT(1 /* racy, enable for debugging */ ||
4830 m->valid == VM_PAGE_BITS_ALL || i == count - 1,
4831 ("buf %d %p invalid", i, m));
4832 if (i == count - 1 && lpart) {
4833 VM_OBJECT_WLOCK(object);
4834 if (m->valid != 0 &&
4835 m->valid != VM_PAGE_BITS_ALL)
4836 vm_page_zero_invalid(m, TRUE);
4837 VM_OBJECT_WUNLOCK(object);
4843 VM_OBJECT_WLOCK(object);
4845 for (i = 0; i < count; i++) {
4846 vm_page_sunbusy(ma[i]);
4847 ma[i] = vm_page_grab(object, ma[i]->pindex, VM_ALLOC_NORMAL);
4850 * Since the pages were only sbusy while neither the
4851 * buffer nor the object lock was held by us, or
4852 * reallocated while vm_page_grab() slept for busy
4853 * relinguish, they could have been invalidated.
4854 * Recheck the valid bits and re-read as needed.
4856 * Note that the last page is made fully valid in the
4857 * read loop, and partial validity for the page at
4858 * index count - 1 could mean that the page was
4859 * invalidated or removed, so we must restart for
4862 if (ma[i]->valid != VM_PAGE_BITS_ALL)
4865 if (redo && error == 0)
4867 VM_OBJECT_WUNLOCK(object);
4868 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
4871 #include "opt_ddb.h"
4873 #include <ddb/ddb.h>
4875 /* DDB command to show buffer data */
4876 DB_SHOW_COMMAND(buffer, db_show_buffer)
4879 struct buf *bp = (struct buf *)addr;
4882 db_printf("usage: show buffer <addr>\n");
4886 db_printf("buf at %p\n", bp);
4887 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4888 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4889 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4891 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4892 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4894 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4895 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4896 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4897 db_printf("b_kvabase = %p, b_kvasize = %d\n",
4898 bp->b_kvabase, bp->b_kvasize);
4901 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4902 for (i = 0; i < bp->b_npages; i++) {
4905 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4906 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4907 if ((i + 1) < bp->b_npages)
4913 BUF_LOCKPRINTINFO(bp);
4916 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4921 for (i = 0; i < nbuf; i++) {
4923 if (BUF_ISLOCKED(bp)) {
4924 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4932 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4938 db_printf("usage: show vnodebufs <addr>\n");
4941 vp = (struct vnode *)addr;
4942 db_printf("Clean buffers:\n");
4943 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4944 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4947 db_printf("Dirty buffers:\n");
4948 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4949 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4954 DB_COMMAND(countfreebufs, db_coundfreebufs)
4957 int i, used = 0, nfree = 0;
4960 db_printf("usage: countfreebufs\n");
4964 for (i = 0; i < nbuf; i++) {
4966 if (bp->b_qindex == QUEUE_EMPTY)
4972 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4974 db_printf("numfreebuffers is %d\n", numfreebuffers);