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);
134 static void maxbcachebuf_adjust(void);
136 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
137 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
138 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
141 int vmiodirenable = TRUE;
142 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
143 "Use the VM system for directory writes");
144 long runningbufspace;
145 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
146 "Amount of presently outstanding async buffer io");
147 static long bufspace;
148 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
149 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
150 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
151 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
153 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
154 "Physical memory used for buffers");
156 static long bufkvaspace;
157 SYSCTL_LONG(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace, 0,
158 "Kernel virtual memory used for buffers");
159 static long maxbufspace;
160 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RW, &maxbufspace, 0,
161 "Maximum allowed value of bufspace (including metadata)");
162 static long bufmallocspace;
163 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
164 "Amount of malloced memory for buffers");
165 static long maxbufmallocspace;
166 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
167 0, "Maximum amount of malloced memory for buffers");
168 static long lobufspace;
169 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RW, &lobufspace, 0,
170 "Minimum amount of buffers we want to have");
172 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RW, &hibufspace, 0,
173 "Maximum allowed value of bufspace (excluding metadata)");
175 SYSCTL_LONG(_vfs, OID_AUTO, bufspacethresh, CTLFLAG_RW, &bufspacethresh,
176 0, "Bufspace consumed before waking the daemon to free some");
177 static int buffreekvacnt;
178 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
179 "Number of times we have freed the KVA space from some buffer");
180 static int bufdefragcnt;
181 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
182 "Number of times we have had to repeat buffer allocation to defragment");
183 static long lorunningspace;
184 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
185 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
186 "Minimum preferred space used for in-progress I/O");
187 static long hirunningspace;
188 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
189 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
190 "Maximum amount of space to use for in-progress I/O");
191 int dirtybufferflushes;
192 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
193 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
195 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
196 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
197 int altbufferflushes;
198 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
199 0, "Number of fsync flushes to limit dirty buffers");
200 static int recursiveflushes;
201 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
202 0, "Number of flushes skipped due to being recursive");
203 static int numdirtybuffers;
204 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
205 "Number of buffers that are dirty (has unwritten changes) at the moment");
206 static int lodirtybuffers;
207 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
208 "How many buffers we want to have free before bufdaemon can sleep");
209 static int hidirtybuffers;
210 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
211 "When the number of dirty buffers is considered severe");
213 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
214 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
215 static int numfreebuffers;
216 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
217 "Number of free buffers");
218 static int lofreebuffers;
219 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
220 "Target number of free buffers");
221 static int hifreebuffers;
222 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
223 "Threshold for clean buffer recycling");
224 static int getnewbufcalls;
225 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
226 "Number of calls to getnewbuf");
227 static int getnewbufrestarts;
228 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
229 "Number of times getnewbuf has had to restart a buffer acquisition");
230 static int mappingrestarts;
231 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
232 "Number of times getblk has had to restart a buffer mapping for "
234 static int numbufallocfails;
235 SYSCTL_INT(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW, &numbufallocfails, 0,
236 "Number of times buffer allocations failed");
237 static int flushbufqtarget = 100;
238 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
239 "Amount of work to do in flushbufqueues when helping bufdaemon");
240 static long notbufdflushes;
241 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 0,
242 "Number of dirty buffer flushes done by the bufdaemon helpers");
243 static long barrierwrites;
244 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
245 "Number of barrier writes");
246 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
247 &unmapped_buf_allowed, 0,
248 "Permit the use of the unmapped i/o");
249 int maxbcachebuf = MAXBCACHEBUF;
250 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0,
251 "Maximum size of a buffer cache block");
254 * This lock synchronizes access to bd_request.
256 static struct mtx_padalign bdlock;
259 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
260 * waitrunningbufspace().
262 static struct mtx_padalign rbreqlock;
265 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
267 static struct rwlock_padalign nblock;
270 * Lock that protects bdirtywait.
272 static struct mtx_padalign bdirtylock;
275 * Wakeup point for bufdaemon, as well as indicator of whether it is already
276 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
279 static int bd_request;
282 * Request/wakeup point for the bufspace daemon.
284 static int bufspace_request;
287 * Request for the buf daemon to write more buffers than is indicated by
288 * lodirtybuf. This may be necessary to push out excess dependencies or
289 * defragment the address space where a simple count of the number of dirty
290 * buffers is insufficient to characterize the demand for flushing them.
292 static int bd_speedupreq;
295 * Synchronization (sleep/wakeup) variable for active buffer space requests.
296 * Set when wait starts, cleared prior to wakeup().
297 * Used in runningbufwakeup() and waitrunningbufspace().
299 static int runningbufreq;
302 * Synchronization (sleep/wakeup) variable for buffer requests.
303 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
305 * Used in numdirtywakeup(), bufspace_wakeup(), bwillwrite(),
306 * getnewbuf(), and getblk().
308 static volatile int needsbuffer;
311 * Synchronization for bwillwrite() waiters.
313 static int bdirtywait;
316 * Definitions for the buffer free lists.
318 #define QUEUE_NONE 0 /* on no queue */
319 #define QUEUE_EMPTY 1 /* empty buffer headers */
320 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
321 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
322 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
324 /* Maximum number of clean buffer queues. */
325 #define CLEAN_QUEUES 16
327 /* Configured number of clean queues. */
328 static int clean_queues;
330 /* Maximum number of buffer queues. */
331 #define BUFFER_QUEUES (QUEUE_CLEAN + CLEAN_QUEUES)
333 /* Queues for free buffers with various properties */
334 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
336 static int bq_len[BUFFER_QUEUES];
340 * Lock for each bufqueue
342 static struct mtx_padalign bqlocks[BUFFER_QUEUES];
345 * per-cpu empty buffer cache.
350 * Single global constant for BUF_WMESG, to avoid getting multiple references.
351 * buf_wmesg is referred from macros.
353 const char *buf_wmesg = BUF_WMESG;
356 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
361 value = *(long *)arg1;
362 error = sysctl_handle_long(oidp, &value, 0, req);
363 if (error != 0 || req->newptr == NULL)
365 mtx_lock(&rbreqlock);
366 if (arg1 == &hirunningspace) {
367 if (value < lorunningspace)
370 hirunningspace = value;
372 KASSERT(arg1 == &lorunningspace,
373 ("%s: unknown arg1", __func__));
374 if (value > hirunningspace)
377 lorunningspace = value;
379 mtx_unlock(&rbreqlock);
383 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
384 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
386 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
391 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
392 return (sysctl_handle_long(oidp, arg1, arg2, req));
393 lvalue = *(long *)arg1;
394 if (lvalue > INT_MAX)
395 /* On overflow, still write out a long to trigger ENOMEM. */
396 return (sysctl_handle_long(oidp, &lvalue, 0, req));
398 return (sysctl_handle_int(oidp, &ivalue, 0, req));
407 return ((atomic_fetchadd_int(&nextq, 1) % clean_queues) + QUEUE_CLEAN);
411 bqisclean(int qindex)
414 return (qindex >= QUEUE_CLEAN && qindex < QUEUE_CLEAN + CLEAN_QUEUES);
420 * Return the appropriate queue lock based on the index.
422 static inline struct mtx *
426 return (struct mtx *)&bqlocks[qindex];
432 * Wakeup any bwillwrite() waiters.
437 mtx_lock(&bdirtylock);
442 mtx_unlock(&bdirtylock);
448 * Decrement the numdirtybuffers count by one and wakeup any
449 * threads blocked in bwillwrite().
455 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
456 (lodirtybuffers + hidirtybuffers) / 2)
463 * Increment the numdirtybuffers count by one and wakeup the buf
471 * Only do the wakeup once as we cross the boundary. The
472 * buf daemon will keep running until the condition clears.
474 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
475 (lodirtybuffers + hidirtybuffers) / 2)
482 * Called when buffer space is potentially available for recovery.
483 * getnewbuf() will block on this flag when it is unable to free
484 * sufficient buffer space. Buffer space becomes recoverable when
485 * bp's get placed back in the queues.
488 bufspace_wakeup(void)
492 * If someone is waiting for bufspace, wake them up.
494 * Since needsbuffer is set prior to doing an additional queue
495 * scan it is safe to check for the flag prior to acquiring the
496 * lock. The thread that is preparing to scan again before
497 * blocking would discover the buf we released.
501 if (atomic_cmpset_int(&needsbuffer, 1, 0) == 1)
502 wakeup(__DEVOLATILE(void *, &needsbuffer));
508 * bufspace_daemonwakeup:
510 * Wakeup the daemon responsible for freeing clean bufs.
513 bufspace_daemonwakeup(void)
516 if (bufspace_request == 0) {
517 bufspace_request = 1;
518 wakeup(&bufspace_request);
526 * Adjust the reported bufspace for a KVA managed buffer, possibly
527 * waking any waiters.
530 bufspace_adjust(struct buf *bp, int bufsize)
535 KASSERT((bp->b_flags & B_MALLOC) == 0,
536 ("bufspace_adjust: malloc buf %p", bp));
537 diff = bufsize - bp->b_bufsize;
539 atomic_subtract_long(&bufspace, -diff);
542 space = atomic_fetchadd_long(&bufspace, diff);
543 /* Wake up the daemon on the transition. */
544 if (space < bufspacethresh && space + diff >= bufspacethresh)
545 bufspace_daemonwakeup();
547 bp->b_bufsize = bufsize;
553 * Reserve bufspace before calling allocbuf(). metadata has a
554 * different space limit than data.
557 bufspace_reserve(int size, bool metadata)
568 if (space + size > limit)
570 } while (atomic_cmpset_long(&bufspace, space, space + size) == 0);
572 /* Wake up the daemon on the transition. */
573 if (space < bufspacethresh && space + size >= bufspacethresh)
574 bufspace_daemonwakeup();
582 * Release reserved bufspace after bufspace_adjust() has consumed it.
585 bufspace_release(int size)
587 atomic_subtract_long(&bufspace, size);
594 * Wait for bufspace, acting as the buf daemon if a locked vnode is
595 * supplied. needsbuffer must be set in a safe fashion prior to
596 * polling for space. The operation must be re-tried on return.
599 bufspace_wait(struct vnode *vp, int gbflags, int slpflag, int slptimeo)
602 int error, fl, norunbuf;
604 if ((gbflags & GB_NOWAIT_BD) != 0)
609 while (needsbuffer != 0) {
610 if (vp != NULL && vp->v_type != VCHR &&
611 (td->td_pflags & TDP_BUFNEED) == 0) {
614 * getblk() is called with a vnode locked, and
615 * some majority of the dirty buffers may as
616 * well belong to the vnode. Flushing the
617 * buffers there would make a progress that
618 * cannot be achieved by the buf_daemon, that
619 * cannot lock the vnode.
621 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
622 (td->td_pflags & TDP_NORUNNINGBUF);
625 * Play bufdaemon. The getnewbuf() function
626 * may be called while the thread owns lock
627 * for another dirty buffer for the same
628 * vnode, which makes it impossible to use
629 * VOP_FSYNC() there, due to the buffer lock
632 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
633 fl = buf_flush(vp, flushbufqtarget);
634 td->td_pflags &= norunbuf;
638 if (needsbuffer == 0)
641 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
642 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
653 * buffer space management daemon. Tries to maintain some marginal
654 * amount of free buffer space so that requesting processes neither
655 * block nor work to reclaim buffers.
658 bufspace_daemon(void)
661 kproc_suspend_check(bufspacedaemonproc);
664 * Free buffers from the clean queue until we meet our
667 * Theory of operation: The buffer cache is most efficient
668 * when some free buffer headers and space are always
669 * available to getnewbuf(). This daemon attempts to prevent
670 * the excessive blocking and synchronization associated
671 * with shortfall. It goes through three phases according
674 * 1) The daemon wakes up voluntarily once per-second
675 * during idle periods when the counters are below
676 * the wakeup thresholds (bufspacethresh, lofreebuffers).
678 * 2) The daemon wakes up as we cross the thresholds
679 * ahead of any potential blocking. This may bounce
680 * slightly according to the rate of consumption and
683 * 3) The daemon and consumers are starved for working
684 * clean buffers. This is the 'bufspace' sleep below
685 * which will inefficiently trade bufs with bqrelse
686 * until we return to condition 2.
688 while (bufspace > lobufspace ||
689 numfreebuffers < hifreebuffers) {
690 if (buf_recycle(false) != 0) {
691 atomic_set_int(&needsbuffer, 1);
692 if (buf_recycle(false) != 0) {
695 rw_sleep(__DEVOLATILE(void *,
696 &needsbuffer), &nblock,
697 PRIBIO|PDROP, "bufspace",
707 * Re-check our limits under the exclusive nblock.
710 if (bufspace < bufspacethresh &&
711 numfreebuffers > lofreebuffers) {
712 bufspace_request = 0;
713 rw_sleep(&bufspace_request, &nblock, PRIBIO|PDROP,
720 static struct kproc_desc bufspace_kp = {
725 SYSINIT(bufspacedaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start,
731 * Adjust the reported bufspace for a malloc managed buffer, possibly
732 * waking any waiters.
735 bufmallocadjust(struct buf *bp, int bufsize)
739 KASSERT((bp->b_flags & B_MALLOC) != 0,
740 ("bufmallocadjust: non-malloc buf %p", bp));
741 diff = bufsize - bp->b_bufsize;
743 atomic_subtract_long(&bufmallocspace, -diff);
745 atomic_add_long(&bufmallocspace, diff);
746 bp->b_bufsize = bufsize;
752 * Wake up processes that are waiting on asynchronous writes to fall
753 * below lorunningspace.
759 mtx_lock(&rbreqlock);
762 wakeup(&runningbufreq);
764 mtx_unlock(&rbreqlock);
770 * Decrement the outstanding write count according.
773 runningbufwakeup(struct buf *bp)
777 bspace = bp->b_runningbufspace;
780 space = atomic_fetchadd_long(&runningbufspace, -bspace);
781 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
783 bp->b_runningbufspace = 0;
785 * Only acquire the lock and wakeup on the transition from exceeding
786 * the threshold to falling below it.
788 if (space < lorunningspace)
790 if (space - bspace > lorunningspace)
796 * waitrunningbufspace()
798 * runningbufspace is a measure of the amount of I/O currently
799 * running. This routine is used in async-write situations to
800 * prevent creating huge backups of pending writes to a device.
801 * Only asynchronous writes are governed by this function.
803 * This does NOT turn an async write into a sync write. It waits
804 * for earlier writes to complete and generally returns before the
805 * caller's write has reached the device.
808 waitrunningbufspace(void)
811 mtx_lock(&rbreqlock);
812 while (runningbufspace > hirunningspace) {
814 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
816 mtx_unlock(&rbreqlock);
821 * vfs_buf_test_cache:
823 * Called when a buffer is extended. This function clears the B_CACHE
824 * bit if the newly extended portion of the buffer does not contain
828 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
829 vm_offset_t size, vm_page_t m)
832 VM_OBJECT_ASSERT_LOCKED(m->object);
833 if (bp->b_flags & B_CACHE) {
834 int base = (foff + off) & PAGE_MASK;
835 if (vm_page_is_valid(m, base, size) == 0)
836 bp->b_flags &= ~B_CACHE;
840 /* Wake up the buffer daemon if necessary */
846 if (bd_request == 0) {
854 * Adjust the maxbcachbuf tunable.
857 maxbcachebuf_adjust(void)
862 * maxbcachebuf must be a power of 2 >= MAXBSIZE.
865 while (i * 2 <= maxbcachebuf)
868 if (maxbcachebuf < MAXBSIZE)
869 maxbcachebuf = MAXBSIZE;
870 if (maxbcachebuf > MAXPHYS)
871 maxbcachebuf = MAXPHYS;
872 if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF)
873 printf("maxbcachebuf=%d\n", maxbcachebuf);
877 * bd_speedup - speedup the buffer cache flushing code
886 if (bd_speedupreq == 0 || bd_request == 0)
896 #define NSWBUF_MIN 16
900 #define TRANSIENT_DENOM 5
902 #define TRANSIENT_DENOM 10
906 * Calculating buffer cache scaling values and reserve space for buffer
907 * headers. This is called during low level kernel initialization and
908 * may be called more then once. We CANNOT write to the memory area
909 * being reserved at this time.
912 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
915 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
918 * physmem_est is in pages. Convert it to kilobytes (assumes
919 * PAGE_SIZE is >= 1K)
921 physmem_est = physmem_est * (PAGE_SIZE / 1024);
923 maxbcachebuf_adjust();
925 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
926 * For the first 64MB of ram nominally allocate sufficient buffers to
927 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
928 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
929 * the buffer cache we limit the eventual kva reservation to
932 * factor represents the 1/4 x ram conversion.
935 int factor = 4 * BKVASIZE / 1024;
938 if (physmem_est > 4096)
939 nbuf += min((physmem_est - 4096) / factor,
941 if (physmem_est > 65536)
942 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
943 32 * 1024 * 1024 / (factor * 5));
945 if (maxbcache && nbuf > maxbcache / BKVASIZE)
946 nbuf = maxbcache / BKVASIZE;
951 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
952 maxbuf = (LONG_MAX / 3) / BKVASIZE;
955 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
961 * Ideal allocation size for the transient bio submap is 10%
962 * of the maximal space buffer map. This roughly corresponds
963 * to the amount of the buffer mapped for typical UFS load.
965 * Clip the buffer map to reserve space for the transient
966 * BIOs, if its extent is bigger than 90% (80% on i386) of the
967 * maximum buffer map extent on the platform.
969 * The fall-back to the maxbuf in case of maxbcache unset,
970 * allows to not trim the buffer KVA for the architectures
971 * with ample KVA space.
973 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
974 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
975 buf_sz = (long)nbuf * BKVASIZE;
976 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
977 (TRANSIENT_DENOM - 1)) {
979 * There is more KVA than memory. Do not
980 * adjust buffer map size, and assign the rest
981 * of maxbuf to transient map.
983 biotmap_sz = maxbuf_sz - buf_sz;
986 * Buffer map spans all KVA we could afford on
987 * this platform. Give 10% (20% on i386) of
988 * the buffer map to the transient bio map.
990 biotmap_sz = buf_sz / TRANSIENT_DENOM;
991 buf_sz -= biotmap_sz;
993 if (biotmap_sz / INT_MAX > MAXPHYS)
994 bio_transient_maxcnt = INT_MAX;
996 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
998 * Artificially limit to 1024 simultaneous in-flight I/Os
999 * using the transient mapping.
1001 if (bio_transient_maxcnt > 1024)
1002 bio_transient_maxcnt = 1024;
1004 nbuf = buf_sz / BKVASIZE;
1008 * swbufs are used as temporary holders for I/O, such as paging I/O.
1009 * We have no less then 16 and no more then 256.
1011 nswbuf = min(nbuf / 4, 256);
1012 TUNABLE_INT_FETCH("kern.nswbuf", &nswbuf);
1013 if (nswbuf < NSWBUF_MIN)
1014 nswbuf = NSWBUF_MIN;
1017 * Reserve space for the buffer cache buffers
1020 v = (caddr_t)(swbuf + nswbuf);
1022 v = (caddr_t)(buf + nbuf);
1027 /* Initialize the buffer subsystem. Called before use of any buffers. */
1034 KASSERT(maxbcachebuf >= MAXBSIZE,
1035 ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf,
1037 mtx_init(&bqlocks[QUEUE_DIRTY], "bufq dirty lock", NULL, MTX_DEF);
1038 mtx_init(&bqlocks[QUEUE_EMPTY], "bufq empty lock", NULL, MTX_DEF);
1039 for (i = QUEUE_CLEAN; i < QUEUE_CLEAN + CLEAN_QUEUES; i++)
1040 mtx_init(&bqlocks[i], "bufq clean lock", NULL, MTX_DEF);
1041 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1042 rw_init(&nblock, "needsbuffer lock");
1043 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1044 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1046 /* next, make a null set of free lists */
1047 for (i = 0; i < BUFFER_QUEUES; i++)
1048 TAILQ_INIT(&bufqueues[i]);
1050 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
1052 /* finally, initialize each buffer header and stick on empty q */
1053 for (i = 0; i < nbuf; i++) {
1055 bzero(bp, sizeof *bp);
1056 bp->b_flags = B_INVAL;
1057 bp->b_rcred = NOCRED;
1058 bp->b_wcred = NOCRED;
1059 bp->b_qindex = QUEUE_EMPTY;
1061 bp->b_data = bp->b_kvabase = unmapped_buf;
1062 LIST_INIT(&bp->b_dep);
1064 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
1066 bq_len[QUEUE_EMPTY]++;
1071 * maxbufspace is the absolute maximum amount of buffer space we are
1072 * allowed to reserve in KVM and in real terms. The absolute maximum
1073 * is nominally used by metadata. hibufspace is the nominal maximum
1074 * used by most other requests. The differential is required to
1075 * ensure that metadata deadlocks don't occur.
1077 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1078 * this may result in KVM fragmentation which is not handled optimally
1079 * by the system. XXX This is less true with vmem. We could use
1082 maxbufspace = (long)nbuf * BKVASIZE;
1083 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10);
1084 lobufspace = (hibufspace / 20) * 19; /* 95% */
1085 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1088 * Note: The 16 MiB upper limit for hirunningspace was chosen
1089 * arbitrarily and may need further tuning. It corresponds to
1090 * 128 outstanding write IO requests (if IO size is 128 KiB),
1091 * which fits with many RAID controllers' tagged queuing limits.
1092 * The lower 1 MiB limit is the historical upper limit for
1095 hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf),
1096 16 * 1024 * 1024), 1024 * 1024);
1097 lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf);
1100 * Limit the amount of malloc memory since it is wired permanently into
1101 * the kernel space. Even though this is accounted for in the buffer
1102 * allocation, we don't want the malloced region to grow uncontrolled.
1103 * The malloc scheme improves memory utilization significantly on
1104 * average (small) directories.
1106 maxbufmallocspace = hibufspace / 20;
1109 * Reduce the chance of a deadlock occurring by limiting the number
1110 * of delayed-write dirty buffers we allow to stack up.
1112 hidirtybuffers = nbuf / 4 + 20;
1113 dirtybufthresh = hidirtybuffers * 9 / 10;
1114 numdirtybuffers = 0;
1116 * To support extreme low-memory systems, make sure hidirtybuffers
1117 * cannot eat up all available buffer space. This occurs when our
1118 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1119 * buffer space assuming BKVASIZE'd buffers.
1121 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1122 hidirtybuffers >>= 1;
1124 lodirtybuffers = hidirtybuffers / 2;
1127 * lofreebuffers should be sufficient to avoid stalling waiting on
1128 * buf headers under heavy utilization. The bufs in per-cpu caches
1129 * are counted as free but will be unavailable to threads executing
1132 * hifreebuffers is the free target for the bufspace daemon. This
1133 * should be set appropriately to limit work per-iteration.
1135 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1136 hifreebuffers = (3 * lofreebuffers) / 2;
1137 numfreebuffers = nbuf;
1139 /* Setup the kva and free list allocators. */
1140 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1141 buf_zone = uma_zcache_create("buf free cache", sizeof(struct buf),
1142 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1145 * Size the clean queue according to the amount of buffer space.
1146 * One queue per-256mb up to the max. More queues gives better
1147 * concurrency but less accurate LRU.
1149 clean_queues = MIN(howmany(maxbufspace, 256*1024*1024), CLEAN_QUEUES);
1155 vfs_buf_check_mapped(struct buf *bp)
1158 KASSERT(bp->b_kvabase != unmapped_buf,
1159 ("mapped buf: b_kvabase was not updated %p", bp));
1160 KASSERT(bp->b_data != unmapped_buf,
1161 ("mapped buf: b_data was not updated %p", bp));
1162 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1163 MAXPHYS, ("b_data + b_offset unmapped %p", bp));
1167 vfs_buf_check_unmapped(struct buf *bp)
1170 KASSERT(bp->b_data == unmapped_buf,
1171 ("unmapped buf: corrupted b_data %p", bp));
1174 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1175 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1177 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1178 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1182 isbufbusy(struct buf *bp)
1184 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1185 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1191 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1194 bufshutdown(int show_busybufs)
1196 static int first_buf_printf = 1;
1198 int iter, nbusy, pbusy;
1204 * Sync filesystems for shutdown
1206 wdog_kern_pat(WD_LASTVAL);
1207 sys_sync(curthread, NULL);
1210 * With soft updates, some buffers that are
1211 * written will be remarked as dirty until other
1212 * buffers are written.
1214 for (iter = pbusy = 0; iter < 20; iter++) {
1216 for (bp = &buf[nbuf]; --bp >= buf; )
1220 if (first_buf_printf)
1221 printf("All buffers synced.");
1224 if (first_buf_printf) {
1225 printf("Syncing disks, buffers remaining... ");
1226 first_buf_printf = 0;
1228 printf("%d ", nbusy);
1233 wdog_kern_pat(WD_LASTVAL);
1234 sys_sync(curthread, NULL);
1238 * Drop Giant and spin for a while to allow
1239 * interrupt threads to run.
1242 DELAY(50000 * iter);
1246 * Drop Giant and context switch several times to
1247 * allow interrupt threads to run.
1250 for (subiter = 0; subiter < 50 * iter; subiter++) {
1251 thread_lock(curthread);
1252 mi_switch(SW_VOL, NULL);
1253 thread_unlock(curthread);
1261 * Count only busy local buffers to prevent forcing
1262 * a fsck if we're just a client of a wedged NFS server
1265 for (bp = &buf[nbuf]; --bp >= buf; ) {
1266 if (isbufbusy(bp)) {
1268 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1269 if (bp->b_dev == NULL) {
1270 TAILQ_REMOVE(&mountlist,
1271 bp->b_vp->v_mount, mnt_list);
1276 if (show_busybufs > 0) {
1278 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1279 nbusy, bp, bp->b_vp, bp->b_flags,
1280 (intmax_t)bp->b_blkno,
1281 (intmax_t)bp->b_lblkno);
1282 BUF_LOCKPRINTINFO(bp);
1283 if (show_busybufs > 1)
1291 * Failed to sync all blocks. Indicate this and don't
1292 * unmount filesystems (thus forcing an fsck on reboot).
1294 printf("Giving up on %d buffers\n", nbusy);
1295 DELAY(5000000); /* 5 seconds */
1297 if (!first_buf_printf)
1298 printf("Final sync complete\n");
1300 * Unmount filesystems
1302 if (panicstr == NULL)
1306 DELAY(100000); /* wait for console output to finish */
1310 bpmap_qenter(struct buf *bp)
1313 BUF_CHECK_MAPPED(bp);
1316 * bp->b_data is relative to bp->b_offset, but
1317 * bp->b_offset may be offset into the first page.
1319 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1320 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1321 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1322 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1328 * Insert the buffer into the appropriate free list.
1331 binsfree(struct buf *bp, int qindex)
1333 struct mtx *olock, *nlock;
1335 if (qindex != QUEUE_EMPTY) {
1336 BUF_ASSERT_XLOCKED(bp);
1340 * Stick to the same clean queue for the lifetime of the buf to
1341 * limit locking below. Otherwise pick ont sequentially.
1343 if (qindex == QUEUE_CLEAN) {
1344 if (bqisclean(bp->b_qindex))
1345 qindex = bp->b_qindex;
1347 qindex = bqcleanq();
1351 * Handle delayed bremfree() processing.
1353 nlock = bqlock(qindex);
1354 if (bp->b_flags & B_REMFREE) {
1355 olock = bqlock(bp->b_qindex);
1358 if (olock != nlock) {
1365 if (bp->b_qindex != QUEUE_NONE)
1366 panic("binsfree: free buffer onto another queue???");
1368 bp->b_qindex = qindex;
1369 if (bp->b_flags & B_AGE)
1370 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1372 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1374 bq_len[bp->b_qindex]++;
1382 * Free a buffer to the buf zone once it no longer has valid contents.
1385 buf_free(struct buf *bp)
1388 if (bp->b_flags & B_REMFREE)
1390 if (bp->b_vflags & BV_BKGRDINPROG)
1391 panic("losing buffer 1");
1392 if (bp->b_rcred != NOCRED) {
1393 crfree(bp->b_rcred);
1394 bp->b_rcred = NOCRED;
1396 if (bp->b_wcred != NOCRED) {
1397 crfree(bp->b_wcred);
1398 bp->b_wcred = NOCRED;
1400 if (!LIST_EMPTY(&bp->b_dep))
1404 uma_zfree(buf_zone, bp);
1405 atomic_add_int(&numfreebuffers, 1);
1412 * Import bufs into the uma cache from the buf list. The system still
1413 * expects a static array of bufs and much of the synchronization
1414 * around bufs assumes type stable storage. As a result, UMA is used
1415 * only as a per-cpu cache of bufs still maintained on a global list.
1418 buf_import(void *arg, void **store, int cnt, int flags)
1423 mtx_lock(&bqlocks[QUEUE_EMPTY]);
1424 for (i = 0; i < cnt; i++) {
1425 bp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1431 mtx_unlock(&bqlocks[QUEUE_EMPTY]);
1439 * Release bufs from the uma cache back to the buffer queues.
1442 buf_release(void *arg, void **store, int cnt)
1446 for (i = 0; i < cnt; i++)
1447 binsfree(store[i], QUEUE_EMPTY);
1453 * Allocate an empty buffer header.
1460 bp = uma_zalloc(buf_zone, M_NOWAIT);
1462 bufspace_daemonwakeup();
1463 atomic_add_int(&numbufallocfails, 1);
1468 * Wake-up the bufspace daemon on transition.
1470 if (atomic_fetchadd_int(&numfreebuffers, -1) == lofreebuffers)
1471 bufspace_daemonwakeup();
1473 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1474 panic("getnewbuf_empty: Locked buf %p on free queue.", bp);
1476 KASSERT(bp->b_vp == NULL,
1477 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1478 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1479 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1480 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1481 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1482 KASSERT(bp->b_npages == 0,
1483 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1484 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1485 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1492 bp->b_blkno = bp->b_lblkno = 0;
1493 bp->b_offset = NOOFFSET;
1499 bp->b_dirtyoff = bp->b_dirtyend = 0;
1500 bp->b_bufobj = NULL;
1501 bp->b_data = bp->b_kvabase = unmapped_buf;
1502 bp->b_fsprivate1 = NULL;
1503 bp->b_fsprivate2 = NULL;
1504 bp->b_fsprivate3 = NULL;
1505 LIST_INIT(&bp->b_dep);
1513 * Free a buffer from the given bufqueue. kva controls whether the
1514 * freed buf must own some kva resources. This is used for
1518 buf_qrecycle(int qindex, bool kva)
1520 struct buf *bp, *nbp;
1523 atomic_add_int(&bufdefragcnt, 1);
1525 mtx_lock(&bqlocks[qindex]);
1526 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1529 * Run scan, possibly freeing data and/or kva mappings on the fly
1532 while ((bp = nbp) != NULL) {
1534 * Calculate next bp (we can only use it if we do not
1535 * release the bqlock).
1537 nbp = TAILQ_NEXT(bp, b_freelist);
1540 * If we are defragging then we need a buffer with
1541 * some kva to reclaim.
1543 if (kva && bp->b_kvasize == 0)
1546 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1550 * Skip buffers with background writes in progress.
1552 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1557 KASSERT(bp->b_qindex == qindex,
1558 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1560 * NOTE: nbp is now entirely invalid. We can only restart
1561 * the scan from this point on.
1564 mtx_unlock(&bqlocks[qindex]);
1567 * Requeue the background write buffer with error and
1570 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1572 mtx_lock(&bqlocks[qindex]);
1573 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1576 bp->b_flags |= B_INVAL;
1580 mtx_unlock(&bqlocks[qindex]);
1588 * Iterate through all clean queues until we find a buf to recycle or
1589 * exhaust the search.
1592 buf_recycle(bool kva)
1594 int qindex, first_qindex;
1596 qindex = first_qindex = bqcleanq();
1598 if (buf_qrecycle(qindex, kva) == 0)
1600 if (++qindex == QUEUE_CLEAN + clean_queues)
1601 qindex = QUEUE_CLEAN;
1602 } while (qindex != first_qindex);
1610 * Scan the clean queues looking for a buffer to recycle. needsbuffer
1611 * is set on failure so that the caller may optionally bufspace_wait()
1612 * in a race-free fashion.
1615 buf_scan(bool defrag)
1620 * To avoid heavy synchronization and wakeup races we set
1621 * needsbuffer and re-poll before failing. This ensures that
1622 * no frees can be missed between an unsuccessful poll and
1623 * going to sleep in a synchronized fashion.
1625 if ((error = buf_recycle(defrag)) != 0) {
1626 atomic_set_int(&needsbuffer, 1);
1627 bufspace_daemonwakeup();
1628 error = buf_recycle(defrag);
1631 atomic_add_int(&getnewbufrestarts, 1);
1638 * Mark the buffer for removal from the appropriate free list.
1642 bremfree(struct buf *bp)
1645 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1646 KASSERT((bp->b_flags & B_REMFREE) == 0,
1647 ("bremfree: buffer %p already marked for delayed removal.", bp));
1648 KASSERT(bp->b_qindex != QUEUE_NONE,
1649 ("bremfree: buffer %p not on a queue.", bp));
1650 BUF_ASSERT_XLOCKED(bp);
1652 bp->b_flags |= B_REMFREE;
1658 * Force an immediate removal from a free list. Used only in nfs when
1659 * it abuses the b_freelist pointer.
1662 bremfreef(struct buf *bp)
1666 qlock = bqlock(bp->b_qindex);
1675 * Removes a buffer from the free list, must be called with the
1676 * correct qlock held.
1679 bremfreel(struct buf *bp)
1682 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1683 bp, bp->b_vp, bp->b_flags);
1684 KASSERT(bp->b_qindex != QUEUE_NONE,
1685 ("bremfreel: buffer %p not on a queue.", bp));
1686 if (bp->b_qindex != QUEUE_EMPTY) {
1687 BUF_ASSERT_XLOCKED(bp);
1689 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1691 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1693 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1695 bq_len[bp->b_qindex]--;
1697 bp->b_qindex = QUEUE_NONE;
1698 bp->b_flags &= ~B_REMFREE;
1704 * Free the kva allocation for a buffer.
1708 bufkva_free(struct buf *bp)
1712 if (bp->b_kvasize == 0) {
1713 KASSERT(bp->b_kvabase == unmapped_buf &&
1714 bp->b_data == unmapped_buf,
1715 ("Leaked KVA space on %p", bp));
1716 } else if (buf_mapped(bp))
1717 BUF_CHECK_MAPPED(bp);
1719 BUF_CHECK_UNMAPPED(bp);
1721 if (bp->b_kvasize == 0)
1724 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
1725 atomic_subtract_long(&bufkvaspace, bp->b_kvasize);
1726 atomic_add_int(&buffreekvacnt, 1);
1727 bp->b_data = bp->b_kvabase = unmapped_buf;
1734 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
1737 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
1742 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
1743 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
1748 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
1751 * Buffer map is too fragmented. Request the caller
1752 * to defragment the map.
1756 bp->b_kvabase = (caddr_t)addr;
1757 bp->b_kvasize = maxsize;
1758 atomic_add_long(&bufkvaspace, bp->b_kvasize);
1759 if ((gbflags & GB_UNMAPPED) != 0) {
1760 bp->b_data = unmapped_buf;
1761 BUF_CHECK_UNMAPPED(bp);
1763 bp->b_data = bp->b_kvabase;
1764 BUF_CHECK_MAPPED(bp);
1772 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
1773 * callback that fires to avoid returning failure.
1776 bufkva_reclaim(vmem_t *vmem, int flags)
1780 for (i = 0; i < 5; i++)
1781 if (buf_scan(true) != 0)
1788 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1789 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1790 * the buffer is valid and we do not have to do anything.
1793 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1794 int cnt, struct ucred * cred)
1799 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1800 if (inmem(vp, *rablkno))
1802 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1804 if ((rabp->b_flags & B_CACHE) == 0) {
1805 if (!TD_IS_IDLETHREAD(curthread)) {
1809 racct_add_buf(curproc, rabp, 0);
1810 PROC_UNLOCK(curproc);
1813 curthread->td_ru.ru_inblock++;
1815 rabp->b_flags |= B_ASYNC;
1816 rabp->b_flags &= ~B_INVAL;
1817 rabp->b_ioflags &= ~BIO_ERROR;
1818 rabp->b_iocmd = BIO_READ;
1819 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1820 rabp->b_rcred = crhold(cred);
1821 vfs_busy_pages(rabp, 0);
1823 rabp->b_iooffset = dbtob(rabp->b_blkno);
1832 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1834 * Get a buffer with the specified data. Look in the cache first. We
1835 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1836 * is set, the buffer is valid and we do not have to do anything, see
1837 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1839 * Always return a NULL buffer pointer (in bpp) when returning an error.
1842 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1843 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1846 int rv = 0, readwait = 0;
1848 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1850 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1852 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1856 /* if not found in cache, do some I/O */
1857 if ((bp->b_flags & B_CACHE) == 0) {
1858 if (!TD_IS_IDLETHREAD(curthread)) {
1862 racct_add_buf(curproc, bp, 0);
1863 PROC_UNLOCK(curproc);
1866 curthread->td_ru.ru_inblock++;
1868 bp->b_iocmd = BIO_READ;
1869 bp->b_flags &= ~B_INVAL;
1870 bp->b_ioflags &= ~BIO_ERROR;
1871 if (bp->b_rcred == NOCRED && cred != NOCRED)
1872 bp->b_rcred = crhold(cred);
1873 vfs_busy_pages(bp, 0);
1874 bp->b_iooffset = dbtob(bp->b_blkno);
1879 breada(vp, rablkno, rabsize, cnt, cred);
1892 * Write, release buffer on completion. (Done by iodone
1893 * if async). Do not bother writing anything if the buffer
1896 * Note that we set B_CACHE here, indicating that buffer is
1897 * fully valid and thus cacheable. This is true even of NFS
1898 * now so we set it generally. This could be set either here
1899 * or in biodone() since the I/O is synchronous. We put it
1903 bufwrite(struct buf *bp)
1910 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1911 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
1912 bp->b_flags |= B_INVAL | B_RELBUF;
1913 bp->b_flags &= ~B_CACHE;
1917 if (bp->b_flags & B_INVAL) {
1922 if (bp->b_flags & B_BARRIER)
1925 oldflags = bp->b_flags;
1927 BUF_ASSERT_HELD(bp);
1929 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1930 ("FFS background buffer should not get here %p", bp));
1934 vp_md = vp->v_vflag & VV_MD;
1939 * Mark the buffer clean. Increment the bufobj write count
1940 * before bundirty() call, to prevent other thread from seeing
1941 * empty dirty list and zero counter for writes in progress,
1942 * falsely indicating that the bufobj is clean.
1944 bufobj_wref(bp->b_bufobj);
1947 bp->b_flags &= ~B_DONE;
1948 bp->b_ioflags &= ~BIO_ERROR;
1949 bp->b_flags |= B_CACHE;
1950 bp->b_iocmd = BIO_WRITE;
1952 vfs_busy_pages(bp, 1);
1955 * Normal bwrites pipeline writes
1957 bp->b_runningbufspace = bp->b_bufsize;
1958 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1960 if (!TD_IS_IDLETHREAD(curthread)) {
1964 racct_add_buf(curproc, bp, 1);
1965 PROC_UNLOCK(curproc);
1968 curthread->td_ru.ru_oublock++;
1970 if (oldflags & B_ASYNC)
1972 bp->b_iooffset = dbtob(bp->b_blkno);
1973 buf_track(bp, __func__);
1976 if ((oldflags & B_ASYNC) == 0) {
1977 int rtval = bufwait(bp);
1980 } else if (space > hirunningspace) {
1982 * don't allow the async write to saturate the I/O
1983 * system. We will not deadlock here because
1984 * we are blocking waiting for I/O that is already in-progress
1985 * to complete. We do not block here if it is the update
1986 * or syncer daemon trying to clean up as that can lead
1989 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1990 waitrunningbufspace();
1997 bufbdflush(struct bufobj *bo, struct buf *bp)
2001 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
2002 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
2004 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
2007 * Try to find a buffer to flush.
2009 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2010 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2012 LK_EXCLUSIVE | LK_NOWAIT, NULL))
2015 panic("bdwrite: found ourselves");
2017 /* Don't countdeps with the bo lock held. */
2018 if (buf_countdeps(nbp, 0)) {
2023 if (nbp->b_flags & B_CLUSTEROK) {
2024 vfs_bio_awrite(nbp);
2029 dirtybufferflushes++;
2038 * Delayed write. (Buffer is marked dirty). Do not bother writing
2039 * anything if the buffer is marked invalid.
2041 * Note that since the buffer must be completely valid, we can safely
2042 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2043 * biodone() in order to prevent getblk from writing the buffer
2044 * out synchronously.
2047 bdwrite(struct buf *bp)
2049 struct thread *td = curthread;
2053 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2054 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2055 KASSERT((bp->b_flags & B_BARRIER) == 0,
2056 ("Barrier request in delayed write %p", bp));
2057 BUF_ASSERT_HELD(bp);
2059 if (bp->b_flags & B_INVAL) {
2065 * If we have too many dirty buffers, don't create any more.
2066 * If we are wildly over our limit, then force a complete
2067 * cleanup. Otherwise, just keep the situation from getting
2068 * out of control. Note that we have to avoid a recursive
2069 * disaster and not try to clean up after our own cleanup!
2073 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2074 td->td_pflags |= TDP_INBDFLUSH;
2076 td->td_pflags &= ~TDP_INBDFLUSH;
2082 * Set B_CACHE, indicating that the buffer is fully valid. This is
2083 * true even of NFS now.
2085 bp->b_flags |= B_CACHE;
2088 * This bmap keeps the system from needing to do the bmap later,
2089 * perhaps when the system is attempting to do a sync. Since it
2090 * is likely that the indirect block -- or whatever other datastructure
2091 * that the filesystem needs is still in memory now, it is a good
2092 * thing to do this. Note also, that if the pageout daemon is
2093 * requesting a sync -- there might not be enough memory to do
2094 * the bmap then... So, this is important to do.
2096 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2097 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2100 buf_track(bp, __func__);
2103 * Set the *dirty* buffer range based upon the VM system dirty
2106 * Mark the buffer pages as clean. We need to do this here to
2107 * satisfy the vnode_pager and the pageout daemon, so that it
2108 * thinks that the pages have been "cleaned". Note that since
2109 * the pages are in a delayed write buffer -- the VFS layer
2110 * "will" see that the pages get written out on the next sync,
2111 * or perhaps the cluster will be completed.
2113 vfs_clean_pages_dirty_buf(bp);
2117 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2118 * due to the softdep code.
2125 * Turn buffer into delayed write request. We must clear BIO_READ and
2126 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2127 * itself to properly update it in the dirty/clean lists. We mark it
2128 * B_DONE to ensure that any asynchronization of the buffer properly
2129 * clears B_DONE ( else a panic will occur later ).
2131 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2132 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2133 * should only be called if the buffer is known-good.
2135 * Since the buffer is not on a queue, we do not update the numfreebuffers
2138 * The buffer must be on QUEUE_NONE.
2141 bdirty(struct buf *bp)
2144 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2145 bp, bp->b_vp, bp->b_flags);
2146 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2147 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2148 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2149 BUF_ASSERT_HELD(bp);
2150 bp->b_flags &= ~(B_RELBUF);
2151 bp->b_iocmd = BIO_WRITE;
2153 if ((bp->b_flags & B_DELWRI) == 0) {
2154 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2163 * Clear B_DELWRI for buffer.
2165 * Since the buffer is not on a queue, we do not update the numfreebuffers
2168 * The buffer must be on QUEUE_NONE.
2172 bundirty(struct buf *bp)
2175 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2176 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2177 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2178 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2179 BUF_ASSERT_HELD(bp);
2181 if (bp->b_flags & B_DELWRI) {
2182 bp->b_flags &= ~B_DELWRI;
2187 * Since it is now being written, we can clear its deferred write flag.
2189 bp->b_flags &= ~B_DEFERRED;
2195 * Asynchronous write. Start output on a buffer, but do not wait for
2196 * it to complete. The buffer is released when the output completes.
2198 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2199 * B_INVAL buffers. Not us.
2202 bawrite(struct buf *bp)
2205 bp->b_flags |= B_ASYNC;
2212 * Asynchronous barrier write. Start output on a buffer, but do not
2213 * wait for it to complete. Place a write barrier after this write so
2214 * that 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 babarrierwrite(struct buf *bp)
2222 bp->b_flags |= B_ASYNC | B_BARRIER;
2229 * Synchronous barrier write. Start output on a buffer and wait for
2230 * it to complete. Place a write barrier after this write so that
2231 * this buffer and all buffers written before it are committed to
2232 * the disk before any buffers written after this write are committed
2233 * to the disk. The buffer is released when the output completes.
2236 bbarrierwrite(struct buf *bp)
2239 bp->b_flags |= B_BARRIER;
2240 return (bwrite(bp));
2246 * Called prior to the locking of any vnodes when we are expecting to
2247 * write. We do not want to starve the buffer cache with too many
2248 * dirty buffers so we block here. By blocking prior to the locking
2249 * of any vnodes we attempt to avoid the situation where a locked vnode
2250 * prevents the various system daemons from flushing related buffers.
2256 if (numdirtybuffers >= hidirtybuffers) {
2257 mtx_lock(&bdirtylock);
2258 while (numdirtybuffers >= hidirtybuffers) {
2260 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2263 mtx_unlock(&bdirtylock);
2268 * Return true if we have too many dirty buffers.
2271 buf_dirty_count_severe(void)
2274 return(numdirtybuffers >= hidirtybuffers);
2280 * Release a busy buffer and, if requested, free its resources. The
2281 * buffer will be stashed in the appropriate bufqueue[] allowing it
2282 * to be accessed later as a cache entity or reused for other purposes.
2285 brelse(struct buf *bp)
2290 * Many functions erroneously call brelse with a NULL bp under rare
2291 * error conditions. Simply return when called with a NULL bp.
2295 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2296 bp, bp->b_vp, bp->b_flags);
2297 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2298 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2299 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2300 ("brelse: non-VMIO buffer marked NOREUSE"));
2302 if (BUF_LOCKRECURSED(bp)) {
2304 * Do not process, in particular, do not handle the
2305 * B_INVAL/B_RELBUF and do not release to free list.
2311 if (bp->b_flags & B_MANAGED) {
2316 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2317 BO_LOCK(bp->b_bufobj);
2318 bp->b_vflags &= ~BV_BKGRDERR;
2319 BO_UNLOCK(bp->b_bufobj);
2322 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2323 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2324 !(bp->b_flags & B_INVAL)) {
2326 * Failed write, redirty. All errors except ENXIO (which
2327 * means the device is gone) are expected to be potentially
2328 * transient - underlying media might work if tried again
2329 * after EIO, and memory might be available after an ENOMEM.
2331 * Do this also for buffers that failed with ENXIO, but have
2332 * non-empty dependencies - the soft updates code might need
2333 * to access the buffer to untangle them.
2335 * Must clear BIO_ERROR to prevent pages from being scrapped.
2337 bp->b_ioflags &= ~BIO_ERROR;
2339 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2340 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2342 * Either a failed read I/O, or we were asked to free or not
2343 * cache the buffer, or we failed to write to a device that's
2344 * no longer present.
2346 bp->b_flags |= B_INVAL;
2347 if (!LIST_EMPTY(&bp->b_dep))
2349 if (bp->b_flags & B_DELWRI)
2351 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2352 if ((bp->b_flags & B_VMIO) == 0) {
2360 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2361 * is called with B_DELWRI set, the underlying pages may wind up
2362 * getting freed causing a previous write (bdwrite()) to get 'lost'
2363 * because pages associated with a B_DELWRI bp are marked clean.
2365 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2366 * if B_DELWRI is set.
2368 if (bp->b_flags & B_DELWRI)
2369 bp->b_flags &= ~B_RELBUF;
2372 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2373 * constituted, not even NFS buffers now. Two flags effect this. If
2374 * B_INVAL, the struct buf is invalidated but the VM object is kept
2375 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2377 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2378 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2379 * buffer is also B_INVAL because it hits the re-dirtying code above.
2381 * Normally we can do this whether a buffer is B_DELWRI or not. If
2382 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2383 * the commit state and we cannot afford to lose the buffer. If the
2384 * buffer has a background write in progress, we need to keep it
2385 * around to prevent it from being reconstituted and starting a second
2388 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2389 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2390 !(bp->b_vp->v_mount != NULL &&
2391 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2392 !vn_isdisk(bp->b_vp, NULL) && (bp->b_flags & B_DELWRI))) {
2393 vfs_vmio_invalidate(bp);
2397 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2398 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2400 bp->b_flags &= ~B_NOREUSE;
2401 if (bp->b_vp != NULL)
2406 * If the buffer has junk contents signal it and eventually
2407 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2410 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2411 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2412 bp->b_flags |= B_INVAL;
2413 if (bp->b_flags & B_INVAL) {
2414 if (bp->b_flags & B_DELWRI)
2420 buf_track(bp, __func__);
2422 /* buffers with no memory */
2423 if (bp->b_bufsize == 0) {
2427 /* buffers with junk contents */
2428 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2429 (bp->b_ioflags & BIO_ERROR)) {
2430 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2431 if (bp->b_vflags & BV_BKGRDINPROG)
2432 panic("losing buffer 2");
2433 qindex = QUEUE_CLEAN;
2434 bp->b_flags |= B_AGE;
2435 /* remaining buffers */
2436 } else if (bp->b_flags & B_DELWRI)
2437 qindex = QUEUE_DIRTY;
2439 qindex = QUEUE_CLEAN;
2441 binsfree(bp, qindex);
2443 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
2444 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2445 panic("brelse: not dirty");
2448 if (qindex == QUEUE_CLEAN)
2453 * Release a buffer back to the appropriate queue but do not try to free
2454 * it. The buffer is expected to be used again soon.
2456 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2457 * biodone() to requeue an async I/O on completion. It is also used when
2458 * known good buffers need to be requeued but we think we may need the data
2461 * XXX we should be able to leave the B_RELBUF hint set on completion.
2464 bqrelse(struct buf *bp)
2468 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2469 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2470 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2472 qindex = QUEUE_NONE;
2473 if (BUF_LOCKRECURSED(bp)) {
2474 /* do not release to free list */
2478 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2480 if (bp->b_flags & B_MANAGED) {
2481 if (bp->b_flags & B_REMFREE)
2486 /* buffers with stale but valid contents */
2487 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2488 BV_BKGRDERR)) == BV_BKGRDERR) {
2489 BO_LOCK(bp->b_bufobj);
2490 bp->b_vflags &= ~BV_BKGRDERR;
2491 BO_UNLOCK(bp->b_bufobj);
2492 qindex = QUEUE_DIRTY;
2494 if ((bp->b_flags & B_DELWRI) == 0 &&
2495 (bp->b_xflags & BX_VNDIRTY))
2496 panic("bqrelse: not dirty");
2497 if ((bp->b_flags & B_NOREUSE) != 0) {
2501 qindex = QUEUE_CLEAN;
2503 binsfree(bp, qindex);
2506 buf_track(bp, __func__);
2509 if (qindex == QUEUE_CLEAN)
2514 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2515 * restore bogus pages.
2518 vfs_vmio_iodone(struct buf *bp)
2524 int i, iosize, resid;
2527 obj = bp->b_bufobj->bo_object;
2528 KASSERT(obj->paging_in_progress >= bp->b_npages,
2529 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2530 obj->paging_in_progress, bp->b_npages));
2533 KASSERT(vp->v_holdcnt > 0,
2534 ("vfs_vmio_iodone: vnode %p has zero hold count", vp));
2535 KASSERT(vp->v_object != NULL,
2536 ("vfs_vmio_iodone: vnode %p has no vm_object", vp));
2538 foff = bp->b_offset;
2539 KASSERT(bp->b_offset != NOOFFSET,
2540 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2543 iosize = bp->b_bcount - bp->b_resid;
2544 VM_OBJECT_WLOCK(obj);
2545 for (i = 0; i < bp->b_npages; i++) {
2546 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2551 * cleanup bogus pages, restoring the originals
2554 if (m == bogus_page) {
2556 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2558 panic("biodone: page disappeared!");
2560 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2562 * In the write case, the valid and clean bits are
2563 * already changed correctly ( see bdwrite() ), so we
2564 * only need to do this here in the read case.
2566 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2567 resid)) == 0, ("vfs_vmio_iodone: page %p "
2568 "has unexpected dirty bits", m));
2569 vfs_page_set_valid(bp, foff, m);
2571 KASSERT(OFF_TO_IDX(foff) == m->pindex,
2572 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
2573 (intmax_t)foff, (uintmax_t)m->pindex));
2576 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2579 vm_object_pip_wakeupn(obj, bp->b_npages);
2580 VM_OBJECT_WUNLOCK(obj);
2581 if (bogus && buf_mapped(bp)) {
2582 BUF_CHECK_MAPPED(bp);
2583 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2584 bp->b_pages, bp->b_npages);
2589 * Unwire a page held by a buf and place it on the appropriate vm queue.
2592 vfs_vmio_unwire(struct buf *bp, vm_page_t m)
2597 if (vm_page_unwire(m, PQ_NONE)) {
2599 * Determine if the page should be freed before adding
2600 * it to the inactive queue.
2602 if (m->valid == 0) {
2603 freed = !vm_page_busied(m);
2606 } else if ((bp->b_flags & B_DIRECT) != 0)
2607 freed = vm_page_try_to_free(m);
2612 * If the page is unlikely to be reused, let the
2613 * VM know. Otherwise, maintain LRU page
2614 * ordering and put the page at the tail of the
2617 if ((bp->b_flags & B_NOREUSE) != 0)
2618 vm_page_deactivate_noreuse(m);
2620 vm_page_deactivate(m);
2627 * Perform page invalidation when a buffer is released. The fully invalid
2628 * pages will be reclaimed later in vfs_vmio_truncate().
2631 vfs_vmio_invalidate(struct buf *bp)
2635 int i, resid, poffset, presid;
2637 if (buf_mapped(bp)) {
2638 BUF_CHECK_MAPPED(bp);
2639 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
2641 BUF_CHECK_UNMAPPED(bp);
2643 * Get the base offset and length of the buffer. Note that
2644 * in the VMIO case if the buffer block size is not
2645 * page-aligned then b_data pointer may not be page-aligned.
2646 * But our b_pages[] array *IS* page aligned.
2648 * block sizes less then DEV_BSIZE (usually 512) are not
2649 * supported due to the page granularity bits (m->valid,
2650 * m->dirty, etc...).
2652 * See man buf(9) for more information
2654 obj = bp->b_bufobj->bo_object;
2655 resid = bp->b_bufsize;
2656 poffset = bp->b_offset & PAGE_MASK;
2657 VM_OBJECT_WLOCK(obj);
2658 for (i = 0; i < bp->b_npages; i++) {
2660 if (m == bogus_page)
2661 panic("vfs_vmio_invalidate: Unexpected bogus page.");
2662 bp->b_pages[i] = NULL;
2664 presid = resid > (PAGE_SIZE - poffset) ?
2665 (PAGE_SIZE - poffset) : resid;
2666 KASSERT(presid >= 0, ("brelse: extra page"));
2667 while (vm_page_xbusied(m)) {
2669 VM_OBJECT_WUNLOCK(obj);
2670 vm_page_busy_sleep(m, "mbncsh", true);
2671 VM_OBJECT_WLOCK(obj);
2673 if (pmap_page_wired_mappings(m) == 0)
2674 vm_page_set_invalid(m, poffset, presid);
2675 vfs_vmio_unwire(bp, m);
2679 VM_OBJECT_WUNLOCK(obj);
2684 * Page-granular truncation of an existing VMIO buffer.
2687 vfs_vmio_truncate(struct buf *bp, int desiredpages)
2693 if (bp->b_npages == desiredpages)
2696 if (buf_mapped(bp)) {
2697 BUF_CHECK_MAPPED(bp);
2698 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
2699 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
2701 BUF_CHECK_UNMAPPED(bp);
2702 obj = bp->b_bufobj->bo_object;
2704 VM_OBJECT_WLOCK(obj);
2705 for (i = desiredpages; i < bp->b_npages; i++) {
2707 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
2708 bp->b_pages[i] = NULL;
2709 vfs_vmio_unwire(bp, m);
2712 VM_OBJECT_WUNLOCK(obj);
2713 bp->b_npages = desiredpages;
2717 * Byte granular extension of VMIO buffers.
2720 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
2723 * We are growing the buffer, possibly in a
2724 * byte-granular fashion.
2732 * Step 1, bring in the VM pages from the object, allocating
2733 * them if necessary. We must clear B_CACHE if these pages
2734 * are not valid for the range covered by the buffer.
2736 obj = bp->b_bufobj->bo_object;
2737 VM_OBJECT_WLOCK(obj);
2738 if (bp->b_npages < desiredpages) {
2740 * We must allocate system pages since blocking
2741 * here could interfere with paging I/O, no
2742 * matter which process we are.
2744 * Only exclusive busy can be tested here.
2745 * Blocking on shared busy might lead to
2746 * deadlocks once allocbuf() is called after
2747 * pages are vfs_busy_pages().
2749 (void)vm_page_grab_pages(obj,
2750 OFF_TO_IDX(bp->b_offset) + bp->b_npages,
2751 VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
2752 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
2753 &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
2754 bp->b_npages = desiredpages;
2758 * Step 2. We've loaded the pages into the buffer,
2759 * we have to figure out if we can still have B_CACHE
2760 * set. Note that B_CACHE is set according to the
2761 * byte-granular range ( bcount and size ), not the
2762 * aligned range ( newbsize ).
2764 * The VM test is against m->valid, which is DEV_BSIZE
2765 * aligned. Needless to say, the validity of the data
2766 * needs to also be DEV_BSIZE aligned. Note that this
2767 * fails with NFS if the server or some other client
2768 * extends the file's EOF. If our buffer is resized,
2769 * B_CACHE may remain set! XXX
2771 toff = bp->b_bcount;
2772 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2773 while ((bp->b_flags & B_CACHE) && toff < size) {
2776 if (tinc > (size - toff))
2778 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
2779 m = bp->b_pages[pi];
2780 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
2784 VM_OBJECT_WUNLOCK(obj);
2787 * Step 3, fixup the KVA pmap.
2792 BUF_CHECK_UNMAPPED(bp);
2796 * Check to see if a block at a particular lbn is available for a clustered
2800 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
2807 /* If the buf isn't in core skip it */
2808 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
2811 /* If the buf is busy we don't want to wait for it */
2812 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2815 /* Only cluster with valid clusterable delayed write buffers */
2816 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
2817 (B_DELWRI | B_CLUSTEROK))
2820 if (bpa->b_bufsize != size)
2824 * Check to see if it is in the expected place on disk and that the
2825 * block has been mapped.
2827 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
2837 * Implement clustered async writes for clearing out B_DELWRI buffers.
2838 * This is much better then the old way of writing only one buffer at
2839 * a time. Note that we may not be presented with the buffers in the
2840 * correct order, so we search for the cluster in both directions.
2843 vfs_bio_awrite(struct buf *bp)
2848 daddr_t lblkno = bp->b_lblkno;
2849 struct vnode *vp = bp->b_vp;
2857 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
2859 * right now we support clustered writing only to regular files. If
2860 * we find a clusterable block we could be in the middle of a cluster
2861 * rather then at the beginning.
2863 if ((vp->v_type == VREG) &&
2864 (vp->v_mount != 0) && /* Only on nodes that have the size info */
2865 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2867 size = vp->v_mount->mnt_stat.f_iosize;
2868 maxcl = MAXPHYS / size;
2871 for (i = 1; i < maxcl; i++)
2872 if (vfs_bio_clcheck(vp, size, lblkno + i,
2873 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2876 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2877 if (vfs_bio_clcheck(vp, size, lblkno - j,
2878 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2884 * this is a possible cluster write
2888 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2894 bp->b_flags |= B_ASYNC;
2896 * default (old) behavior, writing out only one block
2898 * XXX returns b_bufsize instead of b_bcount for nwritten?
2900 nwritten = bp->b_bufsize;
2909 * Allocate KVA for an empty buf header according to gbflags.
2912 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
2915 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
2917 * In order to keep fragmentation sane we only allocate kva
2918 * in BKVASIZE chunks. XXX with vmem we can do page size.
2920 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2922 if (maxsize != bp->b_kvasize &&
2923 bufkva_alloc(bp, maxsize, gbflags))
2932 * Find and initialize a new buffer header, freeing up existing buffers
2933 * in the bufqueues as necessary. The new buffer is returned locked.
2936 * We have insufficient buffer headers
2937 * We have insufficient buffer space
2938 * buffer_arena is too fragmented ( space reservation fails )
2939 * If we have to flush dirty buffers ( but we try to avoid this )
2941 * The caller is responsible for releasing the reserved bufspace after
2942 * allocbuf() is called.
2945 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
2948 bool metadata, reserved;
2951 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2952 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2953 if (!unmapped_buf_allowed)
2954 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2956 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2961 atomic_add_int(&getnewbufcalls, 1);
2964 if (reserved == false &&
2965 bufspace_reserve(maxsize, metadata) != 0)
2968 if ((bp = buf_alloc()) == NULL)
2970 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
2973 } while(buf_scan(false) == 0);
2976 atomic_subtract_long(&bufspace, maxsize);
2978 bp->b_flags |= B_INVAL;
2981 bufspace_wait(vp, gbflags, slpflag, slptimeo);
2989 * buffer flushing daemon. Buffers are normally flushed by the
2990 * update daemon but if it cannot keep up this process starts to
2991 * take the load in an attempt to prevent getnewbuf() from blocking.
2993 static struct kproc_desc buf_kp = {
2998 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3001 buf_flush(struct vnode *vp, int target)
3005 flushed = flushbufqueues(vp, target, 0);
3008 * Could not find any buffers without rollback
3009 * dependencies, so just write the first one
3010 * in the hopes of eventually making progress.
3012 if (vp != NULL && target > 2)
3014 flushbufqueues(vp, target, 1);
3025 * This process needs to be suspended prior to shutdown sync.
3027 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
3031 * This process is allowed to take the buffer cache to the limit
3033 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3037 mtx_unlock(&bdlock);
3039 kproc_suspend_check(bufdaemonproc);
3040 lodirty = lodirtybuffers;
3041 if (bd_speedupreq) {
3042 lodirty = numdirtybuffers / 2;
3046 * Do the flush. Limit the amount of in-transit I/O we
3047 * allow to build up, otherwise we would completely saturate
3050 while (numdirtybuffers > lodirty) {
3051 if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
3053 kern_yield(PRI_USER);
3057 * Only clear bd_request if we have reached our low water
3058 * mark. The buf_daemon normally waits 1 second and
3059 * then incrementally flushes any dirty buffers that have
3060 * built up, within reason.
3062 * If we were unable to hit our low water mark and couldn't
3063 * find any flushable buffers, we sleep for a short period
3064 * to avoid endless loops on unlockable buffers.
3067 if (numdirtybuffers <= lodirtybuffers) {
3069 * We reached our low water mark, reset the
3070 * request and sleep until we are needed again.
3071 * The sleep is just so the suspend code works.
3075 * Do an extra wakeup in case dirty threshold
3076 * changed via sysctl and the explicit transition
3077 * out of shortfall was missed.
3080 if (runningbufspace <= lorunningspace)
3082 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3085 * We couldn't find any flushable dirty buffers but
3086 * still have too many dirty buffers, we
3087 * have to sleep and try again. (rare)
3089 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3097 * Try to flush a buffer in the dirty queue. We must be careful to
3098 * free up B_INVAL buffers instead of write them, which NFS is
3099 * particularly sensitive to.
3101 static int flushwithdeps = 0;
3102 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
3103 0, "Number of buffers flushed with dependecies that require rollbacks");
3106 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
3108 struct buf *sentinel;
3119 queue = QUEUE_DIRTY;
3121 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3122 sentinel->b_qindex = QUEUE_SENTINEL;
3123 mtx_lock(&bqlocks[queue]);
3124 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
3125 mtx_unlock(&bqlocks[queue]);
3126 while (flushed != target) {
3128 mtx_lock(&bqlocks[queue]);
3129 bp = TAILQ_NEXT(sentinel, b_freelist);
3131 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3132 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
3135 mtx_unlock(&bqlocks[queue]);
3139 * Skip sentinels inserted by other invocations of the
3140 * flushbufqueues(), taking care to not reorder them.
3142 * Only flush the buffers that belong to the
3143 * vnode locked by the curthread.
3145 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3147 mtx_unlock(&bqlocks[queue]);
3150 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3151 mtx_unlock(&bqlocks[queue]);
3156 * BKGRDINPROG can only be set with the buf and bufobj
3157 * locks both held. We tolerate a race to clear it here.
3159 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3160 (bp->b_flags & B_DELWRI) == 0) {
3164 if (bp->b_flags & B_INVAL) {
3171 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3172 if (flushdeps == 0) {
3180 * We must hold the lock on a vnode before writing
3181 * one of its buffers. Otherwise we may confuse, or
3182 * in the case of a snapshot vnode, deadlock the
3185 * The lock order here is the reverse of the normal
3186 * of vnode followed by buf lock. This is ok because
3187 * the NOWAIT will prevent deadlock.
3190 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3196 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3198 ASSERT_VOP_LOCKED(vp, "getbuf");
3200 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3201 vn_lock(vp, LK_TRYUPGRADE);
3204 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3205 bp, bp->b_vp, bp->b_flags);
3206 if (curproc == bufdaemonproc) {
3213 vn_finished_write(mp);
3216 flushwithdeps += hasdeps;
3220 * Sleeping on runningbufspace while holding
3221 * vnode lock leads to deadlock.
3223 if (curproc == bufdaemonproc &&
3224 runningbufspace > hirunningspace)
3225 waitrunningbufspace();
3228 vn_finished_write(mp);
3231 mtx_lock(&bqlocks[queue]);
3232 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3233 mtx_unlock(&bqlocks[queue]);
3234 free(sentinel, M_TEMP);
3239 * Check to see if a block is currently memory resident.
3242 incore(struct bufobj *bo, daddr_t blkno)
3247 bp = gbincore(bo, blkno);
3253 * Returns true if no I/O is needed to access the
3254 * associated VM object. This is like incore except
3255 * it also hunts around in the VM system for the data.
3259 inmem(struct vnode * vp, daddr_t blkno)
3262 vm_offset_t toff, tinc, size;
3266 ASSERT_VOP_LOCKED(vp, "inmem");
3268 if (incore(&vp->v_bufobj, blkno))
3270 if (vp->v_mount == NULL)
3277 if (size > vp->v_mount->mnt_stat.f_iosize)
3278 size = vp->v_mount->mnt_stat.f_iosize;
3279 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3281 VM_OBJECT_RLOCK(obj);
3282 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3283 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
3287 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3288 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3289 if (vm_page_is_valid(m,
3290 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
3293 VM_OBJECT_RUNLOCK(obj);
3297 VM_OBJECT_RUNLOCK(obj);
3302 * Set the dirty range for a buffer based on the status of the dirty
3303 * bits in the pages comprising the buffer. The range is limited
3304 * to the size of the buffer.
3306 * Tell the VM system that the pages associated with this buffer
3307 * are clean. This is used for delayed writes where the data is
3308 * going to go to disk eventually without additional VM intevention.
3310 * Note that while we only really need to clean through to b_bcount, we
3311 * just go ahead and clean through to b_bufsize.
3314 vfs_clean_pages_dirty_buf(struct buf *bp)
3316 vm_ooffset_t foff, noff, eoff;
3320 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3323 foff = bp->b_offset;
3324 KASSERT(bp->b_offset != NOOFFSET,
3325 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3327 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3328 vfs_drain_busy_pages(bp);
3329 vfs_setdirty_locked_object(bp);
3330 for (i = 0; i < bp->b_npages; i++) {
3331 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3333 if (eoff > bp->b_offset + bp->b_bufsize)
3334 eoff = bp->b_offset + bp->b_bufsize;
3336 vfs_page_set_validclean(bp, foff, m);
3337 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3340 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3344 vfs_setdirty_locked_object(struct buf *bp)
3349 object = bp->b_bufobj->bo_object;
3350 VM_OBJECT_ASSERT_WLOCKED(object);
3353 * We qualify the scan for modified pages on whether the
3354 * object has been flushed yet.
3356 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
3357 vm_offset_t boffset;
3358 vm_offset_t eoffset;
3361 * test the pages to see if they have been modified directly
3362 * by users through the VM system.
3364 for (i = 0; i < bp->b_npages; i++)
3365 vm_page_test_dirty(bp->b_pages[i]);
3368 * Calculate the encompassing dirty range, boffset and eoffset,
3369 * (eoffset - boffset) bytes.
3372 for (i = 0; i < bp->b_npages; i++) {
3373 if (bp->b_pages[i]->dirty)
3376 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3378 for (i = bp->b_npages - 1; i >= 0; --i) {
3379 if (bp->b_pages[i]->dirty) {
3383 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3386 * Fit it to the buffer.
3389 if (eoffset > bp->b_bcount)
3390 eoffset = bp->b_bcount;
3393 * If we have a good dirty range, merge with the existing
3397 if (boffset < eoffset) {
3398 if (bp->b_dirtyoff > boffset)
3399 bp->b_dirtyoff = boffset;
3400 if (bp->b_dirtyend < eoffset)
3401 bp->b_dirtyend = eoffset;
3407 * Allocate the KVA mapping for an existing buffer.
3408 * If an unmapped buffer is provided but a mapped buffer is requested, take
3409 * also care to properly setup mappings between pages and KVA.
3412 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3414 int bsize, maxsize, need_mapping, need_kva;
3417 need_mapping = bp->b_data == unmapped_buf &&
3418 (gbflags & GB_UNMAPPED) == 0;
3419 need_kva = bp->b_kvabase == unmapped_buf &&
3420 bp->b_data == unmapped_buf &&
3421 (gbflags & GB_KVAALLOC) != 0;
3422 if (!need_mapping && !need_kva)
3425 BUF_CHECK_UNMAPPED(bp);
3427 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3429 * Buffer is not mapped, but the KVA was already
3430 * reserved at the time of the instantiation. Use the
3437 * Calculate the amount of the address space we would reserve
3438 * if the buffer was mapped.
3440 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3441 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3442 offset = blkno * bsize;
3443 maxsize = size + (offset & PAGE_MASK);
3444 maxsize = imax(maxsize, bsize);
3446 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3447 if ((gbflags & GB_NOWAIT_BD) != 0) {
3449 * XXXKIB: defragmentation cannot
3450 * succeed, not sure what else to do.
3452 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3454 atomic_add_int(&mappingrestarts, 1);
3455 bufspace_wait(bp->b_vp, gbflags, 0, 0);
3459 /* b_offset is handled by bpmap_qenter. */
3460 bp->b_data = bp->b_kvabase;
3461 BUF_CHECK_MAPPED(bp);
3469 * Get a block given a specified block and offset into a file/device.
3470 * The buffers B_DONE bit will be cleared on return, making it almost
3471 * ready for an I/O initiation. B_INVAL may or may not be set on
3472 * return. The caller should clear B_INVAL prior to initiating a
3475 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3476 * an existing buffer.
3478 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3479 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3480 * and then cleared based on the backing VM. If the previous buffer is
3481 * non-0-sized but invalid, B_CACHE will be cleared.
3483 * If getblk() must create a new buffer, the new buffer is returned with
3484 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3485 * case it is returned with B_INVAL clear and B_CACHE set based on the
3488 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3489 * B_CACHE bit is clear.
3491 * What this means, basically, is that the caller should use B_CACHE to
3492 * determine whether the buffer is fully valid or not and should clear
3493 * B_INVAL prior to issuing a read. If the caller intends to validate
3494 * the buffer by loading its data area with something, the caller needs
3495 * to clear B_INVAL. If the caller does this without issuing an I/O,
3496 * the caller should set B_CACHE ( as an optimization ), else the caller
3497 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3498 * a write attempt or if it was a successful read. If the caller
3499 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3500 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3503 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3508 int bsize, error, maxsize, vmio;
3511 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3512 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3513 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3514 ASSERT_VOP_LOCKED(vp, "getblk");
3515 if (size > maxbcachebuf)
3516 panic("getblk: size(%d) > maxbcachebuf(%d)\n", size,
3518 if (!unmapped_buf_allowed)
3519 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3524 bp = gbincore(bo, blkno);
3528 * Buffer is in-core. If the buffer is not busy nor managed,
3529 * it must be on a queue.
3531 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3533 if (flags & GB_LOCK_NOWAIT)
3534 lockflags |= LK_NOWAIT;
3536 error = BUF_TIMELOCK(bp, lockflags,
3537 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3540 * If we slept and got the lock we have to restart in case
3541 * the buffer changed identities.
3543 if (error == ENOLCK)
3545 /* We timed out or were interrupted. */
3548 /* If recursed, assume caller knows the rules. */
3549 else if (BUF_LOCKRECURSED(bp))
3553 * The buffer is locked. B_CACHE is cleared if the buffer is
3554 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3555 * and for a VMIO buffer B_CACHE is adjusted according to the
3558 if (bp->b_flags & B_INVAL)
3559 bp->b_flags &= ~B_CACHE;
3560 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3561 bp->b_flags |= B_CACHE;
3562 if (bp->b_flags & B_MANAGED)
3563 MPASS(bp->b_qindex == QUEUE_NONE);
3568 * check for size inconsistencies for non-VMIO case.
3570 if (bp->b_bcount != size) {
3571 if ((bp->b_flags & B_VMIO) == 0 ||
3572 (size > bp->b_kvasize)) {
3573 if (bp->b_flags & B_DELWRI) {
3574 bp->b_flags |= B_NOCACHE;
3577 if (LIST_EMPTY(&bp->b_dep)) {
3578 bp->b_flags |= B_RELBUF;
3581 bp->b_flags |= B_NOCACHE;
3590 * Handle the case of unmapped buffer which should
3591 * become mapped, or the buffer for which KVA
3592 * reservation is requested.
3594 bp_unmapped_get_kva(bp, blkno, size, flags);
3597 * If the size is inconsistent in the VMIO case, we can resize
3598 * the buffer. This might lead to B_CACHE getting set or
3599 * cleared. If the size has not changed, B_CACHE remains
3600 * unchanged from its previous state.
3604 KASSERT(bp->b_offset != NOOFFSET,
3605 ("getblk: no buffer offset"));
3608 * A buffer with B_DELWRI set and B_CACHE clear must
3609 * be committed before we can return the buffer in
3610 * order to prevent the caller from issuing a read
3611 * ( due to B_CACHE not being set ) and overwriting
3614 * Most callers, including NFS and FFS, need this to
3615 * operate properly either because they assume they
3616 * can issue a read if B_CACHE is not set, or because
3617 * ( for example ) an uncached B_DELWRI might loop due
3618 * to softupdates re-dirtying the buffer. In the latter
3619 * case, B_CACHE is set after the first write completes,
3620 * preventing further loops.
3621 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3622 * above while extending the buffer, we cannot allow the
3623 * buffer to remain with B_CACHE set after the write
3624 * completes or it will represent a corrupt state. To
3625 * deal with this we set B_NOCACHE to scrap the buffer
3628 * We might be able to do something fancy, like setting
3629 * B_CACHE in bwrite() except if B_DELWRI is already set,
3630 * so the below call doesn't set B_CACHE, but that gets real
3631 * confusing. This is much easier.
3634 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3635 bp->b_flags |= B_NOCACHE;
3639 bp->b_flags &= ~B_DONE;
3642 * Buffer is not in-core, create new buffer. The buffer
3643 * returned by getnewbuf() is locked. Note that the returned
3644 * buffer is also considered valid (not marked B_INVAL).
3648 * If the user does not want us to create the buffer, bail out
3651 if (flags & GB_NOCREAT)
3653 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3656 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3657 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3658 offset = blkno * bsize;
3659 vmio = vp->v_object != NULL;
3661 maxsize = size + (offset & PAGE_MASK);
3664 /* Do not allow non-VMIO notmapped buffers. */
3665 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3667 maxsize = imax(maxsize, bsize);
3669 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
3671 if (slpflag || slptimeo)
3674 * XXX This is here until the sleep path is diagnosed
3675 * enough to work under very low memory conditions.
3677 * There's an issue on low memory, 4BSD+non-preempt
3678 * systems (eg MIPS routers with 32MB RAM) where buffer
3679 * exhaustion occurs without sleeping for buffer
3680 * reclaimation. This just sticks in a loop and
3681 * constantly attempts to allocate a buffer, which
3682 * hits exhaustion and tries to wakeup bufdaemon.
3683 * This never happens because we never yield.
3685 * The real solution is to identify and fix these cases
3686 * so we aren't effectively busy-waiting in a loop
3687 * until the reclaimation path has cycles to run.
3689 kern_yield(PRI_USER);
3694 * This code is used to make sure that a buffer is not
3695 * created while the getnewbuf routine is blocked.
3696 * This can be a problem whether the vnode is locked or not.
3697 * If the buffer is created out from under us, we have to
3698 * throw away the one we just created.
3700 * Note: this must occur before we associate the buffer
3701 * with the vp especially considering limitations in
3702 * the splay tree implementation when dealing with duplicate
3706 if (gbincore(bo, blkno)) {
3708 bp->b_flags |= B_INVAL;
3710 bufspace_release(maxsize);
3715 * Insert the buffer into the hash, so that it can
3716 * be found by incore.
3718 bp->b_blkno = bp->b_lblkno = blkno;
3719 bp->b_offset = offset;
3724 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3725 * buffer size starts out as 0, B_CACHE will be set by
3726 * allocbuf() for the VMIO case prior to it testing the
3727 * backing store for validity.
3731 bp->b_flags |= B_VMIO;
3732 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3733 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3734 bp, vp->v_object, bp->b_bufobj->bo_object));
3736 bp->b_flags &= ~B_VMIO;
3737 KASSERT(bp->b_bufobj->bo_object == NULL,
3738 ("ARGH! has b_bufobj->bo_object %p %p\n",
3739 bp, bp->b_bufobj->bo_object));
3740 BUF_CHECK_MAPPED(bp);
3744 bufspace_release(maxsize);
3745 bp->b_flags &= ~B_DONE;
3747 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3748 BUF_ASSERT_HELD(bp);
3750 buf_track(bp, __func__);
3751 KASSERT(bp->b_bufobj == bo,
3752 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3757 * Get an empty, disassociated buffer of given size. The buffer is initially
3761 geteblk(int size, int flags)
3766 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3767 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
3768 if ((flags & GB_NOWAIT_BD) &&
3769 (curthread->td_pflags & TDP_BUFNEED) != 0)
3773 bufspace_release(maxsize);
3774 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3775 BUF_ASSERT_HELD(bp);
3780 * Truncate the backing store for a non-vmio buffer.
3783 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
3786 if (bp->b_flags & B_MALLOC) {
3788 * malloced buffers are not shrunk
3790 if (newbsize == 0) {
3791 bufmallocadjust(bp, 0);
3792 free(bp->b_data, M_BIOBUF);
3793 bp->b_data = bp->b_kvabase;
3794 bp->b_flags &= ~B_MALLOC;
3798 vm_hold_free_pages(bp, newbsize);
3799 bufspace_adjust(bp, newbsize);
3803 * Extend the backing for a non-VMIO buffer.
3806 vfs_nonvmio_extend(struct buf *bp, int newbsize)
3812 * We only use malloced memory on the first allocation.
3813 * and revert to page-allocated memory when the buffer
3816 * There is a potential smp race here that could lead
3817 * to bufmallocspace slightly passing the max. It
3818 * is probably extremely rare and not worth worrying
3821 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
3822 bufmallocspace < maxbufmallocspace) {
3823 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
3824 bp->b_flags |= B_MALLOC;
3825 bufmallocadjust(bp, newbsize);
3830 * If the buffer is growing on its other-than-first
3831 * allocation then we revert to the page-allocation
3836 if (bp->b_flags & B_MALLOC) {
3837 origbuf = bp->b_data;
3838 origbufsize = bp->b_bufsize;
3839 bp->b_data = bp->b_kvabase;
3840 bufmallocadjust(bp, 0);
3841 bp->b_flags &= ~B_MALLOC;
3842 newbsize = round_page(newbsize);
3844 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
3845 (vm_offset_t) bp->b_data + newbsize);
3846 if (origbuf != NULL) {
3847 bcopy(origbuf, bp->b_data, origbufsize);
3848 free(origbuf, M_BIOBUF);
3850 bufspace_adjust(bp, newbsize);
3854 * This code constitutes the buffer memory from either anonymous system
3855 * memory (in the case of non-VMIO operations) or from an associated
3856 * VM object (in the case of VMIO operations). This code is able to
3857 * resize a buffer up or down.
3859 * Note that this code is tricky, and has many complications to resolve
3860 * deadlock or inconsistent data situations. Tread lightly!!!
3861 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3862 * the caller. Calling this code willy nilly can result in the loss of data.
3864 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3865 * B_CACHE for the non-VMIO case.
3868 allocbuf(struct buf *bp, int size)
3872 BUF_ASSERT_HELD(bp);
3874 if (bp->b_bcount == size)
3877 if (bp->b_kvasize != 0 && bp->b_kvasize < size)
3878 panic("allocbuf: buffer too small");
3880 newbsize = roundup2(size, DEV_BSIZE);
3881 if ((bp->b_flags & B_VMIO) == 0) {
3882 if ((bp->b_flags & B_MALLOC) == 0)
3883 newbsize = round_page(newbsize);
3885 * Just get anonymous memory from the kernel. Don't
3886 * mess with B_CACHE.
3888 if (newbsize < bp->b_bufsize)
3889 vfs_nonvmio_truncate(bp, newbsize);
3890 else if (newbsize > bp->b_bufsize)
3891 vfs_nonvmio_extend(bp, newbsize);
3895 desiredpages = (size == 0) ? 0 :
3896 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3898 if (bp->b_flags & B_MALLOC)
3899 panic("allocbuf: VMIO buffer can't be malloced");
3901 * Set B_CACHE initially if buffer is 0 length or will become
3904 if (size == 0 || bp->b_bufsize == 0)
3905 bp->b_flags |= B_CACHE;
3907 if (newbsize < bp->b_bufsize)
3908 vfs_vmio_truncate(bp, desiredpages);
3909 /* XXX This looks as if it should be newbsize > b_bufsize */
3910 else if (size > bp->b_bcount)
3911 vfs_vmio_extend(bp, desiredpages, size);
3912 bufspace_adjust(bp, newbsize);
3914 bp->b_bcount = size; /* requested buffer size. */
3918 extern int inflight_transient_maps;
3921 biodone(struct bio *bp)
3924 void (*done)(struct bio *);
3925 vm_offset_t start, end;
3927 biotrack(bp, __func__);
3928 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3929 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3930 bp->bio_flags |= BIO_UNMAPPED;
3931 start = trunc_page((vm_offset_t)bp->bio_data);
3932 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3933 bp->bio_data = unmapped_buf;
3934 pmap_qremove(start, atop(end - start));
3935 vmem_free(transient_arena, start, end - start);
3936 atomic_add_int(&inflight_transient_maps, -1);
3938 done = bp->bio_done;
3940 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3942 bp->bio_flags |= BIO_DONE;
3950 * Wait for a BIO to finish.
3953 biowait(struct bio *bp, const char *wchan)
3957 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3959 while ((bp->bio_flags & BIO_DONE) == 0)
3960 msleep(bp, mtxp, PRIBIO, wchan, 0);
3962 if (bp->bio_error != 0)
3963 return (bp->bio_error);
3964 if (!(bp->bio_flags & BIO_ERROR))
3970 biofinish(struct bio *bp, struct devstat *stat, int error)
3974 bp->bio_error = error;
3975 bp->bio_flags |= BIO_ERROR;
3978 devstat_end_transaction_bio(stat, bp);
3982 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
3984 biotrack_buf(struct bio *bp, const char *location)
3987 buf_track(bp->bio_track_bp, location);
3994 * Wait for buffer I/O completion, returning error status. The buffer
3995 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3996 * error and cleared.
3999 bufwait(struct buf *bp)
4001 if (bp->b_iocmd == BIO_READ)
4002 bwait(bp, PRIBIO, "biord");
4004 bwait(bp, PRIBIO, "biowr");
4005 if (bp->b_flags & B_EINTR) {
4006 bp->b_flags &= ~B_EINTR;
4009 if (bp->b_ioflags & BIO_ERROR) {
4010 return (bp->b_error ? bp->b_error : EIO);
4019 * Finish I/O on a buffer, optionally calling a completion function.
4020 * This is usually called from an interrupt so process blocking is
4023 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4024 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
4025 * assuming B_INVAL is clear.
4027 * For the VMIO case, we set B_CACHE if the op was a read and no
4028 * read error occurred, or if the op was a write. B_CACHE is never
4029 * set if the buffer is invalid or otherwise uncacheable.
4031 * biodone does not mess with B_INVAL, allowing the I/O routine or the
4032 * initiator to leave B_INVAL set to brelse the buffer out of existence
4033 * in the biodone routine.
4036 bufdone(struct buf *bp)
4038 struct bufobj *dropobj;
4039 void (*biodone)(struct buf *);
4041 buf_track(bp, __func__);
4042 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4045 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4046 BUF_ASSERT_HELD(bp);
4048 runningbufwakeup(bp);
4049 if (bp->b_iocmd == BIO_WRITE)
4050 dropobj = bp->b_bufobj;
4051 /* call optional completion function if requested */
4052 if (bp->b_iodone != NULL) {
4053 biodone = bp->b_iodone;
4054 bp->b_iodone = NULL;
4057 bufobj_wdrop(dropobj);
4064 bufobj_wdrop(dropobj);
4068 bufdone_finish(struct buf *bp)
4070 BUF_ASSERT_HELD(bp);
4072 if (!LIST_EMPTY(&bp->b_dep))
4075 if (bp->b_flags & B_VMIO) {
4077 * Set B_CACHE if the op was a normal read and no error
4078 * occurred. B_CACHE is set for writes in the b*write()
4081 if (bp->b_iocmd == BIO_READ &&
4082 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4083 !(bp->b_ioflags & BIO_ERROR))
4084 bp->b_flags |= B_CACHE;
4085 vfs_vmio_iodone(bp);
4089 * For asynchronous completions, release the buffer now. The brelse
4090 * will do a wakeup there if necessary - so no need to do a wakeup
4091 * here in the async case. The sync case always needs to do a wakeup.
4093 if (bp->b_flags & B_ASYNC) {
4094 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4095 (bp->b_ioflags & BIO_ERROR))
4104 * This routine is called in lieu of iodone in the case of
4105 * incomplete I/O. This keeps the busy status for pages
4109 vfs_unbusy_pages(struct buf *bp)
4115 runningbufwakeup(bp);
4116 if (!(bp->b_flags & B_VMIO))
4119 obj = bp->b_bufobj->bo_object;
4120 VM_OBJECT_WLOCK(obj);
4121 for (i = 0; i < bp->b_npages; i++) {
4123 if (m == bogus_page) {
4124 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4126 panic("vfs_unbusy_pages: page missing\n");
4128 if (buf_mapped(bp)) {
4129 BUF_CHECK_MAPPED(bp);
4130 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4131 bp->b_pages, bp->b_npages);
4133 BUF_CHECK_UNMAPPED(bp);
4137 vm_object_pip_wakeupn(obj, bp->b_npages);
4138 VM_OBJECT_WUNLOCK(obj);
4142 * vfs_page_set_valid:
4144 * Set the valid bits in a page based on the supplied offset. The
4145 * range is restricted to the buffer's size.
4147 * This routine is typically called after a read completes.
4150 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4155 * Compute the end offset, eoff, such that [off, eoff) does not span a
4156 * page boundary and eoff is not greater than the end of the buffer.
4157 * The end of the buffer, in this case, is our file EOF, not the
4158 * allocation size of the buffer.
4160 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4161 if (eoff > bp->b_offset + bp->b_bcount)
4162 eoff = bp->b_offset + bp->b_bcount;
4165 * Set valid range. This is typically the entire buffer and thus the
4169 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4173 * vfs_page_set_validclean:
4175 * Set the valid bits and clear the dirty bits in a page based on the
4176 * supplied offset. The range is restricted to the buffer's size.
4179 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4181 vm_ooffset_t soff, eoff;
4184 * Start and end offsets in buffer. eoff - soff may not cross a
4185 * page boundary or cross the end of the buffer. The end of the
4186 * buffer, in this case, is our file EOF, not the allocation size
4190 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4191 if (eoff > bp->b_offset + bp->b_bcount)
4192 eoff = bp->b_offset + bp->b_bcount;
4195 * Set valid range. This is typically the entire buffer and thus the
4199 vm_page_set_validclean(
4201 (vm_offset_t) (soff & PAGE_MASK),
4202 (vm_offset_t) (eoff - soff)
4208 * Ensure that all buffer pages are not exclusive busied. If any page is
4209 * exclusive busy, drain it.
4212 vfs_drain_busy_pages(struct buf *bp)
4217 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4219 for (i = 0; i < bp->b_npages; i++) {
4221 if (vm_page_xbusied(m)) {
4222 for (; last_busied < i; last_busied++)
4223 vm_page_sbusy(bp->b_pages[last_busied]);
4224 while (vm_page_xbusied(m)) {
4226 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4227 vm_page_busy_sleep(m, "vbpage", true);
4228 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4232 for (i = 0; i < last_busied; i++)
4233 vm_page_sunbusy(bp->b_pages[i]);
4237 * This routine is called before a device strategy routine.
4238 * It is used to tell the VM system that paging I/O is in
4239 * progress, and treat the pages associated with the buffer
4240 * almost as being exclusive busy. Also the object paging_in_progress
4241 * flag is handled to make sure that the object doesn't become
4244 * Since I/O has not been initiated yet, certain buffer flags
4245 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4246 * and should be ignored.
4249 vfs_busy_pages(struct buf *bp, int clear_modify)
4257 if (!(bp->b_flags & B_VMIO))
4260 obj = bp->b_bufobj->bo_object;
4261 foff = bp->b_offset;
4262 KASSERT(bp->b_offset != NOOFFSET,
4263 ("vfs_busy_pages: no buffer offset"));
4264 VM_OBJECT_WLOCK(obj);
4265 vfs_drain_busy_pages(bp);
4266 if (bp->b_bufsize != 0)
4267 vfs_setdirty_locked_object(bp);
4269 for (i = 0; i < bp->b_npages; i++) {
4272 if ((bp->b_flags & B_CLUSTER) == 0) {
4273 vm_object_pip_add(obj, 1);
4277 * When readying a buffer for a read ( i.e
4278 * clear_modify == 0 ), it is important to do
4279 * bogus_page replacement for valid pages in
4280 * partially instantiated buffers. Partially
4281 * instantiated buffers can, in turn, occur when
4282 * reconstituting a buffer from its VM backing store
4283 * base. We only have to do this if B_CACHE is
4284 * clear ( which causes the I/O to occur in the
4285 * first place ). The replacement prevents the read
4286 * I/O from overwriting potentially dirty VM-backed
4287 * pages. XXX bogus page replacement is, uh, bogus.
4288 * It may not work properly with small-block devices.
4289 * We need to find a better way.
4292 pmap_remove_write(m);
4293 vfs_page_set_validclean(bp, foff, m);
4294 } else if (m->valid == VM_PAGE_BITS_ALL &&
4295 (bp->b_flags & B_CACHE) == 0) {
4296 bp->b_pages[i] = bogus_page;
4299 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4301 VM_OBJECT_WUNLOCK(obj);
4302 if (bogus && buf_mapped(bp)) {
4303 BUF_CHECK_MAPPED(bp);
4304 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4305 bp->b_pages, bp->b_npages);
4310 * vfs_bio_set_valid:
4312 * Set the range within the buffer to valid. The range is
4313 * relative to the beginning of the buffer, b_offset. Note that
4314 * b_offset itself may be offset from the beginning of the first
4318 vfs_bio_set_valid(struct buf *bp, int base, int size)
4323 if (!(bp->b_flags & B_VMIO))
4327 * Fixup base to be relative to beginning of first page.
4328 * Set initial n to be the maximum number of bytes in the
4329 * first page that can be validated.
4331 base += (bp->b_offset & PAGE_MASK);
4332 n = PAGE_SIZE - (base & PAGE_MASK);
4334 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4335 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4339 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4344 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4350 * If the specified buffer is a non-VMIO buffer, clear the entire
4351 * buffer. If the specified buffer is a VMIO buffer, clear and
4352 * validate only the previously invalid portions of the buffer.
4353 * This routine essentially fakes an I/O, so we need to clear
4354 * BIO_ERROR and B_INVAL.
4356 * Note that while we only theoretically need to clear through b_bcount,
4357 * we go ahead and clear through b_bufsize.
4360 vfs_bio_clrbuf(struct buf *bp)
4362 int i, j, mask, sa, ea, slide;
4364 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4368 bp->b_flags &= ~B_INVAL;
4369 bp->b_ioflags &= ~BIO_ERROR;
4370 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4371 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4372 (bp->b_offset & PAGE_MASK) == 0) {
4373 if (bp->b_pages[0] == bogus_page)
4375 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4376 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4377 if ((bp->b_pages[0]->valid & mask) == mask)
4379 if ((bp->b_pages[0]->valid & mask) == 0) {
4380 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4381 bp->b_pages[0]->valid |= mask;
4385 sa = bp->b_offset & PAGE_MASK;
4387 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4388 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4389 ea = slide & PAGE_MASK;
4392 if (bp->b_pages[i] == bogus_page)
4395 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4396 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4397 if ((bp->b_pages[i]->valid & mask) == mask)
4399 if ((bp->b_pages[i]->valid & mask) == 0)
4400 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4402 for (; sa < ea; sa += DEV_BSIZE, j++) {
4403 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4404 pmap_zero_page_area(bp->b_pages[i],
4409 bp->b_pages[i]->valid |= mask;
4412 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4417 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4422 if (buf_mapped(bp)) {
4423 BUF_CHECK_MAPPED(bp);
4424 bzero(bp->b_data + base, size);
4426 BUF_CHECK_UNMAPPED(bp);
4427 n = PAGE_SIZE - (base & PAGE_MASK);
4428 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4432 pmap_zero_page_area(m, base & PAGE_MASK, n);
4441 * Update buffer flags based on I/O request parameters, optionally releasing the
4442 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM,
4443 * where they may be placed on a page queue (VMIO) or freed immediately (direct
4444 * I/O). Otherwise the buffer is released to the cache.
4447 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4450 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4451 ("buf %p non-VMIO noreuse", bp));
4453 if ((ioflag & IO_DIRECT) != 0)
4454 bp->b_flags |= B_DIRECT;
4455 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4456 bp->b_flags |= B_RELBUF;
4457 if ((ioflag & IO_NOREUSE) != 0)
4458 bp->b_flags |= B_NOREUSE;
4466 vfs_bio_brelse(struct buf *bp, int ioflag)
4469 b_io_dismiss(bp, ioflag, true);
4473 vfs_bio_set_flags(struct buf *bp, int ioflag)
4476 b_io_dismiss(bp, ioflag, false);
4480 * vm_hold_load_pages and vm_hold_free_pages get pages into
4481 * a buffers address space. The pages are anonymous and are
4482 * not associated with a file object.
4485 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4491 BUF_CHECK_MAPPED(bp);
4493 to = round_page(to);
4494 from = round_page(from);
4495 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4497 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4500 * note: must allocate system pages since blocking here
4501 * could interfere with paging I/O, no matter which
4504 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4505 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4510 pmap_qenter(pg, &p, 1);
4511 bp->b_pages[index] = p;
4513 bp->b_npages = index;
4516 /* Return pages associated with this buf to the vm system */
4518 vm_hold_free_pages(struct buf *bp, int newbsize)
4522 int index, newnpages;
4524 BUF_CHECK_MAPPED(bp);
4526 from = round_page((vm_offset_t)bp->b_data + newbsize);
4527 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4528 if (bp->b_npages > newnpages)
4529 pmap_qremove(from, bp->b_npages - newnpages);
4530 for (index = newnpages; index < bp->b_npages; index++) {
4531 p = bp->b_pages[index];
4532 bp->b_pages[index] = NULL;
4536 atomic_subtract_int(&vm_cnt.v_wire_count, bp->b_npages - newnpages);
4537 bp->b_npages = newnpages;
4541 * Map an IO request into kernel virtual address space.
4543 * All requests are (re)mapped into kernel VA space.
4544 * Notice that we use b_bufsize for the size of the buffer
4545 * to be mapped. b_bcount might be modified by the driver.
4547 * Note that even if the caller determines that the address space should
4548 * be valid, a race or a smaller-file mapped into a larger space may
4549 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4550 * check the return value.
4552 * This function only works with pager buffers.
4555 vmapbuf(struct buf *bp, int mapbuf)
4560 if (bp->b_bufsize < 0)
4562 prot = VM_PROT_READ;
4563 if (bp->b_iocmd == BIO_READ)
4564 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4565 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4566 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4567 btoc(MAXPHYS))) < 0)
4569 bp->b_npages = pidx;
4570 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4571 if (mapbuf || !unmapped_buf_allowed) {
4572 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
4573 bp->b_data = bp->b_kvabase + bp->b_offset;
4575 bp->b_data = unmapped_buf;
4580 * Free the io map PTEs associated with this IO operation.
4581 * We also invalidate the TLB entries and restore the original b_addr.
4583 * This function only works with pager buffers.
4586 vunmapbuf(struct buf *bp)
4590 npages = bp->b_npages;
4592 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4593 vm_page_unhold_pages(bp->b_pages, npages);
4595 bp->b_data = unmapped_buf;
4599 bdone(struct buf *bp)
4603 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4605 bp->b_flags |= B_DONE;
4611 bwait(struct buf *bp, u_char pri, const char *wchan)
4615 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4617 while ((bp->b_flags & B_DONE) == 0)
4618 msleep(bp, mtxp, pri, wchan, 0);
4623 bufsync(struct bufobj *bo, int waitfor)
4626 return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
4630 bufstrategy(struct bufobj *bo, struct buf *bp)
4636 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4637 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4638 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4639 i = VOP_STRATEGY(vp, bp);
4640 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4644 bufobj_wrefl(struct bufobj *bo)
4647 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4648 ASSERT_BO_WLOCKED(bo);
4653 bufobj_wref(struct bufobj *bo)
4656 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4663 bufobj_wdrop(struct bufobj *bo)
4666 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4668 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4669 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4670 bo->bo_flag &= ~BO_WWAIT;
4671 wakeup(&bo->bo_numoutput);
4677 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4681 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4682 ASSERT_BO_WLOCKED(bo);
4684 while (bo->bo_numoutput) {
4685 bo->bo_flag |= BO_WWAIT;
4686 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4687 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4695 * Set bio_data or bio_ma for struct bio from the struct buf.
4698 bdata2bio(struct buf *bp, struct bio *bip)
4701 if (!buf_mapped(bp)) {
4702 KASSERT(unmapped_buf_allowed, ("unmapped"));
4703 bip->bio_ma = bp->b_pages;
4704 bip->bio_ma_n = bp->b_npages;
4705 bip->bio_data = unmapped_buf;
4706 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4707 bip->bio_flags |= BIO_UNMAPPED;
4708 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4709 PAGE_SIZE == bp->b_npages,
4710 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4711 (long long)bip->bio_length, bip->bio_ma_n));
4713 bip->bio_data = bp->b_data;
4719 * The MIPS pmap code currently doesn't handle aliased pages.
4720 * The VIPT caches may not handle page aliasing themselves, leading
4721 * to data corruption.
4723 * As such, this code makes a system extremely unhappy if said
4724 * system doesn't support unaliasing the above situation in hardware.
4725 * Some "recent" systems (eg some mips24k/mips74k cores) don't enable
4726 * this feature at build time, so it has to be handled in software.
4728 * Once the MIPS pmap/cache code grows to support this function on
4729 * earlier chips, it should be flipped back off.
4732 static int buf_pager_relbuf = 1;
4734 static int buf_pager_relbuf = 0;
4736 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
4737 &buf_pager_relbuf, 0,
4738 "Make buffer pager release buffers after reading");
4741 * The buffer pager. It uses buffer reads to validate pages.
4743 * In contrast to the generic local pager from vm/vnode_pager.c, this
4744 * pager correctly and easily handles volumes where the underlying
4745 * device block size is greater than the machine page size. The
4746 * buffer cache transparently extends the requested page run to be
4747 * aligned at the block boundary, and does the necessary bogus page
4748 * replacements in the addends to avoid obliterating already valid
4751 * The only non-trivial issue is that the exclusive busy state for
4752 * pages, which is assumed by the vm_pager_getpages() interface, is
4753 * incompatible with the VMIO buffer cache's desire to share-busy the
4754 * pages. This function performs a trivial downgrade of the pages'
4755 * state before reading buffers, and a less trivial upgrade from the
4756 * shared-busy to excl-busy state after the read.
4759 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
4760 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
4761 vbg_get_blksize_t get_blksize)
4768 vm_ooffset_t la, lb, poff, poffe;
4770 int bo_bs, br_flags, error, i, pgsin, pgsin_a, pgsin_b;
4773 object = vp->v_object;
4775 la = IDX_TO_OFF(ma[count - 1]->pindex);
4776 if (la >= object->un_pager.vnp.vnp_size)
4777 return (VM_PAGER_BAD);
4778 lpart = la + PAGE_SIZE > object->un_pager.vnp.vnp_size;
4779 bo_bs = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)));
4782 * Calculate read-ahead, behind and total pages.
4785 lb = IDX_TO_OFF(ma[0]->pindex);
4786 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
4788 if (rbehind != NULL)
4790 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
4791 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
4792 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
4797 VM_CNT_INC(v_vnodein);
4798 VM_CNT_ADD(v_vnodepgsin, pgsin);
4800 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
4801 != 0) ? GB_UNMAPPED : 0;
4802 VM_OBJECT_WLOCK(object);
4804 for (i = 0; i < count; i++)
4805 vm_page_busy_downgrade(ma[i]);
4806 VM_OBJECT_WUNLOCK(object);
4809 for (i = 0; i < count; i++) {
4813 * Pages are shared busy and the object lock is not
4814 * owned, which together allow for the pages'
4815 * invalidation. The racy test for validity avoids
4816 * useless creation of the buffer for the most typical
4817 * case when invalidation is not used in redo or for
4818 * parallel read. The shared->excl upgrade loop at
4819 * the end of the function catches the race in a
4820 * reliable way (protected by the object lock).
4822 if (m->valid == VM_PAGE_BITS_ALL)
4825 poff = IDX_TO_OFF(m->pindex);
4826 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
4827 for (; poff < poffe; poff += bsize) {
4828 lbn = get_lblkno(vp, poff);
4833 bsize = get_blksize(vp, lbn);
4834 error = bread_gb(vp, lbn, bsize, curthread->td_ucred,
4838 if (LIST_EMPTY(&bp->b_dep)) {
4840 * Invalidation clears m->valid, but
4841 * may leave B_CACHE flag if the
4842 * buffer existed at the invalidation
4843 * time. In this case, recycle the
4844 * buffer to do real read on next
4845 * bread() after redo.
4847 * Otherwise B_RELBUF is not strictly
4848 * necessary, enable to reduce buf
4851 if (buf_pager_relbuf ||
4852 m->valid != VM_PAGE_BITS_ALL)
4853 bp->b_flags |= B_RELBUF;
4855 bp->b_flags &= ~B_NOCACHE;
4861 KASSERT(1 /* racy, enable for debugging */ ||
4862 m->valid == VM_PAGE_BITS_ALL || i == count - 1,
4863 ("buf %d %p invalid", i, m));
4864 if (i == count - 1 && lpart) {
4865 VM_OBJECT_WLOCK(object);
4866 if (m->valid != 0 &&
4867 m->valid != VM_PAGE_BITS_ALL)
4868 vm_page_zero_invalid(m, TRUE);
4869 VM_OBJECT_WUNLOCK(object);
4875 VM_OBJECT_WLOCK(object);
4877 for (i = 0; i < count; i++) {
4878 vm_page_sunbusy(ma[i]);
4879 ma[i] = vm_page_grab(object, ma[i]->pindex, VM_ALLOC_NORMAL);
4882 * Since the pages were only sbusy while neither the
4883 * buffer nor the object lock was held by us, or
4884 * reallocated while vm_page_grab() slept for busy
4885 * relinguish, they could have been invalidated.
4886 * Recheck the valid bits and re-read as needed.
4888 * Note that the last page is made fully valid in the
4889 * read loop, and partial validity for the page at
4890 * index count - 1 could mean that the page was
4891 * invalidated or removed, so we must restart for
4894 if (ma[i]->valid != VM_PAGE_BITS_ALL)
4897 if (redo && error == 0)
4899 VM_OBJECT_WUNLOCK(object);
4900 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
4903 #include "opt_ddb.h"
4905 #include <ddb/ddb.h>
4907 /* DDB command to show buffer data */
4908 DB_SHOW_COMMAND(buffer, db_show_buffer)
4911 struct buf *bp = (struct buf *)addr;
4912 #ifdef FULL_BUF_TRACKING
4917 db_printf("usage: show buffer <addr>\n");
4921 db_printf("buf at %p\n", bp);
4922 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4923 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4924 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4926 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4927 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4929 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4930 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4931 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4932 db_printf("b_kvabase = %p, b_kvasize = %d\n",
4933 bp->b_kvabase, bp->b_kvasize);
4936 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4937 for (i = 0; i < bp->b_npages; i++) {
4941 db_printf("(%p, 0x%lx, 0x%lx)", m->object,
4943 (u_long)VM_PAGE_TO_PHYS(m));
4945 db_printf("( ??? )");
4946 if ((i + 1) < bp->b_npages)
4951 #if defined(FULL_BUF_TRACKING)
4952 db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
4954 i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
4955 for (j = 1; j <= BUF_TRACKING_SIZE; j++) {
4956 if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL)
4958 db_printf(" %2u: %s\n", j,
4959 bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
4961 #elif defined(BUF_TRACKING)
4962 db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
4965 BUF_LOCKPRINTINFO(bp);
4968 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4973 for (i = 0; i < nbuf; i++) {
4975 if (BUF_ISLOCKED(bp)) {
4976 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4984 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4990 db_printf("usage: show vnodebufs <addr>\n");
4993 vp = (struct vnode *)addr;
4994 db_printf("Clean buffers:\n");
4995 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4996 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4999 db_printf("Dirty buffers:\n");
5000 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5001 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5006 DB_COMMAND(countfreebufs, db_coundfreebufs)
5009 int i, used = 0, nfree = 0;
5012 db_printf("usage: countfreebufs\n");
5016 for (i = 0; i < nbuf; i++) {
5018 if (bp->b_qindex == QUEUE_EMPTY)
5024 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5026 db_printf("numfreebuffers is %d\n", numfreebuffers);