2 * Copyright (c) 2004 Poul-Henning Kamp
3 * Copyright (c) 1994,1997 John S. Dyson
4 * Copyright (c) 2013 The FreeBSD Foundation
7 * Portions of this software were developed by Konstantin Belousov
8 * under sponsorship from the FreeBSD Foundation.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * this file contains a new buffer I/O scheme implementing a coherent
34 * VM object and buffer cache scheme. Pains have been taken to make
35 * sure that the performance degradation associated with schemes such
36 * as this is not realized.
38 * Author: John S. Dyson
39 * Significant help during the development and debugging phases
40 * had been provided by David Greenman, also of the FreeBSD core team.
42 * see man buf(9) for more info.
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
49 #include <sys/systm.h>
53 #include <sys/devicestat.h>
54 #include <sys/eventhandler.h>
56 #include <sys/limits.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mutex.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
64 #include <sys/racct.h>
65 #include <sys/resourcevar.h>
66 #include <sys/rwlock.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysproto.h>
71 #include <sys/vmmeter.h>
72 #include <sys/vnode.h>
73 #include <sys/watchdog.h>
74 #include <geom/geom.h>
76 #include <vm/vm_param.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_object.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_pageout.h>
81 #include <vm/vm_pager.h>
82 #include <vm/vm_extern.h>
83 #include <vm/vm_map.h>
84 #include <vm/swap_pager.h>
85 #include "opt_compat.h"
88 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
90 struct bio_ops bioops; /* I/O operation notification */
92 struct buf_ops buf_ops_bio = {
93 .bop_name = "buf_ops_bio",
94 .bop_write = bufwrite,
95 .bop_strategy = bufstrategy,
97 .bop_bdflush = bufbdflush,
100 static struct buf *buf; /* buffer header pool */
101 extern struct buf *swbuf; /* Swap buffer header pool. */
102 caddr_t unmapped_buf;
104 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
105 struct proc *bufdaemonproc;
106 struct proc *bufspacedaemonproc;
108 static int inmem(struct vnode *vp, daddr_t blkno);
109 static void vm_hold_free_pages(struct buf *bp, int newbsize);
110 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
112 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
113 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
115 static void vfs_clean_pages_dirty_buf(struct buf *bp);
116 static void vfs_setdirty_locked_object(struct buf *bp);
117 static void vfs_vmio_invalidate(struct buf *bp);
118 static void vfs_vmio_truncate(struct buf *bp, int npages);
119 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
120 static int vfs_bio_clcheck(struct vnode *vp, int size,
121 daddr_t lblkno, daddr_t blkno);
122 static int buf_flush(struct vnode *vp, int);
123 static int buf_recycle(bool);
124 static int buf_scan(bool);
125 static int flushbufqueues(struct vnode *, int, int);
126 static void buf_daemon(void);
127 static void bremfreel(struct buf *bp);
128 static __inline void bd_wakeup(void);
129 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
130 static void bufkva_reclaim(vmem_t *, int);
131 static void bufkva_free(struct buf *);
132 static int buf_import(void *, void **, int, int);
133 static void buf_release(void *, void **, int);
135 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
136 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
137 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
140 int vmiodirenable = TRUE;
141 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
142 "Use the VM system for directory writes");
143 long runningbufspace;
144 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
145 "Amount of presently outstanding async buffer io");
146 static long bufspace;
147 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
148 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
149 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
150 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
152 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
153 "Physical memory used for buffers");
155 static long bufkvaspace;
156 SYSCTL_LONG(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace, 0,
157 "Kernel virtual memory used for buffers");
158 static long maxbufspace;
159 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RW, &maxbufspace, 0,
160 "Maximum allowed value of bufspace (including metadata)");
161 static long bufmallocspace;
162 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
163 "Amount of malloced memory for buffers");
164 static long maxbufmallocspace;
165 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
166 0, "Maximum amount of malloced memory for buffers");
167 static long lobufspace;
168 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RW, &lobufspace, 0,
169 "Minimum amount of buffers we want to have");
171 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RW, &hibufspace, 0,
172 "Maximum allowed value of bufspace (excluding metadata)");
174 SYSCTL_LONG(_vfs, OID_AUTO, bufspacethresh, CTLFLAG_RW, &bufspacethresh,
175 0, "Bufspace consumed before waking the daemon to free some");
176 static int buffreekvacnt;
177 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
178 "Number of times we have freed the KVA space from some buffer");
179 static int bufdefragcnt;
180 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
181 "Number of times we have had to repeat buffer allocation to defragment");
182 static long lorunningspace;
183 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
184 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
185 "Minimum preferred space used for in-progress I/O");
186 static long hirunningspace;
187 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
188 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
189 "Maximum amount of space to use for in-progress I/O");
190 int dirtybufferflushes;
191 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
192 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
194 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
195 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
196 int altbufferflushes;
197 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
198 0, "Number of fsync flushes to limit dirty buffers");
199 static int recursiveflushes;
200 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
201 0, "Number of flushes skipped due to being recursive");
202 static int numdirtybuffers;
203 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
204 "Number of buffers that are dirty (has unwritten changes) at the moment");
205 static int lodirtybuffers;
206 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
207 "How many buffers we want to have free before bufdaemon can sleep");
208 static int hidirtybuffers;
209 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
210 "When the number of dirty buffers is considered severe");
212 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
213 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
214 static int numfreebuffers;
215 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
216 "Number of free buffers");
217 static int lofreebuffers;
218 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
219 "Target number of free buffers");
220 static int hifreebuffers;
221 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
222 "Threshold for clean buffer recycling");
223 static int getnewbufcalls;
224 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
225 "Number of calls to getnewbuf");
226 static int getnewbufrestarts;
227 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
228 "Number of times getnewbuf has had to restart a buffer acquisition");
229 static int mappingrestarts;
230 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
231 "Number of times getblk has had to restart a buffer mapping for "
233 static int numbufallocfails;
234 SYSCTL_INT(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW, &numbufallocfails, 0,
235 "Number of times buffer allocations failed");
236 static int flushbufqtarget = 100;
237 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
238 "Amount of work to do in flushbufqueues when helping bufdaemon");
239 static long notbufdflushes;
240 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 0,
241 "Number of dirty buffer flushes done by the bufdaemon helpers");
242 static long barrierwrites;
243 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
244 "Number of barrier writes");
245 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
246 &unmapped_buf_allowed, 0,
247 "Permit the use of the unmapped i/o");
250 * This lock synchronizes access to bd_request.
252 static struct mtx_padalign bdlock;
255 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
256 * waitrunningbufspace().
258 static struct mtx_padalign rbreqlock;
261 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
263 static struct rwlock_padalign nblock;
266 * Lock that protects bdirtywait.
268 static struct mtx_padalign bdirtylock;
271 * Wakeup point for bufdaemon, as well as indicator of whether it is already
272 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
275 static int bd_request;
278 * Request/wakeup point for the bufspace daemon.
280 static int bufspace_request;
283 * Request for the buf daemon to write more buffers than is indicated by
284 * lodirtybuf. This may be necessary to push out excess dependencies or
285 * defragment the address space where a simple count of the number of dirty
286 * buffers is insufficient to characterize the demand for flushing them.
288 static int bd_speedupreq;
291 * Synchronization (sleep/wakeup) variable for active buffer space requests.
292 * Set when wait starts, cleared prior to wakeup().
293 * Used in runningbufwakeup() and waitrunningbufspace().
295 static int runningbufreq;
298 * Synchronization (sleep/wakeup) variable for buffer requests.
299 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
301 * Used in numdirtywakeup(), bufspace_wakeup(), bwillwrite(),
302 * getnewbuf(), and getblk().
304 static volatile int needsbuffer;
307 * Synchronization for bwillwrite() waiters.
309 static int bdirtywait;
312 * Definitions for the buffer free lists.
314 #define QUEUE_NONE 0 /* on no queue */
315 #define QUEUE_EMPTY 1 /* empty buffer headers */
316 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
317 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
318 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
320 /* Maximum number of clean buffer queues. */
321 #define CLEAN_QUEUES 16
323 /* Configured number of clean queues. */
324 static int clean_queues;
326 /* Maximum number of buffer queues. */
327 #define BUFFER_QUEUES (QUEUE_CLEAN + CLEAN_QUEUES)
329 /* Queues for free buffers with various properties */
330 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
332 static int bq_len[BUFFER_QUEUES];
336 * Lock for each bufqueue
338 static struct mtx_padalign bqlocks[BUFFER_QUEUES];
341 * per-cpu empty buffer cache.
346 * Single global constant for BUF_WMESG, to avoid getting multiple references.
347 * buf_wmesg is referred from macros.
349 const char *buf_wmesg = BUF_WMESG;
352 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
357 value = *(long *)arg1;
358 error = sysctl_handle_long(oidp, &value, 0, req);
359 if (error != 0 || req->newptr == NULL)
361 mtx_lock(&rbreqlock);
362 if (arg1 == &hirunningspace) {
363 if (value < lorunningspace)
366 hirunningspace = value;
368 KASSERT(arg1 == &lorunningspace,
369 ("%s: unknown arg1", __func__));
370 if (value > hirunningspace)
373 lorunningspace = value;
375 mtx_unlock(&rbreqlock);
379 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
380 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
382 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
387 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
388 return (sysctl_handle_long(oidp, arg1, arg2, req));
389 lvalue = *(long *)arg1;
390 if (lvalue > INT_MAX)
391 /* On overflow, still write out a long to trigger ENOMEM. */
392 return (sysctl_handle_long(oidp, &lvalue, 0, req));
394 return (sysctl_handle_int(oidp, &ivalue, 0, req));
403 return ((atomic_fetchadd_int(&nextq, 1) % clean_queues) + QUEUE_CLEAN);
407 bqisclean(int qindex)
410 return (qindex >= QUEUE_CLEAN && qindex < QUEUE_CLEAN + CLEAN_QUEUES);
416 * Return the appropriate queue lock based on the index.
418 static inline struct mtx *
422 return (struct mtx *)&bqlocks[qindex];
428 * Wakeup any bwillwrite() waiters.
433 mtx_lock(&bdirtylock);
438 mtx_unlock(&bdirtylock);
444 * Decrement the numdirtybuffers count by one and wakeup any
445 * threads blocked in bwillwrite().
451 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
452 (lodirtybuffers + hidirtybuffers) / 2)
459 * Increment the numdirtybuffers count by one and wakeup the buf
467 * Only do the wakeup once as we cross the boundary. The
468 * buf daemon will keep running until the condition clears.
470 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
471 (lodirtybuffers + hidirtybuffers) / 2)
478 * Called when buffer space is potentially available for recovery.
479 * getnewbuf() will block on this flag when it is unable to free
480 * sufficient buffer space. Buffer space becomes recoverable when
481 * bp's get placed back in the queues.
484 bufspace_wakeup(void)
488 * If someone is waiting for bufspace, wake them up.
490 * Since needsbuffer is set prior to doing an additional queue
491 * scan it is safe to check for the flag prior to acquiring the
492 * lock. The thread that is preparing to scan again before
493 * blocking would discover the buf we released.
497 if (atomic_cmpset_int(&needsbuffer, 1, 0) == 1)
498 wakeup(__DEVOLATILE(void *, &needsbuffer));
504 * bufspace_daemonwakeup:
506 * Wakeup the daemon responsible for freeing clean bufs.
509 bufspace_daemonwakeup(void)
512 if (bufspace_request == 0) {
513 bufspace_request = 1;
514 wakeup(&bufspace_request);
522 * Adjust the reported bufspace for a KVA managed buffer, possibly
523 * waking any waiters.
526 bufspace_adjust(struct buf *bp, int bufsize)
531 KASSERT((bp->b_flags & B_MALLOC) == 0,
532 ("bufspace_adjust: malloc buf %p", bp));
533 diff = bufsize - bp->b_bufsize;
535 atomic_subtract_long(&bufspace, -diff);
538 space = atomic_fetchadd_long(&bufspace, diff);
539 /* Wake up the daemon on the transition. */
540 if (space < bufspacethresh && space + diff >= bufspacethresh)
541 bufspace_daemonwakeup();
543 bp->b_bufsize = bufsize;
549 * Reserve bufspace before calling allocbuf(). metadata has a
550 * different space limit than data.
553 bufspace_reserve(int size, bool metadata)
564 if (space + size > limit)
566 } while (atomic_cmpset_long(&bufspace, space, space + size) == 0);
568 /* Wake up the daemon on the transition. */
569 if (space < bufspacethresh && space + size >= bufspacethresh)
570 bufspace_daemonwakeup();
578 * Release reserved bufspace after bufspace_adjust() has consumed it.
581 bufspace_release(int size)
583 atomic_subtract_long(&bufspace, size);
590 * Wait for bufspace, acting as the buf daemon if a locked vnode is
591 * supplied. needsbuffer must be set in a safe fashion prior to
592 * polling for space. The operation must be re-tried on return.
595 bufspace_wait(struct vnode *vp, int gbflags, int slpflag, int slptimeo)
598 int error, fl, norunbuf;
600 if ((gbflags & GB_NOWAIT_BD) != 0)
605 while (needsbuffer != 0) {
606 if (vp != NULL && vp->v_type != VCHR &&
607 (td->td_pflags & TDP_BUFNEED) == 0) {
610 * getblk() is called with a vnode locked, and
611 * some majority of the dirty buffers may as
612 * well belong to the vnode. Flushing the
613 * buffers there would make a progress that
614 * cannot be achieved by the buf_daemon, that
615 * cannot lock the vnode.
617 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
618 (td->td_pflags & TDP_NORUNNINGBUF);
621 * Play bufdaemon. The getnewbuf() function
622 * may be called while the thread owns lock
623 * for another dirty buffer for the same
624 * vnode, which makes it impossible to use
625 * VOP_FSYNC() there, due to the buffer lock
628 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
629 fl = buf_flush(vp, flushbufqtarget);
630 td->td_pflags &= norunbuf;
634 if (needsbuffer == 0)
637 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
638 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
649 * buffer space management daemon. Tries to maintain some marginal
650 * amount of free buffer space so that requesting processes neither
651 * block nor work to reclaim buffers.
654 bufspace_daemon(void)
657 kproc_suspend_check(bufspacedaemonproc);
660 * Free buffers from the clean queue until we meet our
663 * Theory of operation: The buffer cache is most efficient
664 * when some free buffer headers and space are always
665 * available to getnewbuf(). This daemon attempts to prevent
666 * the excessive blocking and synchronization associated
667 * with shortfall. It goes through three phases according
670 * 1) The daemon wakes up voluntarily once per-second
671 * during idle periods when the counters are below
672 * the wakeup thresholds (bufspacethresh, lofreebuffers).
674 * 2) The daemon wakes up as we cross the thresholds
675 * ahead of any potential blocking. This may bounce
676 * slightly according to the rate of consumption and
679 * 3) The daemon and consumers are starved for working
680 * clean buffers. This is the 'bufspace' sleep below
681 * which will inefficiently trade bufs with bqrelse
682 * until we return to condition 2.
684 while (bufspace > lobufspace ||
685 numfreebuffers < hifreebuffers) {
686 if (buf_recycle(false) != 0) {
687 atomic_set_int(&needsbuffer, 1);
688 if (buf_recycle(false) != 0) {
691 rw_sleep(__DEVOLATILE(void *,
692 &needsbuffer), &nblock,
693 PRIBIO|PDROP, "bufspace",
703 * Re-check our limits under the exclusive nblock.
706 if (bufspace < bufspacethresh &&
707 numfreebuffers > lofreebuffers) {
708 bufspace_request = 0;
709 rw_sleep(&bufspace_request, &nblock, PRIBIO|PDROP,
716 static struct kproc_desc bufspace_kp = {
721 SYSINIT(bufspacedaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start,
727 * Adjust the reported bufspace for a malloc managed buffer, possibly
728 * waking any waiters.
731 bufmallocadjust(struct buf *bp, int bufsize)
735 KASSERT((bp->b_flags & B_MALLOC) != 0,
736 ("bufmallocadjust: non-malloc buf %p", bp));
737 diff = bufsize - bp->b_bufsize;
739 atomic_subtract_long(&bufmallocspace, -diff);
741 atomic_add_long(&bufmallocspace, diff);
742 bp->b_bufsize = bufsize;
748 * Wake up processes that are waiting on asynchronous writes to fall
749 * below lorunningspace.
755 mtx_lock(&rbreqlock);
758 wakeup(&runningbufreq);
760 mtx_unlock(&rbreqlock);
766 * Decrement the outstanding write count according.
769 runningbufwakeup(struct buf *bp)
773 bspace = bp->b_runningbufspace;
776 space = atomic_fetchadd_long(&runningbufspace, -bspace);
777 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
779 bp->b_runningbufspace = 0;
781 * Only acquire the lock and wakeup on the transition from exceeding
782 * the threshold to falling below it.
784 if (space < lorunningspace)
786 if (space - bspace > lorunningspace)
792 * waitrunningbufspace()
794 * runningbufspace is a measure of the amount of I/O currently
795 * running. This routine is used in async-write situations to
796 * prevent creating huge backups of pending writes to a device.
797 * Only asynchronous writes are governed by this function.
799 * This does NOT turn an async write into a sync write. It waits
800 * for earlier writes to complete and generally returns before the
801 * caller's write has reached the device.
804 waitrunningbufspace(void)
807 mtx_lock(&rbreqlock);
808 while (runningbufspace > hirunningspace) {
810 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
812 mtx_unlock(&rbreqlock);
817 * vfs_buf_test_cache:
819 * Called when a buffer is extended. This function clears the B_CACHE
820 * bit if the newly extended portion of the buffer does not contain
824 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
825 vm_offset_t size, vm_page_t m)
828 VM_OBJECT_ASSERT_LOCKED(m->object);
829 if (bp->b_flags & B_CACHE) {
830 int base = (foff + off) & PAGE_MASK;
831 if (vm_page_is_valid(m, base, size) == 0)
832 bp->b_flags &= ~B_CACHE;
836 /* Wake up the buffer daemon if necessary */
842 if (bd_request == 0) {
850 * bd_speedup - speedup the buffer cache flushing code
859 if (bd_speedupreq == 0 || bd_request == 0)
869 #define NSWBUF_MIN 16
873 #define TRANSIENT_DENOM 5
875 #define TRANSIENT_DENOM 10
879 * Calculating buffer cache scaling values and reserve space for buffer
880 * headers. This is called during low level kernel initialization and
881 * may be called more then once. We CANNOT write to the memory area
882 * being reserved at this time.
885 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
888 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
891 * physmem_est is in pages. Convert it to kilobytes (assumes
892 * PAGE_SIZE is >= 1K)
894 physmem_est = physmem_est * (PAGE_SIZE / 1024);
897 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
898 * For the first 64MB of ram nominally allocate sufficient buffers to
899 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
900 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
901 * the buffer cache we limit the eventual kva reservation to
904 * factor represents the 1/4 x ram conversion.
907 int factor = 4 * BKVASIZE / 1024;
910 if (physmem_est > 4096)
911 nbuf += min((physmem_est - 4096) / factor,
913 if (physmem_est > 65536)
914 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
915 32 * 1024 * 1024 / (factor * 5));
917 if (maxbcache && nbuf > maxbcache / BKVASIZE)
918 nbuf = maxbcache / BKVASIZE;
923 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
924 maxbuf = (LONG_MAX / 3) / BKVASIZE;
927 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
933 * Ideal allocation size for the transient bio submap is 10%
934 * of the maximal space buffer map. This roughly corresponds
935 * to the amount of the buffer mapped for typical UFS load.
937 * Clip the buffer map to reserve space for the transient
938 * BIOs, if its extent is bigger than 90% (80% on i386) of the
939 * maximum buffer map extent on the platform.
941 * The fall-back to the maxbuf in case of maxbcache unset,
942 * allows to not trim the buffer KVA for the architectures
943 * with ample KVA space.
945 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
946 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
947 buf_sz = (long)nbuf * BKVASIZE;
948 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
949 (TRANSIENT_DENOM - 1)) {
951 * There is more KVA than memory. Do not
952 * adjust buffer map size, and assign the rest
953 * of maxbuf to transient map.
955 biotmap_sz = maxbuf_sz - buf_sz;
958 * Buffer map spans all KVA we could afford on
959 * this platform. Give 10% (20% on i386) of
960 * the buffer map to the transient bio map.
962 biotmap_sz = buf_sz / TRANSIENT_DENOM;
963 buf_sz -= biotmap_sz;
965 if (biotmap_sz / INT_MAX > MAXPHYS)
966 bio_transient_maxcnt = INT_MAX;
968 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
970 * Artificially limit to 1024 simultaneous in-flight I/Os
971 * using the transient mapping.
973 if (bio_transient_maxcnt > 1024)
974 bio_transient_maxcnt = 1024;
976 nbuf = buf_sz / BKVASIZE;
980 * swbufs are used as temporary holders for I/O, such as paging I/O.
981 * We have no less then 16 and no more then 256.
983 nswbuf = min(nbuf / 4, 256);
984 TUNABLE_INT_FETCH("kern.nswbuf", &nswbuf);
985 if (nswbuf < NSWBUF_MIN)
989 * Reserve space for the buffer cache buffers
992 v = (caddr_t)(swbuf + nswbuf);
994 v = (caddr_t)(buf + nbuf);
999 /* Initialize the buffer subsystem. Called before use of any buffers. */
1006 CTASSERT(MAXBCACHEBUF >= MAXBSIZE);
1007 mtx_init(&bqlocks[QUEUE_DIRTY], "bufq dirty lock", NULL, MTX_DEF);
1008 mtx_init(&bqlocks[QUEUE_EMPTY], "bufq empty lock", NULL, MTX_DEF);
1009 for (i = QUEUE_CLEAN; i < QUEUE_CLEAN + CLEAN_QUEUES; i++)
1010 mtx_init(&bqlocks[i], "bufq clean lock", NULL, MTX_DEF);
1011 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1012 rw_init(&nblock, "needsbuffer lock");
1013 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1014 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1016 /* next, make a null set of free lists */
1017 for (i = 0; i < BUFFER_QUEUES; i++)
1018 TAILQ_INIT(&bufqueues[i]);
1020 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
1022 /* finally, initialize each buffer header and stick on empty q */
1023 for (i = 0; i < nbuf; i++) {
1025 bzero(bp, sizeof *bp);
1026 bp->b_flags = B_INVAL;
1027 bp->b_rcred = NOCRED;
1028 bp->b_wcred = NOCRED;
1029 bp->b_qindex = QUEUE_EMPTY;
1031 bp->b_data = bp->b_kvabase = unmapped_buf;
1032 LIST_INIT(&bp->b_dep);
1034 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
1036 bq_len[QUEUE_EMPTY]++;
1041 * maxbufspace is the absolute maximum amount of buffer space we are
1042 * allowed to reserve in KVM and in real terms. The absolute maximum
1043 * is nominally used by metadata. hibufspace is the nominal maximum
1044 * used by most other requests. The differential is required to
1045 * ensure that metadata deadlocks don't occur.
1047 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1048 * this may result in KVM fragmentation which is not handled optimally
1049 * by the system. XXX This is less true with vmem. We could use
1052 maxbufspace = (long)nbuf * BKVASIZE;
1053 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBCACHEBUF * 10);
1054 lobufspace = (hibufspace / 20) * 19; /* 95% */
1055 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1058 * Note: The 16 MiB upper limit for hirunningspace was chosen
1059 * arbitrarily and may need further tuning. It corresponds to
1060 * 128 outstanding write IO requests (if IO size is 128 KiB),
1061 * which fits with many RAID controllers' tagged queuing limits.
1062 * The lower 1 MiB limit is the historical upper limit for
1065 hirunningspace = lmax(lmin(roundup(hibufspace / 64, MAXBCACHEBUF),
1066 16 * 1024 * 1024), 1024 * 1024);
1067 lorunningspace = roundup((hirunningspace * 2) / 3, MAXBCACHEBUF);
1070 * Limit the amount of malloc memory since it is wired permanently into
1071 * the kernel space. Even though this is accounted for in the buffer
1072 * allocation, we don't want the malloced region to grow uncontrolled.
1073 * The malloc scheme improves memory utilization significantly on
1074 * average (small) directories.
1076 maxbufmallocspace = hibufspace / 20;
1079 * Reduce the chance of a deadlock occurring by limiting the number
1080 * of delayed-write dirty buffers we allow to stack up.
1082 hidirtybuffers = nbuf / 4 + 20;
1083 dirtybufthresh = hidirtybuffers * 9 / 10;
1084 numdirtybuffers = 0;
1086 * To support extreme low-memory systems, make sure hidirtybuffers
1087 * cannot eat up all available buffer space. This occurs when our
1088 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1089 * buffer space assuming BKVASIZE'd buffers.
1091 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1092 hidirtybuffers >>= 1;
1094 lodirtybuffers = hidirtybuffers / 2;
1097 * lofreebuffers should be sufficient to avoid stalling waiting on
1098 * buf headers under heavy utilization. The bufs in per-cpu caches
1099 * are counted as free but will be unavailable to threads executing
1102 * hifreebuffers is the free target for the bufspace daemon. This
1103 * should be set appropriately to limit work per-iteration.
1105 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1106 hifreebuffers = (3 * lofreebuffers) / 2;
1107 numfreebuffers = nbuf;
1109 /* Setup the kva and free list allocators. */
1110 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1111 buf_zone = uma_zcache_create("buf free cache", sizeof(struct buf),
1112 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1115 * Size the clean queue according to the amount of buffer space.
1116 * One queue per-256mb up to the max. More queues gives better
1117 * concurrency but less accurate LRU.
1119 clean_queues = MIN(howmany(maxbufspace, 256*1024*1024), CLEAN_QUEUES);
1125 vfs_buf_check_mapped(struct buf *bp)
1128 KASSERT(bp->b_kvabase != unmapped_buf,
1129 ("mapped buf: b_kvabase was not updated %p", bp));
1130 KASSERT(bp->b_data != unmapped_buf,
1131 ("mapped buf: b_data was not updated %p", bp));
1132 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1133 MAXPHYS, ("b_data + b_offset unmapped %p", bp));
1137 vfs_buf_check_unmapped(struct buf *bp)
1140 KASSERT(bp->b_data == unmapped_buf,
1141 ("unmapped buf: corrupted b_data %p", bp));
1144 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1145 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1147 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1148 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1152 isbufbusy(struct buf *bp)
1154 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1155 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1161 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1164 bufshutdown(int show_busybufs)
1166 static int first_buf_printf = 1;
1168 int iter, nbusy, pbusy;
1174 * Sync filesystems for shutdown
1176 wdog_kern_pat(WD_LASTVAL);
1177 sys_sync(curthread, NULL);
1180 * With soft updates, some buffers that are
1181 * written will be remarked as dirty until other
1182 * buffers are written.
1184 for (iter = pbusy = 0; iter < 20; iter++) {
1186 for (bp = &buf[nbuf]; --bp >= buf; )
1190 if (first_buf_printf)
1191 printf("All buffers synced.");
1194 if (first_buf_printf) {
1195 printf("Syncing disks, buffers remaining... ");
1196 first_buf_printf = 0;
1198 printf("%d ", nbusy);
1203 wdog_kern_pat(WD_LASTVAL);
1204 sys_sync(curthread, NULL);
1208 * Drop Giant and spin for a while to allow
1209 * interrupt threads to run.
1212 DELAY(50000 * iter);
1216 * Drop Giant and context switch several times to
1217 * allow interrupt threads to run.
1220 for (subiter = 0; subiter < 50 * iter; subiter++) {
1221 thread_lock(curthread);
1222 mi_switch(SW_VOL, NULL);
1223 thread_unlock(curthread);
1231 * Count only busy local buffers to prevent forcing
1232 * a fsck if we're just a client of a wedged NFS server
1235 for (bp = &buf[nbuf]; --bp >= buf; ) {
1236 if (isbufbusy(bp)) {
1238 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1239 if (bp->b_dev == NULL) {
1240 TAILQ_REMOVE(&mountlist,
1241 bp->b_vp->v_mount, mnt_list);
1246 if (show_busybufs > 0) {
1248 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1249 nbusy, bp, bp->b_vp, bp->b_flags,
1250 (intmax_t)bp->b_blkno,
1251 (intmax_t)bp->b_lblkno);
1252 BUF_LOCKPRINTINFO(bp);
1253 if (show_busybufs > 1)
1261 * Failed to sync all blocks. Indicate this and don't
1262 * unmount filesystems (thus forcing an fsck on reboot).
1264 printf("Giving up on %d buffers\n", nbusy);
1265 DELAY(5000000); /* 5 seconds */
1267 if (!first_buf_printf)
1268 printf("Final sync complete\n");
1270 * Unmount filesystems
1272 if (panicstr == NULL)
1276 DELAY(100000); /* wait for console output to finish */
1280 bpmap_qenter(struct buf *bp)
1283 BUF_CHECK_MAPPED(bp);
1286 * bp->b_data is relative to bp->b_offset, but
1287 * bp->b_offset may be offset into the first page.
1289 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1290 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1291 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1292 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1298 * Insert the buffer into the appropriate free list.
1301 binsfree(struct buf *bp, int qindex)
1303 struct mtx *olock, *nlock;
1305 if (qindex != QUEUE_EMPTY) {
1306 BUF_ASSERT_XLOCKED(bp);
1310 * Stick to the same clean queue for the lifetime of the buf to
1311 * limit locking below. Otherwise pick ont sequentially.
1313 if (qindex == QUEUE_CLEAN) {
1314 if (bqisclean(bp->b_qindex))
1315 qindex = bp->b_qindex;
1317 qindex = bqcleanq();
1321 * Handle delayed bremfree() processing.
1323 nlock = bqlock(qindex);
1324 if (bp->b_flags & B_REMFREE) {
1325 olock = bqlock(bp->b_qindex);
1328 if (olock != nlock) {
1335 if (bp->b_qindex != QUEUE_NONE)
1336 panic("binsfree: free buffer onto another queue???");
1338 bp->b_qindex = qindex;
1339 if (bp->b_flags & B_AGE)
1340 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1342 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1344 bq_len[bp->b_qindex]++;
1352 * Free a buffer to the buf zone once it no longer has valid contents.
1355 buf_free(struct buf *bp)
1358 if (bp->b_flags & B_REMFREE)
1360 if (bp->b_vflags & BV_BKGRDINPROG)
1361 panic("losing buffer 1");
1362 if (bp->b_rcred != NOCRED) {
1363 crfree(bp->b_rcred);
1364 bp->b_rcred = NOCRED;
1366 if (bp->b_wcred != NOCRED) {
1367 crfree(bp->b_wcred);
1368 bp->b_wcred = NOCRED;
1370 if (!LIST_EMPTY(&bp->b_dep))
1374 uma_zfree(buf_zone, bp);
1375 atomic_add_int(&numfreebuffers, 1);
1382 * Import bufs into the uma cache from the buf list. The system still
1383 * expects a static array of bufs and much of the synchronization
1384 * around bufs assumes type stable storage. As a result, UMA is used
1385 * only as a per-cpu cache of bufs still maintained on a global list.
1388 buf_import(void *arg, void **store, int cnt, int flags)
1393 mtx_lock(&bqlocks[QUEUE_EMPTY]);
1394 for (i = 0; i < cnt; i++) {
1395 bp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1401 mtx_unlock(&bqlocks[QUEUE_EMPTY]);
1409 * Release bufs from the uma cache back to the buffer queues.
1412 buf_release(void *arg, void **store, int cnt)
1416 for (i = 0; i < cnt; i++)
1417 binsfree(store[i], QUEUE_EMPTY);
1423 * Allocate an empty buffer header.
1430 bp = uma_zalloc(buf_zone, M_NOWAIT);
1432 bufspace_daemonwakeup();
1433 atomic_add_int(&numbufallocfails, 1);
1438 * Wake-up the bufspace daemon on transition.
1440 if (atomic_fetchadd_int(&numfreebuffers, -1) == lofreebuffers)
1441 bufspace_daemonwakeup();
1443 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1444 panic("getnewbuf_empty: Locked buf %p on free queue.", bp);
1446 KASSERT(bp->b_vp == NULL,
1447 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1448 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1449 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1450 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1451 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1452 KASSERT(bp->b_npages == 0,
1453 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1454 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1455 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1462 bp->b_blkno = bp->b_lblkno = 0;
1463 bp->b_offset = NOOFFSET;
1469 bp->b_dirtyoff = bp->b_dirtyend = 0;
1470 bp->b_bufobj = NULL;
1471 bp->b_data = bp->b_kvabase = unmapped_buf;
1472 bp->b_fsprivate1 = NULL;
1473 bp->b_fsprivate2 = NULL;
1474 bp->b_fsprivate3 = NULL;
1475 LIST_INIT(&bp->b_dep);
1483 * Free a buffer from the given bufqueue. kva controls whether the
1484 * freed buf must own some kva resources. This is used for
1488 buf_qrecycle(int qindex, bool kva)
1490 struct buf *bp, *nbp;
1493 atomic_add_int(&bufdefragcnt, 1);
1495 mtx_lock(&bqlocks[qindex]);
1496 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1499 * Run scan, possibly freeing data and/or kva mappings on the fly
1502 while ((bp = nbp) != NULL) {
1504 * Calculate next bp (we can only use it if we do not
1505 * release the bqlock).
1507 nbp = TAILQ_NEXT(bp, b_freelist);
1510 * If we are defragging then we need a buffer with
1511 * some kva to reclaim.
1513 if (kva && bp->b_kvasize == 0)
1516 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1520 * Skip buffers with background writes in progress.
1522 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1527 KASSERT(bp->b_qindex == qindex,
1528 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1530 * NOTE: nbp is now entirely invalid. We can only restart
1531 * the scan from this point on.
1534 mtx_unlock(&bqlocks[qindex]);
1537 * Requeue the background write buffer with error and
1540 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1542 mtx_lock(&bqlocks[qindex]);
1543 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1546 bp->b_flags |= B_INVAL;
1550 mtx_unlock(&bqlocks[qindex]);
1558 * Iterate through all clean queues until we find a buf to recycle or
1559 * exhaust the search.
1562 buf_recycle(bool kva)
1564 int qindex, first_qindex;
1566 qindex = first_qindex = bqcleanq();
1568 if (buf_qrecycle(qindex, kva) == 0)
1570 if (++qindex == QUEUE_CLEAN + clean_queues)
1571 qindex = QUEUE_CLEAN;
1572 } while (qindex != first_qindex);
1580 * Scan the clean queues looking for a buffer to recycle. needsbuffer
1581 * is set on failure so that the caller may optionally bufspace_wait()
1582 * in a race-free fashion.
1585 buf_scan(bool defrag)
1590 * To avoid heavy synchronization and wakeup races we set
1591 * needsbuffer and re-poll before failing. This ensures that
1592 * no frees can be missed between an unsuccessful poll and
1593 * going to sleep in a synchronized fashion.
1595 if ((error = buf_recycle(defrag)) != 0) {
1596 atomic_set_int(&needsbuffer, 1);
1597 bufspace_daemonwakeup();
1598 error = buf_recycle(defrag);
1601 atomic_add_int(&getnewbufrestarts, 1);
1608 * Mark the buffer for removal from the appropriate free list.
1612 bremfree(struct buf *bp)
1615 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1616 KASSERT((bp->b_flags & B_REMFREE) == 0,
1617 ("bremfree: buffer %p already marked for delayed removal.", bp));
1618 KASSERT(bp->b_qindex != QUEUE_NONE,
1619 ("bremfree: buffer %p not on a queue.", bp));
1620 BUF_ASSERT_XLOCKED(bp);
1622 bp->b_flags |= B_REMFREE;
1628 * Force an immediate removal from a free list. Used only in nfs when
1629 * it abuses the b_freelist pointer.
1632 bremfreef(struct buf *bp)
1636 qlock = bqlock(bp->b_qindex);
1645 * Removes a buffer from the free list, must be called with the
1646 * correct qlock held.
1649 bremfreel(struct buf *bp)
1652 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1653 bp, bp->b_vp, bp->b_flags);
1654 KASSERT(bp->b_qindex != QUEUE_NONE,
1655 ("bremfreel: buffer %p not on a queue.", bp));
1656 if (bp->b_qindex != QUEUE_EMPTY) {
1657 BUF_ASSERT_XLOCKED(bp);
1659 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1661 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1663 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1665 bq_len[bp->b_qindex]--;
1667 bp->b_qindex = QUEUE_NONE;
1668 bp->b_flags &= ~B_REMFREE;
1674 * Free the kva allocation for a buffer.
1678 bufkva_free(struct buf *bp)
1682 if (bp->b_kvasize == 0) {
1683 KASSERT(bp->b_kvabase == unmapped_buf &&
1684 bp->b_data == unmapped_buf,
1685 ("Leaked KVA space on %p", bp));
1686 } else if (buf_mapped(bp))
1687 BUF_CHECK_MAPPED(bp);
1689 BUF_CHECK_UNMAPPED(bp);
1691 if (bp->b_kvasize == 0)
1694 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
1695 atomic_subtract_long(&bufkvaspace, bp->b_kvasize);
1696 atomic_add_int(&buffreekvacnt, 1);
1697 bp->b_data = bp->b_kvabase = unmapped_buf;
1704 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
1707 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
1712 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
1713 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
1718 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
1721 * Buffer map is too fragmented. Request the caller
1722 * to defragment the map.
1726 bp->b_kvabase = (caddr_t)addr;
1727 bp->b_kvasize = maxsize;
1728 atomic_add_long(&bufkvaspace, bp->b_kvasize);
1729 if ((gbflags & GB_UNMAPPED) != 0) {
1730 bp->b_data = unmapped_buf;
1731 BUF_CHECK_UNMAPPED(bp);
1733 bp->b_data = bp->b_kvabase;
1734 BUF_CHECK_MAPPED(bp);
1742 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
1743 * callback that fires to avoid returning failure.
1746 bufkva_reclaim(vmem_t *vmem, int flags)
1750 for (i = 0; i < 5; i++)
1751 if (buf_scan(true) != 0)
1758 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1759 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1760 * the buffer is valid and we do not have to do anything.
1763 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1764 int cnt, struct ucred * cred)
1769 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1770 if (inmem(vp, *rablkno))
1772 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1774 if ((rabp->b_flags & B_CACHE) == 0) {
1775 if (!TD_IS_IDLETHREAD(curthread)) {
1779 racct_add_buf(curproc, rabp, 0);
1780 PROC_UNLOCK(curproc);
1783 curthread->td_ru.ru_inblock++;
1785 rabp->b_flags |= B_ASYNC;
1786 rabp->b_flags &= ~B_INVAL;
1787 rabp->b_ioflags &= ~BIO_ERROR;
1788 rabp->b_iocmd = BIO_READ;
1789 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1790 rabp->b_rcred = crhold(cred);
1791 vfs_busy_pages(rabp, 0);
1793 rabp->b_iooffset = dbtob(rabp->b_blkno);
1802 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1804 * Get a buffer with the specified data. Look in the cache first. We
1805 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1806 * is set, the buffer is valid and we do not have to do anything, see
1807 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1809 * Always return a NULL buffer pointer (in bpp) when returning an error.
1812 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1813 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1816 int rv = 0, readwait = 0;
1818 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1820 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1822 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1826 /* if not found in cache, do some I/O */
1827 if ((bp->b_flags & B_CACHE) == 0) {
1828 if (!TD_IS_IDLETHREAD(curthread)) {
1832 racct_add_buf(curproc, bp, 0);
1833 PROC_UNLOCK(curproc);
1836 curthread->td_ru.ru_inblock++;
1838 bp->b_iocmd = BIO_READ;
1839 bp->b_flags &= ~B_INVAL;
1840 bp->b_ioflags &= ~BIO_ERROR;
1841 if (bp->b_rcred == NOCRED && cred != NOCRED)
1842 bp->b_rcred = crhold(cred);
1843 vfs_busy_pages(bp, 0);
1844 bp->b_iooffset = dbtob(bp->b_blkno);
1849 breada(vp, rablkno, rabsize, cnt, cred);
1862 * Write, release buffer on completion. (Done by iodone
1863 * if async). Do not bother writing anything if the buffer
1866 * Note that we set B_CACHE here, indicating that buffer is
1867 * fully valid and thus cacheable. This is true even of NFS
1868 * now so we set it generally. This could be set either here
1869 * or in biodone() since the I/O is synchronous. We put it
1873 bufwrite(struct buf *bp)
1880 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1881 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
1882 bp->b_flags |= B_INVAL | B_RELBUF;
1883 bp->b_flags &= ~B_CACHE;
1887 if (bp->b_flags & B_INVAL) {
1892 if (bp->b_flags & B_BARRIER)
1895 oldflags = bp->b_flags;
1897 BUF_ASSERT_HELD(bp);
1899 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1900 ("FFS background buffer should not get here %p", bp));
1904 vp_md = vp->v_vflag & VV_MD;
1909 * Mark the buffer clean. Increment the bufobj write count
1910 * before bundirty() call, to prevent other thread from seeing
1911 * empty dirty list and zero counter for writes in progress,
1912 * falsely indicating that the bufobj is clean.
1914 bufobj_wref(bp->b_bufobj);
1917 bp->b_flags &= ~B_DONE;
1918 bp->b_ioflags &= ~BIO_ERROR;
1919 bp->b_flags |= B_CACHE;
1920 bp->b_iocmd = BIO_WRITE;
1922 vfs_busy_pages(bp, 1);
1925 * Normal bwrites pipeline writes
1927 bp->b_runningbufspace = bp->b_bufsize;
1928 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1930 if (!TD_IS_IDLETHREAD(curthread)) {
1934 racct_add_buf(curproc, bp, 1);
1935 PROC_UNLOCK(curproc);
1938 curthread->td_ru.ru_oublock++;
1940 if (oldflags & B_ASYNC)
1942 bp->b_iooffset = dbtob(bp->b_blkno);
1943 buf_track(bp, __func__);
1946 if ((oldflags & B_ASYNC) == 0) {
1947 int rtval = bufwait(bp);
1950 } else if (space > hirunningspace) {
1952 * don't allow the async write to saturate the I/O
1953 * system. We will not deadlock here because
1954 * we are blocking waiting for I/O that is already in-progress
1955 * to complete. We do not block here if it is the update
1956 * or syncer daemon trying to clean up as that can lead
1959 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
1960 waitrunningbufspace();
1967 bufbdflush(struct bufobj *bo, struct buf *bp)
1971 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
1972 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
1974 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
1977 * Try to find a buffer to flush.
1979 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
1980 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
1982 LK_EXCLUSIVE | LK_NOWAIT, NULL))
1985 panic("bdwrite: found ourselves");
1987 /* Don't countdeps with the bo lock held. */
1988 if (buf_countdeps(nbp, 0)) {
1993 if (nbp->b_flags & B_CLUSTEROK) {
1994 vfs_bio_awrite(nbp);
1999 dirtybufferflushes++;
2008 * Delayed write. (Buffer is marked dirty). Do not bother writing
2009 * anything if the buffer is marked invalid.
2011 * Note that since the buffer must be completely valid, we can safely
2012 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2013 * biodone() in order to prevent getblk from writing the buffer
2014 * out synchronously.
2017 bdwrite(struct buf *bp)
2019 struct thread *td = curthread;
2023 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2024 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2025 KASSERT((bp->b_flags & B_BARRIER) == 0,
2026 ("Barrier request in delayed write %p", bp));
2027 BUF_ASSERT_HELD(bp);
2029 if (bp->b_flags & B_INVAL) {
2035 * If we have too many dirty buffers, don't create any more.
2036 * If we are wildly over our limit, then force a complete
2037 * cleanup. Otherwise, just keep the situation from getting
2038 * out of control. Note that we have to avoid a recursive
2039 * disaster and not try to clean up after our own cleanup!
2043 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2044 td->td_pflags |= TDP_INBDFLUSH;
2046 td->td_pflags &= ~TDP_INBDFLUSH;
2052 * Set B_CACHE, indicating that the buffer is fully valid. This is
2053 * true even of NFS now.
2055 bp->b_flags |= B_CACHE;
2058 * This bmap keeps the system from needing to do the bmap later,
2059 * perhaps when the system is attempting to do a sync. Since it
2060 * is likely that the indirect block -- or whatever other datastructure
2061 * that the filesystem needs is still in memory now, it is a good
2062 * thing to do this. Note also, that if the pageout daemon is
2063 * requesting a sync -- there might not be enough memory to do
2064 * the bmap then... So, this is important to do.
2066 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2067 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2070 buf_track(bp, __func__);
2073 * Set the *dirty* buffer range based upon the VM system dirty
2076 * Mark the buffer pages as clean. We need to do this here to
2077 * satisfy the vnode_pager and the pageout daemon, so that it
2078 * thinks that the pages have been "cleaned". Note that since
2079 * the pages are in a delayed write buffer -- the VFS layer
2080 * "will" see that the pages get written out on the next sync,
2081 * or perhaps the cluster will be completed.
2083 vfs_clean_pages_dirty_buf(bp);
2087 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2088 * due to the softdep code.
2095 * Turn buffer into delayed write request. We must clear BIO_READ and
2096 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2097 * itself to properly update it in the dirty/clean lists. We mark it
2098 * B_DONE to ensure that any asynchronization of the buffer properly
2099 * clears B_DONE ( else a panic will occur later ).
2101 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2102 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2103 * should only be called if the buffer is known-good.
2105 * Since the buffer is not on a queue, we do not update the numfreebuffers
2108 * The buffer must be on QUEUE_NONE.
2111 bdirty(struct buf *bp)
2114 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2115 bp, bp->b_vp, bp->b_flags);
2116 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2117 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2118 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2119 BUF_ASSERT_HELD(bp);
2120 bp->b_flags &= ~(B_RELBUF);
2121 bp->b_iocmd = BIO_WRITE;
2123 if ((bp->b_flags & B_DELWRI) == 0) {
2124 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2133 * Clear B_DELWRI for buffer.
2135 * Since the buffer is not on a queue, we do not update the numfreebuffers
2138 * The buffer must be on QUEUE_NONE.
2142 bundirty(struct buf *bp)
2145 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", 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 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2149 BUF_ASSERT_HELD(bp);
2151 if (bp->b_flags & B_DELWRI) {
2152 bp->b_flags &= ~B_DELWRI;
2157 * Since it is now being written, we can clear its deferred write flag.
2159 bp->b_flags &= ~B_DEFERRED;
2165 * Asynchronous write. Start output on a buffer, but do not wait for
2166 * it to complete. The buffer is released when the output completes.
2168 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2169 * B_INVAL buffers. Not us.
2172 bawrite(struct buf *bp)
2175 bp->b_flags |= B_ASYNC;
2182 * Asynchronous barrier write. Start output on a buffer, but do not
2183 * wait for it to complete. Place a write barrier after this write so
2184 * that this buffer and all buffers written before it are committed to
2185 * the disk before any buffers written after this write are committed
2186 * to the disk. The buffer is released when the output completes.
2189 babarrierwrite(struct buf *bp)
2192 bp->b_flags |= B_ASYNC | B_BARRIER;
2199 * Synchronous barrier write. Start output on a buffer and wait for
2200 * it to complete. Place a write barrier after this write so that
2201 * this buffer and all buffers written before it are committed to
2202 * the disk before any buffers written after this write are committed
2203 * to the disk. The buffer is released when the output completes.
2206 bbarrierwrite(struct buf *bp)
2209 bp->b_flags |= B_BARRIER;
2210 return (bwrite(bp));
2216 * Called prior to the locking of any vnodes when we are expecting to
2217 * write. We do not want to starve the buffer cache with too many
2218 * dirty buffers so we block here. By blocking prior to the locking
2219 * of any vnodes we attempt to avoid the situation where a locked vnode
2220 * prevents the various system daemons from flushing related buffers.
2226 if (numdirtybuffers >= hidirtybuffers) {
2227 mtx_lock(&bdirtylock);
2228 while (numdirtybuffers >= hidirtybuffers) {
2230 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2233 mtx_unlock(&bdirtylock);
2238 * Return true if we have too many dirty buffers.
2241 buf_dirty_count_severe(void)
2244 return(numdirtybuffers >= hidirtybuffers);
2250 * Release a busy buffer and, if requested, free its resources. The
2251 * buffer will be stashed in the appropriate bufqueue[] allowing it
2252 * to be accessed later as a cache entity or reused for other purposes.
2255 brelse(struct buf *bp)
2260 * Many functions erroneously call brelse with a NULL bp under rare
2261 * error conditions. Simply return when called with a NULL bp.
2265 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2266 bp, bp->b_vp, bp->b_flags);
2267 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2268 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2269 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2270 ("brelse: non-VMIO buffer marked NOREUSE"));
2272 if (BUF_LOCKRECURSED(bp)) {
2274 * Do not process, in particular, do not handle the
2275 * B_INVAL/B_RELBUF and do not release to free list.
2281 if (bp->b_flags & B_MANAGED) {
2286 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2287 BO_LOCK(bp->b_bufobj);
2288 bp->b_vflags &= ~BV_BKGRDERR;
2289 BO_UNLOCK(bp->b_bufobj);
2292 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2293 !(bp->b_flags & B_INVAL)) {
2295 * Failed write, redirty. Must clear BIO_ERROR to prevent
2296 * pages from being scrapped.
2298 bp->b_ioflags &= ~BIO_ERROR;
2300 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2301 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2303 * Either a failed read I/O or we were asked to free or not
2306 bp->b_flags |= B_INVAL;
2307 if (!LIST_EMPTY(&bp->b_dep))
2309 if (bp->b_flags & B_DELWRI)
2311 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2312 if ((bp->b_flags & B_VMIO) == 0) {
2320 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2321 * is called with B_DELWRI set, the underlying pages may wind up
2322 * getting freed causing a previous write (bdwrite()) to get 'lost'
2323 * because pages associated with a B_DELWRI bp are marked clean.
2325 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2326 * if B_DELWRI is set.
2328 if (bp->b_flags & B_DELWRI)
2329 bp->b_flags &= ~B_RELBUF;
2332 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2333 * constituted, not even NFS buffers now. Two flags effect this. If
2334 * B_INVAL, the struct buf is invalidated but the VM object is kept
2335 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2337 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2338 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2339 * buffer is also B_INVAL because it hits the re-dirtying code above.
2341 * Normally we can do this whether a buffer is B_DELWRI or not. If
2342 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2343 * the commit state and we cannot afford to lose the buffer. If the
2344 * buffer has a background write in progress, we need to keep it
2345 * around to prevent it from being reconstituted and starting a second
2348 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2349 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2350 !(bp->b_vp->v_mount != NULL &&
2351 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2352 !vn_isdisk(bp->b_vp, NULL) && (bp->b_flags & B_DELWRI))) {
2353 vfs_vmio_invalidate(bp);
2357 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2358 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2360 bp->b_flags &= ~B_NOREUSE;
2361 if (bp->b_vp != NULL)
2366 * If the buffer has junk contents signal it and eventually
2367 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2370 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2371 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2372 bp->b_flags |= B_INVAL;
2373 if (bp->b_flags & B_INVAL) {
2374 if (bp->b_flags & B_DELWRI)
2380 buf_track(bp, __func__);
2382 /* buffers with no memory */
2383 if (bp->b_bufsize == 0) {
2387 /* buffers with junk contents */
2388 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2389 (bp->b_ioflags & BIO_ERROR)) {
2390 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2391 if (bp->b_vflags & BV_BKGRDINPROG)
2392 panic("losing buffer 2");
2393 qindex = QUEUE_CLEAN;
2394 bp->b_flags |= B_AGE;
2395 /* remaining buffers */
2396 } else if (bp->b_flags & B_DELWRI)
2397 qindex = QUEUE_DIRTY;
2399 qindex = QUEUE_CLEAN;
2401 binsfree(bp, qindex);
2403 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
2404 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2405 panic("brelse: not dirty");
2408 if (qindex == QUEUE_CLEAN)
2413 * Release a buffer back to the appropriate queue but do not try to free
2414 * it. The buffer is expected to be used again soon.
2416 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2417 * biodone() to requeue an async I/O on completion. It is also used when
2418 * known good buffers need to be requeued but we think we may need the data
2421 * XXX we should be able to leave the B_RELBUF hint set on completion.
2424 bqrelse(struct buf *bp)
2428 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2429 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2430 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2432 qindex = QUEUE_NONE;
2433 if (BUF_LOCKRECURSED(bp)) {
2434 /* do not release to free list */
2438 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2440 if (bp->b_flags & B_MANAGED) {
2441 if (bp->b_flags & B_REMFREE)
2446 /* buffers with stale but valid contents */
2447 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2448 BV_BKGRDERR)) == BV_BKGRDERR) {
2449 BO_LOCK(bp->b_bufobj);
2450 bp->b_vflags &= ~BV_BKGRDERR;
2451 BO_UNLOCK(bp->b_bufobj);
2452 qindex = QUEUE_DIRTY;
2454 if ((bp->b_flags & B_DELWRI) == 0 &&
2455 (bp->b_xflags & BX_VNDIRTY))
2456 panic("bqrelse: not dirty");
2457 if ((bp->b_flags & B_NOREUSE) != 0) {
2461 qindex = QUEUE_CLEAN;
2463 binsfree(bp, qindex);
2466 buf_track(bp, __func__);
2469 if (qindex == QUEUE_CLEAN)
2474 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2475 * restore bogus pages.
2478 vfs_vmio_iodone(struct buf *bp)
2484 int bogus, i, iosize;
2486 obj = bp->b_bufobj->bo_object;
2487 KASSERT(obj->paging_in_progress >= bp->b_npages,
2488 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2489 obj->paging_in_progress, bp->b_npages));
2492 KASSERT(vp->v_holdcnt > 0,
2493 ("vfs_vmio_iodone: vnode %p has zero hold count", vp));
2494 KASSERT(vp->v_object != NULL,
2495 ("vfs_vmio_iodone: vnode %p has no vm_object", vp));
2497 foff = bp->b_offset;
2498 KASSERT(bp->b_offset != NOOFFSET,
2499 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2502 iosize = bp->b_bcount - bp->b_resid;
2503 VM_OBJECT_WLOCK(obj);
2504 for (i = 0; i < bp->b_npages; i++) {
2507 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2512 * cleanup bogus pages, restoring the originals
2515 if (m == bogus_page) {
2517 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2519 panic("biodone: page disappeared!");
2521 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2523 * In the write case, the valid and clean bits are
2524 * already changed correctly ( see bdwrite() ), so we
2525 * only need to do this here in the read case.
2527 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2528 resid)) == 0, ("vfs_vmio_iodone: page %p "
2529 "has unexpected dirty bits", m));
2530 vfs_page_set_valid(bp, foff, m);
2532 KASSERT(OFF_TO_IDX(foff) == m->pindex,
2533 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
2534 (intmax_t)foff, (uintmax_t)m->pindex));
2537 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2540 vm_object_pip_wakeupn(obj, bp->b_npages);
2541 VM_OBJECT_WUNLOCK(obj);
2542 if (bogus && buf_mapped(bp)) {
2543 BUF_CHECK_MAPPED(bp);
2544 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2545 bp->b_pages, bp->b_npages);
2550 * Unwire a page held by a buf and place it on the appropriate vm queue.
2553 vfs_vmio_unwire(struct buf *bp, vm_page_t m)
2558 if (vm_page_unwire(m, PQ_NONE)) {
2560 * Determine if the page should be freed before adding
2561 * it to the inactive queue.
2563 if (m->valid == 0) {
2564 freed = !vm_page_busied(m);
2567 } else if ((bp->b_flags & B_DIRECT) != 0)
2568 freed = vm_page_try_to_free(m);
2573 * If the page is unlikely to be reused, let the
2574 * VM know. Otherwise, maintain LRU page
2575 * ordering and put the page at the tail of the
2578 if ((bp->b_flags & B_NOREUSE) != 0)
2579 vm_page_deactivate_noreuse(m);
2581 vm_page_deactivate(m);
2588 * Perform page invalidation when a buffer is released. The fully invalid
2589 * pages will be reclaimed later in vfs_vmio_truncate().
2592 vfs_vmio_invalidate(struct buf *bp)
2596 int i, resid, poffset, presid;
2598 if (buf_mapped(bp)) {
2599 BUF_CHECK_MAPPED(bp);
2600 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
2602 BUF_CHECK_UNMAPPED(bp);
2604 * Get the base offset and length of the buffer. Note that
2605 * in the VMIO case if the buffer block size is not
2606 * page-aligned then b_data pointer may not be page-aligned.
2607 * But our b_pages[] array *IS* page aligned.
2609 * block sizes less then DEV_BSIZE (usually 512) are not
2610 * supported due to the page granularity bits (m->valid,
2611 * m->dirty, etc...).
2613 * See man buf(9) for more information
2615 obj = bp->b_bufobj->bo_object;
2616 resid = bp->b_bufsize;
2617 poffset = bp->b_offset & PAGE_MASK;
2618 VM_OBJECT_WLOCK(obj);
2619 for (i = 0; i < bp->b_npages; i++) {
2621 if (m == bogus_page)
2622 panic("vfs_vmio_invalidate: Unexpected bogus page.");
2623 bp->b_pages[i] = NULL;
2625 presid = resid > (PAGE_SIZE - poffset) ?
2626 (PAGE_SIZE - poffset) : resid;
2627 KASSERT(presid >= 0, ("brelse: extra page"));
2628 while (vm_page_xbusied(m)) {
2630 VM_OBJECT_WUNLOCK(obj);
2631 vm_page_busy_sleep(m, "mbncsh", true);
2632 VM_OBJECT_WLOCK(obj);
2634 if (pmap_page_wired_mappings(m) == 0)
2635 vm_page_set_invalid(m, poffset, presid);
2636 vfs_vmio_unwire(bp, m);
2640 VM_OBJECT_WUNLOCK(obj);
2645 * Page-granular truncation of an existing VMIO buffer.
2648 vfs_vmio_truncate(struct buf *bp, int desiredpages)
2654 if (bp->b_npages == desiredpages)
2657 if (buf_mapped(bp)) {
2658 BUF_CHECK_MAPPED(bp);
2659 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
2660 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
2662 BUF_CHECK_UNMAPPED(bp);
2663 obj = bp->b_bufobj->bo_object;
2665 VM_OBJECT_WLOCK(obj);
2666 for (i = desiredpages; i < bp->b_npages; i++) {
2668 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
2669 bp->b_pages[i] = NULL;
2670 vfs_vmio_unwire(bp, m);
2673 VM_OBJECT_WUNLOCK(obj);
2674 bp->b_npages = desiredpages;
2678 * Byte granular extension of VMIO buffers.
2681 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
2684 * We are growing the buffer, possibly in a
2685 * byte-granular fashion.
2693 * Step 1, bring in the VM pages from the object, allocating
2694 * them if necessary. We must clear B_CACHE if these pages
2695 * are not valid for the range covered by the buffer.
2697 obj = bp->b_bufobj->bo_object;
2698 VM_OBJECT_WLOCK(obj);
2699 while (bp->b_npages < desiredpages) {
2701 * We must allocate system pages since blocking
2702 * here could interfere with paging I/O, no
2703 * matter which process we are.
2705 * Only exclusive busy can be tested here.
2706 * Blocking on shared busy might lead to
2707 * deadlocks once allocbuf() is called after
2708 * pages are vfs_busy_pages().
2710 m = vm_page_grab(obj, OFF_TO_IDX(bp->b_offset) + bp->b_npages,
2711 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM |
2712 VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY |
2713 VM_ALLOC_COUNT(desiredpages - bp->b_npages));
2715 bp->b_flags &= ~B_CACHE;
2716 bp->b_pages[bp->b_npages] = m;
2721 * Step 2. We've loaded the pages into the buffer,
2722 * we have to figure out if we can still have B_CACHE
2723 * set. Note that B_CACHE is set according to the
2724 * byte-granular range ( bcount and size ), not the
2725 * aligned range ( newbsize ).
2727 * The VM test is against m->valid, which is DEV_BSIZE
2728 * aligned. Needless to say, the validity of the data
2729 * needs to also be DEV_BSIZE aligned. Note that this
2730 * fails with NFS if the server or some other client
2731 * extends the file's EOF. If our buffer is resized,
2732 * B_CACHE may remain set! XXX
2734 toff = bp->b_bcount;
2735 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2736 while ((bp->b_flags & B_CACHE) && toff < size) {
2739 if (tinc > (size - toff))
2741 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
2742 m = bp->b_pages[pi];
2743 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
2747 VM_OBJECT_WUNLOCK(obj);
2750 * Step 3, fixup the KVA pmap.
2755 BUF_CHECK_UNMAPPED(bp);
2759 * Check to see if a block at a particular lbn is available for a clustered
2763 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
2770 /* If the buf isn't in core skip it */
2771 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
2774 /* If the buf is busy we don't want to wait for it */
2775 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2778 /* Only cluster with valid clusterable delayed write buffers */
2779 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
2780 (B_DELWRI | B_CLUSTEROK))
2783 if (bpa->b_bufsize != size)
2787 * Check to see if it is in the expected place on disk and that the
2788 * block has been mapped.
2790 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
2800 * Implement clustered async writes for clearing out B_DELWRI buffers.
2801 * This is much better then the old way of writing only one buffer at
2802 * a time. Note that we may not be presented with the buffers in the
2803 * correct order, so we search for the cluster in both directions.
2806 vfs_bio_awrite(struct buf *bp)
2811 daddr_t lblkno = bp->b_lblkno;
2812 struct vnode *vp = bp->b_vp;
2820 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
2822 * right now we support clustered writing only to regular files. If
2823 * we find a clusterable block we could be in the middle of a cluster
2824 * rather then at the beginning.
2826 if ((vp->v_type == VREG) &&
2827 (vp->v_mount != 0) && /* Only on nodes that have the size info */
2828 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2830 size = vp->v_mount->mnt_stat.f_iosize;
2831 maxcl = MAXPHYS / size;
2834 for (i = 1; i < maxcl; i++)
2835 if (vfs_bio_clcheck(vp, size, lblkno + i,
2836 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2839 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2840 if (vfs_bio_clcheck(vp, size, lblkno - j,
2841 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2847 * this is a possible cluster write
2851 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2857 bp->b_flags |= B_ASYNC;
2859 * default (old) behavior, writing out only one block
2861 * XXX returns b_bufsize instead of b_bcount for nwritten?
2863 nwritten = bp->b_bufsize;
2872 * Allocate KVA for an empty buf header according to gbflags.
2875 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
2878 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
2880 * In order to keep fragmentation sane we only allocate kva
2881 * in BKVASIZE chunks. XXX with vmem we can do page size.
2883 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2885 if (maxsize != bp->b_kvasize &&
2886 bufkva_alloc(bp, maxsize, gbflags))
2895 * Find and initialize a new buffer header, freeing up existing buffers
2896 * in the bufqueues as necessary. The new buffer is returned locked.
2899 * We have insufficient buffer headers
2900 * We have insufficient buffer space
2901 * buffer_arena is too fragmented ( space reservation fails )
2902 * If we have to flush dirty buffers ( but we try to avoid this )
2904 * The caller is responsible for releasing the reserved bufspace after
2905 * allocbuf() is called.
2908 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
2911 bool metadata, reserved;
2914 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2915 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2916 if (!unmapped_buf_allowed)
2917 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2919 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2924 atomic_add_int(&getnewbufcalls, 1);
2927 if (reserved == false &&
2928 bufspace_reserve(maxsize, metadata) != 0)
2931 if ((bp = buf_alloc()) == NULL)
2933 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
2936 } while(buf_scan(false) == 0);
2939 atomic_subtract_long(&bufspace, maxsize);
2941 bp->b_flags |= B_INVAL;
2944 bufspace_wait(vp, gbflags, slpflag, slptimeo);
2952 * buffer flushing daemon. Buffers are normally flushed by the
2953 * update daemon but if it cannot keep up this process starts to
2954 * take the load in an attempt to prevent getnewbuf() from blocking.
2956 static struct kproc_desc buf_kp = {
2961 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
2964 buf_flush(struct vnode *vp, int target)
2968 flushed = flushbufqueues(vp, target, 0);
2971 * Could not find any buffers without rollback
2972 * dependencies, so just write the first one
2973 * in the hopes of eventually making progress.
2975 if (vp != NULL && target > 2)
2977 flushbufqueues(vp, target, 1);
2988 * This process needs to be suspended prior to shutdown sync.
2990 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
2994 * This process is allowed to take the buffer cache to the limit
2996 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3000 mtx_unlock(&bdlock);
3002 kproc_suspend_check(bufdaemonproc);
3003 lodirty = lodirtybuffers;
3004 if (bd_speedupreq) {
3005 lodirty = numdirtybuffers / 2;
3009 * Do the flush. Limit the amount of in-transit I/O we
3010 * allow to build up, otherwise we would completely saturate
3013 while (numdirtybuffers > lodirty) {
3014 if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
3016 kern_yield(PRI_USER);
3020 * Only clear bd_request if we have reached our low water
3021 * mark. The buf_daemon normally waits 1 second and
3022 * then incrementally flushes any dirty buffers that have
3023 * built up, within reason.
3025 * If we were unable to hit our low water mark and couldn't
3026 * find any flushable buffers, we sleep for a short period
3027 * to avoid endless loops on unlockable buffers.
3030 if (numdirtybuffers <= lodirtybuffers) {
3032 * We reached our low water mark, reset the
3033 * request and sleep until we are needed again.
3034 * The sleep is just so the suspend code works.
3038 * Do an extra wakeup in case dirty threshold
3039 * changed via sysctl and the explicit transition
3040 * out of shortfall was missed.
3043 if (runningbufspace <= lorunningspace)
3045 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3048 * We couldn't find any flushable dirty buffers but
3049 * still have too many dirty buffers, we
3050 * have to sleep and try again. (rare)
3052 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3060 * Try to flush a buffer in the dirty queue. We must be careful to
3061 * free up B_INVAL buffers instead of write them, which NFS is
3062 * particularly sensitive to.
3064 static int flushwithdeps = 0;
3065 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
3066 0, "Number of buffers flushed with dependecies that require rollbacks");
3069 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
3071 struct buf *sentinel;
3082 queue = QUEUE_DIRTY;
3084 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3085 sentinel->b_qindex = QUEUE_SENTINEL;
3086 mtx_lock(&bqlocks[queue]);
3087 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
3088 mtx_unlock(&bqlocks[queue]);
3089 while (flushed != target) {
3091 mtx_lock(&bqlocks[queue]);
3092 bp = TAILQ_NEXT(sentinel, b_freelist);
3094 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3095 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
3098 mtx_unlock(&bqlocks[queue]);
3102 * Skip sentinels inserted by other invocations of the
3103 * flushbufqueues(), taking care to not reorder them.
3105 * Only flush the buffers that belong to the
3106 * vnode locked by the curthread.
3108 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3110 mtx_unlock(&bqlocks[queue]);
3113 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3114 mtx_unlock(&bqlocks[queue]);
3119 * BKGRDINPROG can only be set with the buf and bufobj
3120 * locks both held. We tolerate a race to clear it here.
3122 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3123 (bp->b_flags & B_DELWRI) == 0) {
3127 if (bp->b_flags & B_INVAL) {
3134 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3135 if (flushdeps == 0) {
3143 * We must hold the lock on a vnode before writing
3144 * one of its buffers. Otherwise we may confuse, or
3145 * in the case of a snapshot vnode, deadlock the
3148 * The lock order here is the reverse of the normal
3149 * of vnode followed by buf lock. This is ok because
3150 * the NOWAIT will prevent deadlock.
3153 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3159 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3161 ASSERT_VOP_LOCKED(vp, "getbuf");
3163 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3164 vn_lock(vp, LK_TRYUPGRADE);
3167 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3168 bp, bp->b_vp, bp->b_flags);
3169 if (curproc == bufdaemonproc) {
3176 vn_finished_write(mp);
3179 flushwithdeps += hasdeps;
3183 * Sleeping on runningbufspace while holding
3184 * vnode lock leads to deadlock.
3186 if (curproc == bufdaemonproc &&
3187 runningbufspace > hirunningspace)
3188 waitrunningbufspace();
3191 vn_finished_write(mp);
3194 mtx_lock(&bqlocks[queue]);
3195 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3196 mtx_unlock(&bqlocks[queue]);
3197 free(sentinel, M_TEMP);
3202 * Check to see if a block is currently memory resident.
3205 incore(struct bufobj *bo, daddr_t blkno)
3210 bp = gbincore(bo, blkno);
3216 * Returns true if no I/O is needed to access the
3217 * associated VM object. This is like incore except
3218 * it also hunts around in the VM system for the data.
3222 inmem(struct vnode * vp, daddr_t blkno)
3225 vm_offset_t toff, tinc, size;
3229 ASSERT_VOP_LOCKED(vp, "inmem");
3231 if (incore(&vp->v_bufobj, blkno))
3233 if (vp->v_mount == NULL)
3240 if (size > vp->v_mount->mnt_stat.f_iosize)
3241 size = vp->v_mount->mnt_stat.f_iosize;
3242 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3244 VM_OBJECT_RLOCK(obj);
3245 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3246 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
3250 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3251 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3252 if (vm_page_is_valid(m,
3253 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
3256 VM_OBJECT_RUNLOCK(obj);
3260 VM_OBJECT_RUNLOCK(obj);
3265 * Set the dirty range for a buffer based on the status of the dirty
3266 * bits in the pages comprising the buffer. The range is limited
3267 * to the size of the buffer.
3269 * Tell the VM system that the pages associated with this buffer
3270 * are clean. This is used for delayed writes where the data is
3271 * going to go to disk eventually without additional VM intevention.
3273 * Note that while we only really need to clean through to b_bcount, we
3274 * just go ahead and clean through to b_bufsize.
3277 vfs_clean_pages_dirty_buf(struct buf *bp)
3279 vm_ooffset_t foff, noff, eoff;
3283 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3286 foff = bp->b_offset;
3287 KASSERT(bp->b_offset != NOOFFSET,
3288 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3290 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3291 vfs_drain_busy_pages(bp);
3292 vfs_setdirty_locked_object(bp);
3293 for (i = 0; i < bp->b_npages; i++) {
3294 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3296 if (eoff > bp->b_offset + bp->b_bufsize)
3297 eoff = bp->b_offset + bp->b_bufsize;
3299 vfs_page_set_validclean(bp, foff, m);
3300 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3303 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3307 vfs_setdirty_locked_object(struct buf *bp)
3312 object = bp->b_bufobj->bo_object;
3313 VM_OBJECT_ASSERT_WLOCKED(object);
3316 * We qualify the scan for modified pages on whether the
3317 * object has been flushed yet.
3319 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
3320 vm_offset_t boffset;
3321 vm_offset_t eoffset;
3324 * test the pages to see if they have been modified directly
3325 * by users through the VM system.
3327 for (i = 0; i < bp->b_npages; i++)
3328 vm_page_test_dirty(bp->b_pages[i]);
3331 * Calculate the encompassing dirty range, boffset and eoffset,
3332 * (eoffset - boffset) bytes.
3335 for (i = 0; i < bp->b_npages; i++) {
3336 if (bp->b_pages[i]->dirty)
3339 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3341 for (i = bp->b_npages - 1; i >= 0; --i) {
3342 if (bp->b_pages[i]->dirty) {
3346 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3349 * Fit it to the buffer.
3352 if (eoffset > bp->b_bcount)
3353 eoffset = bp->b_bcount;
3356 * If we have a good dirty range, merge with the existing
3360 if (boffset < eoffset) {
3361 if (bp->b_dirtyoff > boffset)
3362 bp->b_dirtyoff = boffset;
3363 if (bp->b_dirtyend < eoffset)
3364 bp->b_dirtyend = eoffset;
3370 * Allocate the KVA mapping for an existing buffer.
3371 * If an unmapped buffer is provided but a mapped buffer is requested, take
3372 * also care to properly setup mappings between pages and KVA.
3375 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3377 int bsize, maxsize, need_mapping, need_kva;
3380 need_mapping = bp->b_data == unmapped_buf &&
3381 (gbflags & GB_UNMAPPED) == 0;
3382 need_kva = bp->b_kvabase == unmapped_buf &&
3383 bp->b_data == unmapped_buf &&
3384 (gbflags & GB_KVAALLOC) != 0;
3385 if (!need_mapping && !need_kva)
3388 BUF_CHECK_UNMAPPED(bp);
3390 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3392 * Buffer is not mapped, but the KVA was already
3393 * reserved at the time of the instantiation. Use the
3400 * Calculate the amount of the address space we would reserve
3401 * if the buffer was mapped.
3403 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3404 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3405 offset = blkno * bsize;
3406 maxsize = size + (offset & PAGE_MASK);
3407 maxsize = imax(maxsize, bsize);
3409 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3410 if ((gbflags & GB_NOWAIT_BD) != 0) {
3412 * XXXKIB: defragmentation cannot
3413 * succeed, not sure what else to do.
3415 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3417 atomic_add_int(&mappingrestarts, 1);
3418 bufspace_wait(bp->b_vp, gbflags, 0, 0);
3422 /* b_offset is handled by bpmap_qenter. */
3423 bp->b_data = bp->b_kvabase;
3424 BUF_CHECK_MAPPED(bp);
3432 * Get a block given a specified block and offset into a file/device.
3433 * The buffers B_DONE bit will be cleared on return, making it almost
3434 * ready for an I/O initiation. B_INVAL may or may not be set on
3435 * return. The caller should clear B_INVAL prior to initiating a
3438 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3439 * an existing buffer.
3441 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3442 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3443 * and then cleared based on the backing VM. If the previous buffer is
3444 * non-0-sized but invalid, B_CACHE will be cleared.
3446 * If getblk() must create a new buffer, the new buffer is returned with
3447 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3448 * case it is returned with B_INVAL clear and B_CACHE set based on the
3451 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3452 * B_CACHE bit is clear.
3454 * What this means, basically, is that the caller should use B_CACHE to
3455 * determine whether the buffer is fully valid or not and should clear
3456 * B_INVAL prior to issuing a read. If the caller intends to validate
3457 * the buffer by loading its data area with something, the caller needs
3458 * to clear B_INVAL. If the caller does this without issuing an I/O,
3459 * the caller should set B_CACHE ( as an optimization ), else the caller
3460 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3461 * a write attempt or if it was a successful read. If the caller
3462 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3463 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3466 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3471 int bsize, error, maxsize, vmio;
3474 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3475 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3476 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3477 ASSERT_VOP_LOCKED(vp, "getblk");
3478 if (size > MAXBCACHEBUF)
3479 panic("getblk: size(%d) > MAXBCACHEBUF(%d)\n", size,
3481 if (!unmapped_buf_allowed)
3482 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3487 bp = gbincore(bo, blkno);
3491 * Buffer is in-core. If the buffer is not busy nor managed,
3492 * it must be on a queue.
3494 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3496 if (flags & GB_LOCK_NOWAIT)
3497 lockflags |= LK_NOWAIT;
3499 error = BUF_TIMELOCK(bp, lockflags,
3500 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3503 * If we slept and got the lock we have to restart in case
3504 * the buffer changed identities.
3506 if (error == ENOLCK)
3508 /* We timed out or were interrupted. */
3511 /* If recursed, assume caller knows the rules. */
3512 else if (BUF_LOCKRECURSED(bp))
3516 * The buffer is locked. B_CACHE is cleared if the buffer is
3517 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3518 * and for a VMIO buffer B_CACHE is adjusted according to the
3521 if (bp->b_flags & B_INVAL)
3522 bp->b_flags &= ~B_CACHE;
3523 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3524 bp->b_flags |= B_CACHE;
3525 if (bp->b_flags & B_MANAGED)
3526 MPASS(bp->b_qindex == QUEUE_NONE);
3531 * check for size inconsistencies for non-VMIO case.
3533 if (bp->b_bcount != size) {
3534 if ((bp->b_flags & B_VMIO) == 0 ||
3535 (size > bp->b_kvasize)) {
3536 if (bp->b_flags & B_DELWRI) {
3537 bp->b_flags |= B_NOCACHE;
3540 if (LIST_EMPTY(&bp->b_dep)) {
3541 bp->b_flags |= B_RELBUF;
3544 bp->b_flags |= B_NOCACHE;
3553 * Handle the case of unmapped buffer which should
3554 * become mapped, or the buffer for which KVA
3555 * reservation is requested.
3557 bp_unmapped_get_kva(bp, blkno, size, flags);
3560 * If the size is inconsistent in the VMIO case, we can resize
3561 * the buffer. This might lead to B_CACHE getting set or
3562 * cleared. If the size has not changed, B_CACHE remains
3563 * unchanged from its previous state.
3567 KASSERT(bp->b_offset != NOOFFSET,
3568 ("getblk: no buffer offset"));
3571 * A buffer with B_DELWRI set and B_CACHE clear must
3572 * be committed before we can return the buffer in
3573 * order to prevent the caller from issuing a read
3574 * ( due to B_CACHE not being set ) and overwriting
3577 * Most callers, including NFS and FFS, need this to
3578 * operate properly either because they assume they
3579 * can issue a read if B_CACHE is not set, or because
3580 * ( for example ) an uncached B_DELWRI might loop due
3581 * to softupdates re-dirtying the buffer. In the latter
3582 * case, B_CACHE is set after the first write completes,
3583 * preventing further loops.
3584 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3585 * above while extending the buffer, we cannot allow the
3586 * buffer to remain with B_CACHE set after the write
3587 * completes or it will represent a corrupt state. To
3588 * deal with this we set B_NOCACHE to scrap the buffer
3591 * We might be able to do something fancy, like setting
3592 * B_CACHE in bwrite() except if B_DELWRI is already set,
3593 * so the below call doesn't set B_CACHE, but that gets real
3594 * confusing. This is much easier.
3597 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3598 bp->b_flags |= B_NOCACHE;
3602 bp->b_flags &= ~B_DONE;
3605 * Buffer is not in-core, create new buffer. The buffer
3606 * returned by getnewbuf() is locked. Note that the returned
3607 * buffer is also considered valid (not marked B_INVAL).
3611 * If the user does not want us to create the buffer, bail out
3614 if (flags & GB_NOCREAT)
3616 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3619 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3620 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3621 offset = blkno * bsize;
3622 vmio = vp->v_object != NULL;
3624 maxsize = size + (offset & PAGE_MASK);
3627 /* Do not allow non-VMIO notmapped buffers. */
3628 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3630 maxsize = imax(maxsize, bsize);
3632 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
3634 if (slpflag || slptimeo)
3637 * XXX This is here until the sleep path is diagnosed
3638 * enough to work under very low memory conditions.
3640 * There's an issue on low memory, 4BSD+non-preempt
3641 * systems (eg MIPS routers with 32MB RAM) where buffer
3642 * exhaustion occurs without sleeping for buffer
3643 * reclaimation. This just sticks in a loop and
3644 * constantly attempts to allocate a buffer, which
3645 * hits exhaustion and tries to wakeup bufdaemon.
3646 * This never happens because we never yield.
3648 * The real solution is to identify and fix these cases
3649 * so we aren't effectively busy-waiting in a loop
3650 * until the reclaimation path has cycles to run.
3652 kern_yield(PRI_USER);
3657 * This code is used to make sure that a buffer is not
3658 * created while the getnewbuf routine is blocked.
3659 * This can be a problem whether the vnode is locked or not.
3660 * If the buffer is created out from under us, we have to
3661 * throw away the one we just created.
3663 * Note: this must occur before we associate the buffer
3664 * with the vp especially considering limitations in
3665 * the splay tree implementation when dealing with duplicate
3669 if (gbincore(bo, blkno)) {
3671 bp->b_flags |= B_INVAL;
3673 bufspace_release(maxsize);
3678 * Insert the buffer into the hash, so that it can
3679 * be found by incore.
3681 bp->b_blkno = bp->b_lblkno = blkno;
3682 bp->b_offset = offset;
3687 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3688 * buffer size starts out as 0, B_CACHE will be set by
3689 * allocbuf() for the VMIO case prior to it testing the
3690 * backing store for validity.
3694 bp->b_flags |= B_VMIO;
3695 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3696 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3697 bp, vp->v_object, bp->b_bufobj->bo_object));
3699 bp->b_flags &= ~B_VMIO;
3700 KASSERT(bp->b_bufobj->bo_object == NULL,
3701 ("ARGH! has b_bufobj->bo_object %p %p\n",
3702 bp, bp->b_bufobj->bo_object));
3703 BUF_CHECK_MAPPED(bp);
3707 bufspace_release(maxsize);
3708 bp->b_flags &= ~B_DONE;
3710 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3711 BUF_ASSERT_HELD(bp);
3713 buf_track(bp, __func__);
3714 KASSERT(bp->b_bufobj == bo,
3715 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3720 * Get an empty, disassociated buffer of given size. The buffer is initially
3724 geteblk(int size, int flags)
3729 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3730 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
3731 if ((flags & GB_NOWAIT_BD) &&
3732 (curthread->td_pflags & TDP_BUFNEED) != 0)
3736 bufspace_release(maxsize);
3737 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3738 BUF_ASSERT_HELD(bp);
3743 * Truncate the backing store for a non-vmio buffer.
3746 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
3749 if (bp->b_flags & B_MALLOC) {
3751 * malloced buffers are not shrunk
3753 if (newbsize == 0) {
3754 bufmallocadjust(bp, 0);
3755 free(bp->b_data, M_BIOBUF);
3756 bp->b_data = bp->b_kvabase;
3757 bp->b_flags &= ~B_MALLOC;
3761 vm_hold_free_pages(bp, newbsize);
3762 bufspace_adjust(bp, newbsize);
3766 * Extend the backing for a non-VMIO buffer.
3769 vfs_nonvmio_extend(struct buf *bp, int newbsize)
3775 * We only use malloced memory on the first allocation.
3776 * and revert to page-allocated memory when the buffer
3779 * There is a potential smp race here that could lead
3780 * to bufmallocspace slightly passing the max. It
3781 * is probably extremely rare and not worth worrying
3784 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
3785 bufmallocspace < maxbufmallocspace) {
3786 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
3787 bp->b_flags |= B_MALLOC;
3788 bufmallocadjust(bp, newbsize);
3793 * If the buffer is growing on its other-than-first
3794 * allocation then we revert to the page-allocation
3799 if (bp->b_flags & B_MALLOC) {
3800 origbuf = bp->b_data;
3801 origbufsize = bp->b_bufsize;
3802 bp->b_data = bp->b_kvabase;
3803 bufmallocadjust(bp, 0);
3804 bp->b_flags &= ~B_MALLOC;
3805 newbsize = round_page(newbsize);
3807 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
3808 (vm_offset_t) bp->b_data + newbsize);
3809 if (origbuf != NULL) {
3810 bcopy(origbuf, bp->b_data, origbufsize);
3811 free(origbuf, M_BIOBUF);
3813 bufspace_adjust(bp, newbsize);
3817 * This code constitutes the buffer memory from either anonymous system
3818 * memory (in the case of non-VMIO operations) or from an associated
3819 * VM object (in the case of VMIO operations). This code is able to
3820 * resize a buffer up or down.
3822 * Note that this code is tricky, and has many complications to resolve
3823 * deadlock or inconsistent data situations. Tread lightly!!!
3824 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3825 * the caller. Calling this code willy nilly can result in the loss of data.
3827 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3828 * B_CACHE for the non-VMIO case.
3831 allocbuf(struct buf *bp, int size)
3835 BUF_ASSERT_HELD(bp);
3837 if (bp->b_bcount == size)
3840 if (bp->b_kvasize != 0 && bp->b_kvasize < size)
3841 panic("allocbuf: buffer too small");
3843 newbsize = roundup2(size, DEV_BSIZE);
3844 if ((bp->b_flags & B_VMIO) == 0) {
3845 if ((bp->b_flags & B_MALLOC) == 0)
3846 newbsize = round_page(newbsize);
3848 * Just get anonymous memory from the kernel. Don't
3849 * mess with B_CACHE.
3851 if (newbsize < bp->b_bufsize)
3852 vfs_nonvmio_truncate(bp, newbsize);
3853 else if (newbsize > bp->b_bufsize)
3854 vfs_nonvmio_extend(bp, newbsize);
3858 desiredpages = (size == 0) ? 0 :
3859 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3861 if (bp->b_flags & B_MALLOC)
3862 panic("allocbuf: VMIO buffer can't be malloced");
3864 * Set B_CACHE initially if buffer is 0 length or will become
3867 if (size == 0 || bp->b_bufsize == 0)
3868 bp->b_flags |= B_CACHE;
3870 if (newbsize < bp->b_bufsize)
3871 vfs_vmio_truncate(bp, desiredpages);
3872 /* XXX This looks as if it should be newbsize > b_bufsize */
3873 else if (size > bp->b_bcount)
3874 vfs_vmio_extend(bp, desiredpages, size);
3875 bufspace_adjust(bp, newbsize);
3877 bp->b_bcount = size; /* requested buffer size. */
3881 extern int inflight_transient_maps;
3884 biodone(struct bio *bp)
3887 void (*done)(struct bio *);
3888 vm_offset_t start, end;
3890 biotrack(bp, __func__);
3891 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3892 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3893 bp->bio_flags |= BIO_UNMAPPED;
3894 start = trunc_page((vm_offset_t)bp->bio_data);
3895 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3896 bp->bio_data = unmapped_buf;
3897 pmap_qremove(start, OFF_TO_IDX(end - start));
3898 vmem_free(transient_arena, start, end - start);
3899 atomic_add_int(&inflight_transient_maps, -1);
3901 done = bp->bio_done;
3903 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3905 bp->bio_flags |= BIO_DONE;
3913 * Wait for a BIO to finish.
3916 biowait(struct bio *bp, const char *wchan)
3920 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3922 while ((bp->bio_flags & BIO_DONE) == 0)
3923 msleep(bp, mtxp, PRIBIO, wchan, 0);
3925 if (bp->bio_error != 0)
3926 return (bp->bio_error);
3927 if (!(bp->bio_flags & BIO_ERROR))
3933 biofinish(struct bio *bp, struct devstat *stat, int error)
3937 bp->bio_error = error;
3938 bp->bio_flags |= BIO_ERROR;
3941 devstat_end_transaction_bio(stat, bp);
3945 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
3947 biotrack_buf(struct bio *bp, const char *location)
3950 buf_track(bp->bio_track_bp, location);
3957 * Wait for buffer I/O completion, returning error status. The buffer
3958 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
3959 * error and cleared.
3962 bufwait(struct buf *bp)
3964 if (bp->b_iocmd == BIO_READ)
3965 bwait(bp, PRIBIO, "biord");
3967 bwait(bp, PRIBIO, "biowr");
3968 if (bp->b_flags & B_EINTR) {
3969 bp->b_flags &= ~B_EINTR;
3972 if (bp->b_ioflags & BIO_ERROR) {
3973 return (bp->b_error ? bp->b_error : EIO);
3982 * Finish I/O on a buffer, optionally calling a completion function.
3983 * This is usually called from an interrupt so process blocking is
3986 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3987 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3988 * assuming B_INVAL is clear.
3990 * For the VMIO case, we set B_CACHE if the op was a read and no
3991 * read error occurred, or if the op was a write. B_CACHE is never
3992 * set if the buffer is invalid or otherwise uncacheable.
3994 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3995 * initiator to leave B_INVAL set to brelse the buffer out of existence
3996 * in the biodone routine.
3999 bufdone(struct buf *bp)
4001 struct bufobj *dropobj;
4002 void (*biodone)(struct buf *);
4004 buf_track(bp, __func__);
4005 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4008 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4009 BUF_ASSERT_HELD(bp);
4011 runningbufwakeup(bp);
4012 if (bp->b_iocmd == BIO_WRITE)
4013 dropobj = bp->b_bufobj;
4014 /* call optional completion function if requested */
4015 if (bp->b_iodone != NULL) {
4016 biodone = bp->b_iodone;
4017 bp->b_iodone = NULL;
4020 bufobj_wdrop(dropobj);
4027 bufobj_wdrop(dropobj);
4031 bufdone_finish(struct buf *bp)
4033 BUF_ASSERT_HELD(bp);
4035 if (!LIST_EMPTY(&bp->b_dep))
4038 if (bp->b_flags & B_VMIO) {
4040 * Set B_CACHE if the op was a normal read and no error
4041 * occurred. B_CACHE is set for writes in the b*write()
4044 if (bp->b_iocmd == BIO_READ &&
4045 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4046 !(bp->b_ioflags & BIO_ERROR))
4047 bp->b_flags |= B_CACHE;
4048 vfs_vmio_iodone(bp);
4052 * For asynchronous completions, release the buffer now. The brelse
4053 * will do a wakeup there if necessary - so no need to do a wakeup
4054 * here in the async case. The sync case always needs to do a wakeup.
4056 if (bp->b_flags & B_ASYNC) {
4057 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4058 (bp->b_ioflags & BIO_ERROR))
4067 * This routine is called in lieu of iodone in the case of
4068 * incomplete I/O. This keeps the busy status for pages
4072 vfs_unbusy_pages(struct buf *bp)
4078 runningbufwakeup(bp);
4079 if (!(bp->b_flags & B_VMIO))
4082 obj = bp->b_bufobj->bo_object;
4083 VM_OBJECT_WLOCK(obj);
4084 for (i = 0; i < bp->b_npages; i++) {
4086 if (m == bogus_page) {
4087 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4089 panic("vfs_unbusy_pages: page missing\n");
4091 if (buf_mapped(bp)) {
4092 BUF_CHECK_MAPPED(bp);
4093 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4094 bp->b_pages, bp->b_npages);
4096 BUF_CHECK_UNMAPPED(bp);
4100 vm_object_pip_wakeupn(obj, bp->b_npages);
4101 VM_OBJECT_WUNLOCK(obj);
4105 * vfs_page_set_valid:
4107 * Set the valid bits in a page based on the supplied offset. The
4108 * range is restricted to the buffer's size.
4110 * This routine is typically called after a read completes.
4113 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4118 * Compute the end offset, eoff, such that [off, eoff) does not span a
4119 * page boundary and eoff is not greater than the end of the buffer.
4120 * The end of the buffer, in this case, is our file EOF, not the
4121 * allocation size of the buffer.
4123 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4124 if (eoff > bp->b_offset + bp->b_bcount)
4125 eoff = bp->b_offset + bp->b_bcount;
4128 * Set valid range. This is typically the entire buffer and thus the
4132 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4136 * vfs_page_set_validclean:
4138 * Set the valid bits and clear the dirty bits in a page based on the
4139 * supplied offset. The range is restricted to the buffer's size.
4142 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4144 vm_ooffset_t soff, eoff;
4147 * Start and end offsets in buffer. eoff - soff may not cross a
4148 * page boundary or cross the end of the buffer. The end of the
4149 * buffer, in this case, is our file EOF, not the allocation size
4153 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4154 if (eoff > bp->b_offset + bp->b_bcount)
4155 eoff = bp->b_offset + bp->b_bcount;
4158 * Set valid range. This is typically the entire buffer and thus the
4162 vm_page_set_validclean(
4164 (vm_offset_t) (soff & PAGE_MASK),
4165 (vm_offset_t) (eoff - soff)
4171 * Ensure that all buffer pages are not exclusive busied. If any page is
4172 * exclusive busy, drain it.
4175 vfs_drain_busy_pages(struct buf *bp)
4180 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4182 for (i = 0; i < bp->b_npages; i++) {
4184 if (vm_page_xbusied(m)) {
4185 for (; last_busied < i; last_busied++)
4186 vm_page_sbusy(bp->b_pages[last_busied]);
4187 while (vm_page_xbusied(m)) {
4189 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4190 vm_page_busy_sleep(m, "vbpage", true);
4191 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4195 for (i = 0; i < last_busied; i++)
4196 vm_page_sunbusy(bp->b_pages[i]);
4200 * This routine is called before a device strategy routine.
4201 * It is used to tell the VM system that paging I/O is in
4202 * progress, and treat the pages associated with the buffer
4203 * almost as being exclusive busy. Also the object paging_in_progress
4204 * flag is handled to make sure that the object doesn't become
4207 * Since I/O has not been initiated yet, certain buffer flags
4208 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4209 * and should be ignored.
4212 vfs_busy_pages(struct buf *bp, int clear_modify)
4219 if (!(bp->b_flags & B_VMIO))
4222 obj = bp->b_bufobj->bo_object;
4223 foff = bp->b_offset;
4224 KASSERT(bp->b_offset != NOOFFSET,
4225 ("vfs_busy_pages: no buffer offset"));
4226 VM_OBJECT_WLOCK(obj);
4227 vfs_drain_busy_pages(bp);
4228 if (bp->b_bufsize != 0)
4229 vfs_setdirty_locked_object(bp);
4231 for (i = 0; i < bp->b_npages; i++) {
4234 if ((bp->b_flags & B_CLUSTER) == 0) {
4235 vm_object_pip_add(obj, 1);
4239 * When readying a buffer for a read ( i.e
4240 * clear_modify == 0 ), it is important to do
4241 * bogus_page replacement for valid pages in
4242 * partially instantiated buffers. Partially
4243 * instantiated buffers can, in turn, occur when
4244 * reconstituting a buffer from its VM backing store
4245 * base. We only have to do this if B_CACHE is
4246 * clear ( which causes the I/O to occur in the
4247 * first place ). The replacement prevents the read
4248 * I/O from overwriting potentially dirty VM-backed
4249 * pages. XXX bogus page replacement is, uh, bogus.
4250 * It may not work properly with small-block devices.
4251 * We need to find a better way.
4254 pmap_remove_write(m);
4255 vfs_page_set_validclean(bp, foff, m);
4256 } else if (m->valid == VM_PAGE_BITS_ALL &&
4257 (bp->b_flags & B_CACHE) == 0) {
4258 bp->b_pages[i] = bogus_page;
4261 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4263 VM_OBJECT_WUNLOCK(obj);
4264 if (bogus && buf_mapped(bp)) {
4265 BUF_CHECK_MAPPED(bp);
4266 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4267 bp->b_pages, bp->b_npages);
4272 * vfs_bio_set_valid:
4274 * Set the range within the buffer to valid. The range is
4275 * relative to the beginning of the buffer, b_offset. Note that
4276 * b_offset itself may be offset from the beginning of the first
4280 vfs_bio_set_valid(struct buf *bp, int base, int size)
4285 if (!(bp->b_flags & B_VMIO))
4289 * Fixup base to be relative to beginning of first page.
4290 * Set initial n to be the maximum number of bytes in the
4291 * first page that can be validated.
4293 base += (bp->b_offset & PAGE_MASK);
4294 n = PAGE_SIZE - (base & PAGE_MASK);
4296 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4297 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4301 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4306 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4312 * If the specified buffer is a non-VMIO buffer, clear the entire
4313 * buffer. If the specified buffer is a VMIO buffer, clear and
4314 * validate only the previously invalid portions of the buffer.
4315 * This routine essentially fakes an I/O, so we need to clear
4316 * BIO_ERROR and B_INVAL.
4318 * Note that while we only theoretically need to clear through b_bcount,
4319 * we go ahead and clear through b_bufsize.
4322 vfs_bio_clrbuf(struct buf *bp)
4324 int i, j, mask, sa, ea, slide;
4326 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4330 bp->b_flags &= ~B_INVAL;
4331 bp->b_ioflags &= ~BIO_ERROR;
4332 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4333 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4334 (bp->b_offset & PAGE_MASK) == 0) {
4335 if (bp->b_pages[0] == bogus_page)
4337 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4338 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4339 if ((bp->b_pages[0]->valid & mask) == mask)
4341 if ((bp->b_pages[0]->valid & mask) == 0) {
4342 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4343 bp->b_pages[0]->valid |= mask;
4347 sa = bp->b_offset & PAGE_MASK;
4349 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4350 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4351 ea = slide & PAGE_MASK;
4354 if (bp->b_pages[i] == bogus_page)
4357 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4358 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4359 if ((bp->b_pages[i]->valid & mask) == mask)
4361 if ((bp->b_pages[i]->valid & mask) == 0)
4362 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4364 for (; sa < ea; sa += DEV_BSIZE, j++) {
4365 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4366 pmap_zero_page_area(bp->b_pages[i],
4371 bp->b_pages[i]->valid |= mask;
4374 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4379 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4384 if (buf_mapped(bp)) {
4385 BUF_CHECK_MAPPED(bp);
4386 bzero(bp->b_data + base, size);
4388 BUF_CHECK_UNMAPPED(bp);
4389 n = PAGE_SIZE - (base & PAGE_MASK);
4390 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4394 pmap_zero_page_area(m, base & PAGE_MASK, n);
4403 * Update buffer flags based on I/O request parameters, optionally releasing the
4404 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM,
4405 * where they may be placed on a page queue (VMIO) or freed immediately (direct
4406 * I/O). Otherwise the buffer is released to the cache.
4409 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4412 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4413 ("buf %p non-VMIO noreuse", bp));
4415 if ((ioflag & IO_DIRECT) != 0)
4416 bp->b_flags |= B_DIRECT;
4417 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4418 bp->b_flags |= B_RELBUF;
4419 if ((ioflag & IO_NOREUSE) != 0)
4420 bp->b_flags |= B_NOREUSE;
4428 vfs_bio_brelse(struct buf *bp, int ioflag)
4431 b_io_dismiss(bp, ioflag, true);
4435 vfs_bio_set_flags(struct buf *bp, int ioflag)
4438 b_io_dismiss(bp, ioflag, false);
4442 * vm_hold_load_pages and vm_hold_free_pages get pages into
4443 * a buffers address space. The pages are anonymous and are
4444 * not associated with a file object.
4447 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4453 BUF_CHECK_MAPPED(bp);
4455 to = round_page(to);
4456 from = round_page(from);
4457 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4459 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4462 * note: must allocate system pages since blocking here
4463 * could interfere with paging I/O, no matter which
4466 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4467 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT));
4472 pmap_qenter(pg, &p, 1);
4473 bp->b_pages[index] = p;
4475 bp->b_npages = index;
4478 /* Return pages associated with this buf to the vm system */
4480 vm_hold_free_pages(struct buf *bp, int newbsize)
4484 int index, newnpages;
4486 BUF_CHECK_MAPPED(bp);
4488 from = round_page((vm_offset_t)bp->b_data + newbsize);
4489 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4490 if (bp->b_npages > newnpages)
4491 pmap_qremove(from, bp->b_npages - newnpages);
4492 for (index = newnpages; index < bp->b_npages; index++) {
4493 p = bp->b_pages[index];
4494 bp->b_pages[index] = NULL;
4495 if (vm_page_sbusied(p))
4496 printf("vm_hold_free_pages: blkno: %jd, lblkno: %jd\n",
4497 (intmax_t)bp->b_blkno, (intmax_t)bp->b_lblkno);
4500 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
4502 bp->b_npages = newnpages;
4506 * Map an IO request into kernel virtual address space.
4508 * All requests are (re)mapped into kernel VA space.
4509 * Notice that we use b_bufsize for the size of the buffer
4510 * to be mapped. b_bcount might be modified by the driver.
4512 * Note that even if the caller determines that the address space should
4513 * be valid, a race or a smaller-file mapped into a larger space may
4514 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4515 * check the return value.
4517 * This function only works with pager buffers.
4520 vmapbuf(struct buf *bp, int mapbuf)
4525 if (bp->b_bufsize < 0)
4527 prot = VM_PROT_READ;
4528 if (bp->b_iocmd == BIO_READ)
4529 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4530 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4531 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4532 btoc(MAXPHYS))) < 0)
4534 bp->b_npages = pidx;
4535 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4536 if (mapbuf || !unmapped_buf_allowed) {
4537 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
4538 bp->b_data = bp->b_kvabase + bp->b_offset;
4540 bp->b_data = unmapped_buf;
4545 * Free the io map PTEs associated with this IO operation.
4546 * We also invalidate the TLB entries and restore the original b_addr.
4548 * This function only works with pager buffers.
4551 vunmapbuf(struct buf *bp)
4555 npages = bp->b_npages;
4557 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4558 vm_page_unhold_pages(bp->b_pages, npages);
4560 bp->b_data = unmapped_buf;
4564 bdone(struct buf *bp)
4568 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4570 bp->b_flags |= B_DONE;
4576 bwait(struct buf *bp, u_char pri, const char *wchan)
4580 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4582 while ((bp->b_flags & B_DONE) == 0)
4583 msleep(bp, mtxp, pri, wchan, 0);
4588 bufsync(struct bufobj *bo, int waitfor)
4591 return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
4595 bufstrategy(struct bufobj *bo, struct buf *bp)
4601 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4602 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4603 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4604 i = VOP_STRATEGY(vp, bp);
4605 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4609 bufobj_wrefl(struct bufobj *bo)
4612 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4613 ASSERT_BO_WLOCKED(bo);
4618 bufobj_wref(struct bufobj *bo)
4621 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4628 bufobj_wdrop(struct bufobj *bo)
4631 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4633 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4634 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4635 bo->bo_flag &= ~BO_WWAIT;
4636 wakeup(&bo->bo_numoutput);
4642 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4646 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4647 ASSERT_BO_WLOCKED(bo);
4649 while (bo->bo_numoutput) {
4650 bo->bo_flag |= BO_WWAIT;
4651 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4652 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4660 * Set bio_data or bio_ma for struct bio from the struct buf.
4663 bdata2bio(struct buf *bp, struct bio *bip)
4666 if (!buf_mapped(bp)) {
4667 KASSERT(unmapped_buf_allowed, ("unmapped"));
4668 bip->bio_ma = bp->b_pages;
4669 bip->bio_ma_n = bp->b_npages;
4670 bip->bio_data = unmapped_buf;
4671 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4672 bip->bio_flags |= BIO_UNMAPPED;
4673 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4674 PAGE_SIZE == bp->b_npages,
4675 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4676 (long long)bip->bio_length, bip->bio_ma_n));
4678 bip->bio_data = bp->b_data;
4684 * The MIPS pmap code currently doesn't handle aliased pages.
4685 * The VIPT caches may not handle page aliasing themselves, leading
4686 * to data corruption.
4688 * As such, this code makes a system extremely unhappy if said
4689 * system doesn't support unaliasing the above situation in hardware.
4690 * Some "recent" systems (eg some mips24k/mips74k cores) don't enable
4691 * this feature at build time, so it has to be handled in software.
4693 * Once the MIPS pmap/cache code grows to support this function on
4694 * earlier chips, it should be flipped back off.
4697 static int buf_pager_relbuf = 1;
4699 static int buf_pager_relbuf = 0;
4701 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
4702 &buf_pager_relbuf, 0,
4703 "Make buffer pager release buffers after reading");
4706 * The buffer pager. It uses buffer reads to validate pages.
4708 * In contrast to the generic local pager from vm/vnode_pager.c, this
4709 * pager correctly and easily handles volumes where the underlying
4710 * device block size is greater than the machine page size. The
4711 * buffer cache transparently extends the requested page run to be
4712 * aligned at the block boundary, and does the necessary bogus page
4713 * replacements in the addends to avoid obliterating already valid
4716 * The only non-trivial issue is that the exclusive busy state for
4717 * pages, which is assumed by the vm_pager_getpages() interface, is
4718 * incompatible with the VMIO buffer cache's desire to share-busy the
4719 * pages. This function performs a trivial downgrade of the pages'
4720 * state before reading buffers, and a less trivial upgrade from the
4721 * shared-busy to excl-busy state after the read.
4724 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
4725 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
4726 vbg_get_blksize_t get_blksize)
4733 vm_ooffset_t la, lb, poff, poffe;
4735 int bo_bs, br_flags, error, i, pgsin, pgsin_a, pgsin_b;
4738 object = vp->v_object;
4740 la = IDX_TO_OFF(ma[count - 1]->pindex);
4741 if (la >= object->un_pager.vnp.vnp_size)
4742 return (VM_PAGER_BAD);
4743 lpart = la + PAGE_SIZE > object->un_pager.vnp.vnp_size;
4744 bo_bs = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)));
4747 * Calculate read-ahead, behind and total pages.
4750 lb = IDX_TO_OFF(ma[0]->pindex);
4751 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
4753 if (rbehind != NULL)
4755 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
4756 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
4757 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
4762 PCPU_INC(cnt.v_vnodein);
4763 PCPU_ADD(cnt.v_vnodepgsin, pgsin);
4765 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
4766 != 0) ? GB_UNMAPPED : 0;
4767 VM_OBJECT_WLOCK(object);
4769 for (i = 0; i < count; i++)
4770 vm_page_busy_downgrade(ma[i]);
4771 VM_OBJECT_WUNLOCK(object);
4774 for (i = 0; i < count; i++) {
4778 * Pages are shared busy and the object lock is not
4779 * owned, which together allow for the pages'
4780 * invalidation. The racy test for validity avoids
4781 * useless creation of the buffer for the most typical
4782 * case when invalidation is not used in redo or for
4783 * parallel read. The shared->excl upgrade loop at
4784 * the end of the function catches the race in a
4785 * reliable way (protected by the object lock).
4787 if (m->valid == VM_PAGE_BITS_ALL)
4790 poff = IDX_TO_OFF(m->pindex);
4791 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
4792 for (; poff < poffe; poff += bsize) {
4793 lbn = get_lblkno(vp, poff);
4798 bsize = get_blksize(vp, lbn);
4799 error = bread_gb(vp, lbn, bsize, curthread->td_ucred,
4803 if (LIST_EMPTY(&bp->b_dep)) {
4805 * Invalidation clears m->valid, but
4806 * may leave B_CACHE flag if the
4807 * buffer existed at the invalidation
4808 * time. In this case, recycle the
4809 * buffer to do real read on next
4810 * bread() after redo.
4812 * Otherwise B_RELBUF is not strictly
4813 * necessary, enable to reduce buf
4816 if (buf_pager_relbuf ||
4817 m->valid != VM_PAGE_BITS_ALL)
4818 bp->b_flags |= B_RELBUF;
4820 bp->b_flags &= ~B_NOCACHE;
4826 KASSERT(1 /* racy, enable for debugging */ ||
4827 m->valid == VM_PAGE_BITS_ALL || i == count - 1,
4828 ("buf %d %p invalid", i, m));
4829 if (i == count - 1 && lpart) {
4830 VM_OBJECT_WLOCK(object);
4831 if (m->valid != 0 &&
4832 m->valid != VM_PAGE_BITS_ALL)
4833 vm_page_zero_invalid(m, TRUE);
4834 VM_OBJECT_WUNLOCK(object);
4840 VM_OBJECT_WLOCK(object);
4842 for (i = 0; i < count; i++) {
4843 vm_page_sunbusy(ma[i]);
4844 ma[i] = vm_page_grab(object, ma[i]->pindex, VM_ALLOC_NORMAL);
4847 * Since the pages were only sbusy while neither the
4848 * buffer nor the object lock was held by us, or
4849 * reallocated while vm_page_grab() slept for busy
4850 * relinguish, they could have been invalidated.
4851 * Recheck the valid bits and re-read as needed.
4853 * Note that the last page is made fully valid in the
4854 * read loop, and partial validity for the page at
4855 * index count - 1 could mean that the page was
4856 * invalidated or removed, so we must restart for
4859 if (ma[i]->valid != VM_PAGE_BITS_ALL)
4862 if (redo && error == 0)
4864 VM_OBJECT_WUNLOCK(object);
4865 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
4868 #include "opt_ddb.h"
4870 #include <ddb/ddb.h>
4872 /* DDB command to show buffer data */
4873 DB_SHOW_COMMAND(buffer, db_show_buffer)
4876 struct buf *bp = (struct buf *)addr;
4877 #ifdef FULL_BUF_TRACKING
4882 db_printf("usage: show buffer <addr>\n");
4886 db_printf("buf at %p\n", bp);
4887 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4888 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4889 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4891 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4892 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4894 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4895 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4896 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4897 db_printf("b_kvabase = %p, b_kvasize = %d\n",
4898 bp->b_kvabase, bp->b_kvasize);
4901 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4902 for (i = 0; i < bp->b_npages; i++) {
4906 db_printf("(%p, 0x%lx, 0x%lx)", m->object,
4908 (u_long)VM_PAGE_TO_PHYS(m));
4910 db_printf("( ??? )");
4911 if ((i + 1) < bp->b_npages)
4916 #if defined(FULL_BUF_TRACKING)
4917 db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
4919 i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
4920 for (j = 1; j <= BUF_TRACKING_SIZE; j++)
4921 db_printf(" %2u: %s\n", j,
4922 bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
4923 #elif defined(BUF_TRACKING)
4924 db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
4927 BUF_LOCKPRINTINFO(bp);
4930 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
4935 for (i = 0; i < nbuf; i++) {
4937 if (BUF_ISLOCKED(bp)) {
4938 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4944 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
4950 db_printf("usage: show vnodebufs <addr>\n");
4953 vp = (struct vnode *)addr;
4954 db_printf("Clean buffers:\n");
4955 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
4956 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4959 db_printf("Dirty buffers:\n");
4960 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
4961 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
4966 DB_COMMAND(countfreebufs, db_coundfreebufs)
4969 int i, used = 0, nfree = 0;
4972 db_printf("usage: countfreebufs\n");
4976 for (i = 0; i < nbuf; i++) {
4978 if (bp->b_qindex == QUEUE_EMPTY)
4984 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
4986 db_printf("numfreebuffers is %d\n", numfreebuffers);