2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2004 Poul-Henning Kamp
5 * Copyright (c) 1994,1997 John S. Dyson
6 * Copyright (c) 2013 The FreeBSD Foundation
9 * Portions of this software were developed by Konstantin Belousov
10 * under sponsorship from the FreeBSD Foundation.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * this file contains a new buffer I/O scheme implementing a coherent
36 * VM object and buffer cache scheme. Pains have been taken to make
37 * sure that the performance degradation associated with schemes such
38 * as this is not realized.
40 * Author: John S. Dyson
41 * Significant help during the development and debugging phases
42 * had been provided by David Greenman, also of the FreeBSD core team.
44 * see man buf(9) for more info.
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
50 #include <sys/param.h>
51 #include <sys/systm.h>
55 #include <sys/devicestat.h>
56 #include <sys/eventhandler.h>
58 #include <sys/limits.h>
60 #include <sys/malloc.h>
61 #include <sys/mount.h>
62 #include <sys/mutex.h>
63 #include <sys/kernel.h>
64 #include <sys/kthread.h>
66 #include <sys/racct.h>
67 #include <sys/resourcevar.h>
68 #include <sys/rwlock.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysproto.h>
73 #include <sys/vmmeter.h>
74 #include <sys/vnode.h>
75 #include <sys/watchdog.h>
76 #include <geom/geom.h>
78 #include <vm/vm_param.h>
79 #include <vm/vm_kern.h>
80 #include <vm/vm_object.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_pageout.h>
83 #include <vm/vm_pager.h>
84 #include <vm/vm_extern.h>
85 #include <vm/vm_map.h>
86 #include <vm/swap_pager.h>
87 #include "opt_compat.h"
90 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
92 struct bio_ops bioops; /* I/O operation notification */
94 struct buf_ops buf_ops_bio = {
95 .bop_name = "buf_ops_bio",
96 .bop_write = bufwrite,
97 .bop_strategy = bufstrategy,
99 .bop_bdflush = bufbdflush,
102 static struct buf *buf; /* buffer header pool */
103 extern struct buf *swbuf; /* Swap buffer header pool. */
104 caddr_t unmapped_buf;
106 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
107 struct proc *bufdaemonproc;
108 struct proc *bufspacedaemonproc;
110 static int inmem(struct vnode *vp, daddr_t blkno);
111 static void vm_hold_free_pages(struct buf *bp, int newbsize);
112 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
114 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
115 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
117 static void vfs_clean_pages_dirty_buf(struct buf *bp);
118 static void vfs_setdirty_locked_object(struct buf *bp);
119 static void vfs_vmio_invalidate(struct buf *bp);
120 static void vfs_vmio_truncate(struct buf *bp, int npages);
121 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
122 static int vfs_bio_clcheck(struct vnode *vp, int size,
123 daddr_t lblkno, daddr_t blkno);
124 static void breada(struct vnode *, daddr_t *, int *, int, struct ucred *, int,
125 void (*)(struct buf *));
126 static int buf_flush(struct vnode *vp, int);
127 static int buf_recycle(bool);
128 static int buf_scan(bool);
129 static int flushbufqueues(struct vnode *, int, int);
130 static void buf_daemon(void);
131 static void bremfreel(struct buf *bp);
132 static __inline void bd_wakeup(void);
133 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
134 static void bufkva_reclaim(vmem_t *, int);
135 static void bufkva_free(struct buf *);
136 static int buf_import(void *, void **, int, int, int);
137 static void buf_release(void *, void **, int);
138 static void maxbcachebuf_adjust(void);
140 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
141 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
142 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
145 int vmiodirenable = TRUE;
146 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
147 "Use the VM system for directory writes");
148 long runningbufspace;
149 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
150 "Amount of presently outstanding async buffer io");
151 static long bufspace;
152 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
153 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
154 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
155 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
157 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
158 "Physical memory used for buffers");
160 static long bufkvaspace;
161 SYSCTL_LONG(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace, 0,
162 "Kernel virtual memory used for buffers");
163 static long maxbufspace;
164 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RW, &maxbufspace, 0,
165 "Maximum allowed value of bufspace (including metadata)");
166 static long bufmallocspace;
167 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
168 "Amount of malloced memory for buffers");
169 static long maxbufmallocspace;
170 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
171 0, "Maximum amount of malloced memory for buffers");
172 static long lobufspace;
173 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RW, &lobufspace, 0,
174 "Minimum amount of buffers we want to have");
176 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RW, &hibufspace, 0,
177 "Maximum allowed value of bufspace (excluding metadata)");
179 SYSCTL_LONG(_vfs, OID_AUTO, bufspacethresh, CTLFLAG_RW, &bufspacethresh,
180 0, "Bufspace consumed before waking the daemon to free some");
181 static int buffreekvacnt;
182 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
183 "Number of times we have freed the KVA space from some buffer");
184 static int bufdefragcnt;
185 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
186 "Number of times we have had to repeat buffer allocation to defragment");
187 static long lorunningspace;
188 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
189 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
190 "Minimum preferred space used for in-progress I/O");
191 static long hirunningspace;
192 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
193 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
194 "Maximum amount of space to use for in-progress I/O");
195 int dirtybufferflushes;
196 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
197 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
199 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
200 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
201 int altbufferflushes;
202 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
203 0, "Number of fsync flushes to limit dirty buffers");
204 static int recursiveflushes;
205 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
206 0, "Number of flushes skipped due to being recursive");
207 static int numdirtybuffers;
208 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
209 "Number of buffers that are dirty (has unwritten changes) at the moment");
210 static int lodirtybuffers;
211 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
212 "How many buffers we want to have free before bufdaemon can sleep");
213 static int hidirtybuffers;
214 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
215 "When the number of dirty buffers is considered severe");
217 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
218 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
219 static int numfreebuffers;
220 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
221 "Number of free buffers");
222 static int lofreebuffers;
223 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
224 "Target number of free buffers");
225 static int hifreebuffers;
226 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
227 "Threshold for clean buffer recycling");
228 static int getnewbufcalls;
229 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
230 "Number of calls to getnewbuf");
231 static int getnewbufrestarts;
232 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
233 "Number of times getnewbuf has had to restart a buffer acquisition");
234 static int mappingrestarts;
235 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
236 "Number of times getblk has had to restart a buffer mapping for "
238 static int numbufallocfails;
239 SYSCTL_INT(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW, &numbufallocfails, 0,
240 "Number of times buffer allocations failed");
241 static int flushbufqtarget = 100;
242 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
243 "Amount of work to do in flushbufqueues when helping bufdaemon");
244 static long notbufdflushes;
245 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 0,
246 "Number of dirty buffer flushes done by the bufdaemon helpers");
247 static long barrierwrites;
248 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
249 "Number of barrier writes");
250 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
251 &unmapped_buf_allowed, 0,
252 "Permit the use of the unmapped i/o");
253 int maxbcachebuf = MAXBCACHEBUF;
254 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0,
255 "Maximum size of a buffer cache block");
258 * This lock synchronizes access to bd_request.
260 static struct mtx_padalign __exclusive_cache_line bdlock;
263 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
264 * waitrunningbufspace().
266 static struct mtx_padalign __exclusive_cache_line rbreqlock;
269 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
271 static struct rwlock_padalign __exclusive_cache_line nblock;
274 * Lock that protects bdirtywait.
276 static struct mtx_padalign __exclusive_cache_line bdirtylock;
279 * Wakeup point for bufdaemon, as well as indicator of whether it is already
280 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
283 static int bd_request;
286 * Request/wakeup point for the bufspace daemon.
288 static int bufspace_request;
291 * Request for the buf daemon to write more buffers than is indicated by
292 * lodirtybuf. This may be necessary to push out excess dependencies or
293 * defragment the address space where a simple count of the number of dirty
294 * buffers is insufficient to characterize the demand for flushing them.
296 static int bd_speedupreq;
299 * Synchronization (sleep/wakeup) variable for active buffer space requests.
300 * Set when wait starts, cleared prior to wakeup().
301 * Used in runningbufwakeup() and waitrunningbufspace().
303 static int runningbufreq;
306 * Synchronization (sleep/wakeup) variable for buffer requests.
307 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
309 * Used in numdirtywakeup(), bufspace_wakeup(), bwillwrite(),
310 * getnewbuf(), and getblk().
312 static volatile int needsbuffer;
315 * Synchronization for bwillwrite() waiters.
317 static int bdirtywait;
320 * Definitions for the buffer free lists.
322 #define QUEUE_NONE 0 /* on no queue */
323 #define QUEUE_EMPTY 1 /* empty buffer headers */
324 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
325 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
326 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
328 /* Maximum number of clean buffer queues. */
329 #define CLEAN_QUEUES 16
331 /* Configured number of clean queues. */
332 static int clean_queues;
334 /* Maximum number of buffer queues. */
335 #define BUFFER_QUEUES (QUEUE_CLEAN + CLEAN_QUEUES)
337 /* Queues for free buffers with various properties */
338 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
340 static int bq_len[BUFFER_QUEUES];
344 * Lock for each bufqueue
346 static struct mtx_padalign __exclusive_cache_line bqlocks[BUFFER_QUEUES];
349 * per-cpu empty buffer cache.
354 * Single global constant for BUF_WMESG, to avoid getting multiple references.
355 * buf_wmesg is referred from macros.
357 const char *buf_wmesg = BUF_WMESG;
360 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
365 value = *(long *)arg1;
366 error = sysctl_handle_long(oidp, &value, 0, req);
367 if (error != 0 || req->newptr == NULL)
369 mtx_lock(&rbreqlock);
370 if (arg1 == &hirunningspace) {
371 if (value < lorunningspace)
374 hirunningspace = value;
376 KASSERT(arg1 == &lorunningspace,
377 ("%s: unknown arg1", __func__));
378 if (value > hirunningspace)
381 lorunningspace = value;
383 mtx_unlock(&rbreqlock);
387 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
388 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
390 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
395 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
396 return (sysctl_handle_long(oidp, arg1, arg2, req));
397 lvalue = *(long *)arg1;
398 if (lvalue > INT_MAX)
399 /* On overflow, still write out a long to trigger ENOMEM. */
400 return (sysctl_handle_long(oidp, &lvalue, 0, req));
402 return (sysctl_handle_int(oidp, &ivalue, 0, req));
411 return ((atomic_fetchadd_int(&nextq, 1) % clean_queues) + QUEUE_CLEAN);
415 bqisclean(int qindex)
418 return (qindex >= QUEUE_CLEAN && qindex < QUEUE_CLEAN + CLEAN_QUEUES);
424 * Return the appropriate queue lock based on the index.
426 static inline struct mtx *
430 return (struct mtx *)&bqlocks[qindex];
436 * Wakeup any bwillwrite() waiters.
441 mtx_lock(&bdirtylock);
446 mtx_unlock(&bdirtylock);
452 * Decrement the numdirtybuffers count by one and wakeup any
453 * threads blocked in bwillwrite().
459 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
460 (lodirtybuffers + hidirtybuffers) / 2)
467 * Increment the numdirtybuffers count by one and wakeup the buf
475 * Only do the wakeup once as we cross the boundary. The
476 * buf daemon will keep running until the condition clears.
478 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
479 (lodirtybuffers + hidirtybuffers) / 2)
486 * Called when buffer space is potentially available for recovery.
487 * getnewbuf() will block on this flag when it is unable to free
488 * sufficient buffer space. Buffer space becomes recoverable when
489 * bp's get placed back in the queues.
492 bufspace_wakeup(void)
496 * If someone is waiting for bufspace, wake them up.
498 * Since needsbuffer is set prior to doing an additional queue
499 * scan it is safe to check for the flag prior to acquiring the
500 * lock. The thread that is preparing to scan again before
501 * blocking would discover the buf we released.
505 if (atomic_cmpset_int(&needsbuffer, 1, 0) == 1)
506 wakeup(__DEVOLATILE(void *, &needsbuffer));
512 * bufspace_daemonwakeup:
514 * Wakeup the daemon responsible for freeing clean bufs.
517 bufspace_daemonwakeup(void)
520 if (bufspace_request == 0) {
521 bufspace_request = 1;
522 wakeup(&bufspace_request);
530 * Adjust the reported bufspace for a KVA managed buffer, possibly
531 * waking any waiters.
534 bufspace_adjust(struct buf *bp, int bufsize)
539 KASSERT((bp->b_flags & B_MALLOC) == 0,
540 ("bufspace_adjust: malloc buf %p", bp));
541 diff = bufsize - bp->b_bufsize;
543 atomic_subtract_long(&bufspace, -diff);
546 space = atomic_fetchadd_long(&bufspace, diff);
547 /* Wake up the daemon on the transition. */
548 if (space < bufspacethresh && space + diff >= bufspacethresh)
549 bufspace_daemonwakeup();
551 bp->b_bufsize = bufsize;
557 * Reserve bufspace before calling allocbuf(). metadata has a
558 * different space limit than data.
561 bufspace_reserve(int size, bool metadata)
572 if (space + size > limit)
574 } while (atomic_cmpset_long(&bufspace, space, space + size) == 0);
576 /* Wake up the daemon on the transition. */
577 if (space < bufspacethresh && space + size >= bufspacethresh)
578 bufspace_daemonwakeup();
586 * Release reserved bufspace after bufspace_adjust() has consumed it.
589 bufspace_release(int size)
591 atomic_subtract_long(&bufspace, size);
598 * Wait for bufspace, acting as the buf daemon if a locked vnode is
599 * supplied. needsbuffer must be set in a safe fashion prior to
600 * polling for space. The operation must be re-tried on return.
603 bufspace_wait(struct vnode *vp, int gbflags, int slpflag, int slptimeo)
606 int error, fl, norunbuf;
608 if ((gbflags & GB_NOWAIT_BD) != 0)
613 while (needsbuffer != 0) {
614 if (vp != NULL && vp->v_type != VCHR &&
615 (td->td_pflags & TDP_BUFNEED) == 0) {
618 * getblk() is called with a vnode locked, and
619 * some majority of the dirty buffers may as
620 * well belong to the vnode. Flushing the
621 * buffers there would make a progress that
622 * cannot be achieved by the buf_daemon, that
623 * cannot lock the vnode.
625 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
626 (td->td_pflags & TDP_NORUNNINGBUF);
629 * Play bufdaemon. The getnewbuf() function
630 * may be called while the thread owns lock
631 * for another dirty buffer for the same
632 * vnode, which makes it impossible to use
633 * VOP_FSYNC() there, due to the buffer lock
636 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
637 fl = buf_flush(vp, flushbufqtarget);
638 td->td_pflags &= norunbuf;
642 if (needsbuffer == 0)
645 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
646 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
657 * buffer space management daemon. Tries to maintain some marginal
658 * amount of free buffer space so that requesting processes neither
659 * block nor work to reclaim buffers.
662 bufspace_daemon(void)
665 kproc_suspend_check(bufspacedaemonproc);
668 * Free buffers from the clean queue until we meet our
671 * Theory of operation: The buffer cache is most efficient
672 * when some free buffer headers and space are always
673 * available to getnewbuf(). This daemon attempts to prevent
674 * the excessive blocking and synchronization associated
675 * with shortfall. It goes through three phases according
678 * 1) The daemon wakes up voluntarily once per-second
679 * during idle periods when the counters are below
680 * the wakeup thresholds (bufspacethresh, lofreebuffers).
682 * 2) The daemon wakes up as we cross the thresholds
683 * ahead of any potential blocking. This may bounce
684 * slightly according to the rate of consumption and
687 * 3) The daemon and consumers are starved for working
688 * clean buffers. This is the 'bufspace' sleep below
689 * which will inefficiently trade bufs with bqrelse
690 * until we return to condition 2.
692 while (bufspace > lobufspace ||
693 numfreebuffers < hifreebuffers) {
694 if (buf_recycle(false) != 0) {
695 atomic_set_int(&needsbuffer, 1);
696 if (buf_recycle(false) != 0) {
699 rw_sleep(__DEVOLATILE(void *,
700 &needsbuffer), &nblock,
701 PRIBIO|PDROP, "bufspace",
711 * Re-check our limits under the exclusive nblock.
714 if (bufspace < bufspacethresh &&
715 numfreebuffers > lofreebuffers) {
716 bufspace_request = 0;
717 rw_sleep(&bufspace_request, &nblock, PRIBIO|PDROP,
724 static struct kproc_desc bufspace_kp = {
729 SYSINIT(bufspacedaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start,
735 * Adjust the reported bufspace for a malloc managed buffer, possibly
736 * waking any waiters.
739 bufmallocadjust(struct buf *bp, int bufsize)
743 KASSERT((bp->b_flags & B_MALLOC) != 0,
744 ("bufmallocadjust: non-malloc buf %p", bp));
745 diff = bufsize - bp->b_bufsize;
747 atomic_subtract_long(&bufmallocspace, -diff);
749 atomic_add_long(&bufmallocspace, diff);
750 bp->b_bufsize = bufsize;
756 * Wake up processes that are waiting on asynchronous writes to fall
757 * below lorunningspace.
763 mtx_lock(&rbreqlock);
766 wakeup(&runningbufreq);
768 mtx_unlock(&rbreqlock);
774 * Decrement the outstanding write count according.
777 runningbufwakeup(struct buf *bp)
781 bspace = bp->b_runningbufspace;
784 space = atomic_fetchadd_long(&runningbufspace, -bspace);
785 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
787 bp->b_runningbufspace = 0;
789 * Only acquire the lock and wakeup on the transition from exceeding
790 * the threshold to falling below it.
792 if (space < lorunningspace)
794 if (space - bspace > lorunningspace)
800 * waitrunningbufspace()
802 * runningbufspace is a measure of the amount of I/O currently
803 * running. This routine is used in async-write situations to
804 * prevent creating huge backups of pending writes to a device.
805 * Only asynchronous writes are governed by this function.
807 * This does NOT turn an async write into a sync write. It waits
808 * for earlier writes to complete and generally returns before the
809 * caller's write has reached the device.
812 waitrunningbufspace(void)
815 mtx_lock(&rbreqlock);
816 while (runningbufspace > hirunningspace) {
818 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
820 mtx_unlock(&rbreqlock);
825 * vfs_buf_test_cache:
827 * Called when a buffer is extended. This function clears the B_CACHE
828 * bit if the newly extended portion of the buffer does not contain
832 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
833 vm_offset_t size, vm_page_t m)
836 VM_OBJECT_ASSERT_LOCKED(m->object);
837 if (bp->b_flags & B_CACHE) {
838 int base = (foff + off) & PAGE_MASK;
839 if (vm_page_is_valid(m, base, size) == 0)
840 bp->b_flags &= ~B_CACHE;
844 /* Wake up the buffer daemon if necessary */
850 if (bd_request == 0) {
858 * Adjust the maxbcachbuf tunable.
861 maxbcachebuf_adjust(void)
866 * maxbcachebuf must be a power of 2 >= MAXBSIZE.
869 while (i * 2 <= maxbcachebuf)
872 if (maxbcachebuf < MAXBSIZE)
873 maxbcachebuf = MAXBSIZE;
874 if (maxbcachebuf > MAXPHYS)
875 maxbcachebuf = MAXPHYS;
876 if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF)
877 printf("maxbcachebuf=%d\n", maxbcachebuf);
881 * bd_speedup - speedup the buffer cache flushing code
890 if (bd_speedupreq == 0 || bd_request == 0)
900 #define NSWBUF_MIN 16
904 #define TRANSIENT_DENOM 5
906 #define TRANSIENT_DENOM 10
910 * Calculating buffer cache scaling values and reserve space for buffer
911 * headers. This is called during low level kernel initialization and
912 * may be called more then once. We CANNOT write to the memory area
913 * being reserved at this time.
916 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
919 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
922 * physmem_est is in pages. Convert it to kilobytes (assumes
923 * PAGE_SIZE is >= 1K)
925 physmem_est = physmem_est * (PAGE_SIZE / 1024);
927 maxbcachebuf_adjust();
929 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
930 * For the first 64MB of ram nominally allocate sufficient buffers to
931 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
932 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
933 * the buffer cache we limit the eventual kva reservation to
936 * factor represents the 1/4 x ram conversion.
939 int factor = 4 * BKVASIZE / 1024;
942 if (physmem_est > 4096)
943 nbuf += min((physmem_est - 4096) / factor,
945 if (physmem_est > 65536)
946 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
947 32 * 1024 * 1024 / (factor * 5));
949 if (maxbcache && nbuf > maxbcache / BKVASIZE)
950 nbuf = maxbcache / BKVASIZE;
955 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
956 maxbuf = (LONG_MAX / 3) / BKVASIZE;
959 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
965 * Ideal allocation size for the transient bio submap is 10%
966 * of the maximal space buffer map. This roughly corresponds
967 * to the amount of the buffer mapped for typical UFS load.
969 * Clip the buffer map to reserve space for the transient
970 * BIOs, if its extent is bigger than 90% (80% on i386) of the
971 * maximum buffer map extent on the platform.
973 * The fall-back to the maxbuf in case of maxbcache unset,
974 * allows to not trim the buffer KVA for the architectures
975 * with ample KVA space.
977 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
978 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
979 buf_sz = (long)nbuf * BKVASIZE;
980 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
981 (TRANSIENT_DENOM - 1)) {
983 * There is more KVA than memory. Do not
984 * adjust buffer map size, and assign the rest
985 * of maxbuf to transient map.
987 biotmap_sz = maxbuf_sz - buf_sz;
990 * Buffer map spans all KVA we could afford on
991 * this platform. Give 10% (20% on i386) of
992 * the buffer map to the transient bio map.
994 biotmap_sz = buf_sz / TRANSIENT_DENOM;
995 buf_sz -= biotmap_sz;
997 if (biotmap_sz / INT_MAX > MAXPHYS)
998 bio_transient_maxcnt = INT_MAX;
1000 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
1002 * Artificially limit to 1024 simultaneous in-flight I/Os
1003 * using the transient mapping.
1005 if (bio_transient_maxcnt > 1024)
1006 bio_transient_maxcnt = 1024;
1008 nbuf = buf_sz / BKVASIZE;
1012 * swbufs are used as temporary holders for I/O, such as paging I/O.
1013 * We have no less then 16 and no more then 256.
1015 nswbuf = min(nbuf / 4, 256);
1016 TUNABLE_INT_FETCH("kern.nswbuf", &nswbuf);
1017 if (nswbuf < NSWBUF_MIN)
1018 nswbuf = NSWBUF_MIN;
1021 * Reserve space for the buffer cache buffers
1024 v = (caddr_t)(swbuf + nswbuf);
1026 v = (caddr_t)(buf + nbuf);
1031 /* Initialize the buffer subsystem. Called before use of any buffers. */
1038 KASSERT(maxbcachebuf >= MAXBSIZE,
1039 ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf,
1041 mtx_init(&bqlocks[QUEUE_DIRTY], "bufq dirty lock", NULL, MTX_DEF);
1042 mtx_init(&bqlocks[QUEUE_EMPTY], "bufq empty lock", NULL, MTX_DEF);
1043 for (i = QUEUE_CLEAN; i < QUEUE_CLEAN + CLEAN_QUEUES; i++)
1044 mtx_init(&bqlocks[i], "bufq clean lock", NULL, MTX_DEF);
1045 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1046 rw_init(&nblock, "needsbuffer lock");
1047 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1048 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1050 /* next, make a null set of free lists */
1051 for (i = 0; i < BUFFER_QUEUES; i++)
1052 TAILQ_INIT(&bufqueues[i]);
1054 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
1056 /* finally, initialize each buffer header and stick on empty q */
1057 for (i = 0; i < nbuf; i++) {
1059 bzero(bp, sizeof *bp);
1060 bp->b_flags = B_INVAL;
1061 bp->b_rcred = NOCRED;
1062 bp->b_wcred = NOCRED;
1063 bp->b_qindex = QUEUE_EMPTY;
1065 bp->b_data = bp->b_kvabase = unmapped_buf;
1066 LIST_INIT(&bp->b_dep);
1068 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
1070 bq_len[QUEUE_EMPTY]++;
1075 * maxbufspace is the absolute maximum amount of buffer space we are
1076 * allowed to reserve in KVM and in real terms. The absolute maximum
1077 * is nominally used by metadata. hibufspace is the nominal maximum
1078 * used by most other requests. The differential is required to
1079 * ensure that metadata deadlocks don't occur.
1081 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1082 * this may result in KVM fragmentation which is not handled optimally
1083 * by the system. XXX This is less true with vmem. We could use
1086 maxbufspace = (long)nbuf * BKVASIZE;
1087 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10);
1088 lobufspace = (hibufspace / 20) * 19; /* 95% */
1089 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1092 * Note: The 16 MiB upper limit for hirunningspace was chosen
1093 * arbitrarily and may need further tuning. It corresponds to
1094 * 128 outstanding write IO requests (if IO size is 128 KiB),
1095 * which fits with many RAID controllers' tagged queuing limits.
1096 * The lower 1 MiB limit is the historical upper limit for
1099 hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf),
1100 16 * 1024 * 1024), 1024 * 1024);
1101 lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf);
1104 * Limit the amount of malloc memory since it is wired permanently into
1105 * the kernel space. Even though this is accounted for in the buffer
1106 * allocation, we don't want the malloced region to grow uncontrolled.
1107 * The malloc scheme improves memory utilization significantly on
1108 * average (small) directories.
1110 maxbufmallocspace = hibufspace / 20;
1113 * Reduce the chance of a deadlock occurring by limiting the number
1114 * of delayed-write dirty buffers we allow to stack up.
1116 hidirtybuffers = nbuf / 4 + 20;
1117 dirtybufthresh = hidirtybuffers * 9 / 10;
1118 numdirtybuffers = 0;
1120 * To support extreme low-memory systems, make sure hidirtybuffers
1121 * cannot eat up all available buffer space. This occurs when our
1122 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1123 * buffer space assuming BKVASIZE'd buffers.
1125 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1126 hidirtybuffers >>= 1;
1128 lodirtybuffers = hidirtybuffers / 2;
1131 * lofreebuffers should be sufficient to avoid stalling waiting on
1132 * buf headers under heavy utilization. The bufs in per-cpu caches
1133 * are counted as free but will be unavailable to threads executing
1136 * hifreebuffers is the free target for the bufspace daemon. This
1137 * should be set appropriately to limit work per-iteration.
1139 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1140 hifreebuffers = (3 * lofreebuffers) / 2;
1141 numfreebuffers = nbuf;
1143 /* Setup the kva and free list allocators. */
1144 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1145 buf_zone = uma_zcache_create("buf free cache", sizeof(struct buf),
1146 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1149 * Size the clean queue according to the amount of buffer space.
1150 * One queue per-256mb up to the max. More queues gives better
1151 * concurrency but less accurate LRU.
1153 clean_queues = MIN(howmany(maxbufspace, 256*1024*1024), CLEAN_QUEUES);
1159 vfs_buf_check_mapped(struct buf *bp)
1162 KASSERT(bp->b_kvabase != unmapped_buf,
1163 ("mapped buf: b_kvabase was not updated %p", bp));
1164 KASSERT(bp->b_data != unmapped_buf,
1165 ("mapped buf: b_data was not updated %p", bp));
1166 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1167 MAXPHYS, ("b_data + b_offset unmapped %p", bp));
1171 vfs_buf_check_unmapped(struct buf *bp)
1174 KASSERT(bp->b_data == unmapped_buf,
1175 ("unmapped buf: corrupted b_data %p", bp));
1178 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1179 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1181 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1182 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1186 isbufbusy(struct buf *bp)
1188 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1189 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1195 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1198 bufshutdown(int show_busybufs)
1200 static int first_buf_printf = 1;
1202 int iter, nbusy, pbusy;
1208 * Sync filesystems for shutdown
1210 wdog_kern_pat(WD_LASTVAL);
1211 sys_sync(curthread, NULL);
1214 * With soft updates, some buffers that are
1215 * written will be remarked as dirty until other
1216 * buffers are written.
1218 for (iter = pbusy = 0; iter < 20; iter++) {
1220 for (bp = &buf[nbuf]; --bp >= buf; )
1224 if (first_buf_printf)
1225 printf("All buffers synced.");
1228 if (first_buf_printf) {
1229 printf("Syncing disks, buffers remaining... ");
1230 first_buf_printf = 0;
1232 printf("%d ", nbusy);
1237 wdog_kern_pat(WD_LASTVAL);
1238 sys_sync(curthread, NULL);
1242 * Drop Giant and spin for a while to allow
1243 * interrupt threads to run.
1246 DELAY(50000 * iter);
1250 * Drop Giant and context switch several times to
1251 * allow interrupt threads to run.
1254 for (subiter = 0; subiter < 50 * iter; subiter++) {
1255 thread_lock(curthread);
1256 mi_switch(SW_VOL, NULL);
1257 thread_unlock(curthread);
1265 * Count only busy local buffers to prevent forcing
1266 * a fsck if we're just a client of a wedged NFS server
1269 for (bp = &buf[nbuf]; --bp >= buf; ) {
1270 if (isbufbusy(bp)) {
1272 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1273 if (bp->b_dev == NULL) {
1274 TAILQ_REMOVE(&mountlist,
1275 bp->b_vp->v_mount, mnt_list);
1280 if (show_busybufs > 0) {
1282 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1283 nbusy, bp, bp->b_vp, bp->b_flags,
1284 (intmax_t)bp->b_blkno,
1285 (intmax_t)bp->b_lblkno);
1286 BUF_LOCKPRINTINFO(bp);
1287 if (show_busybufs > 1)
1295 * Failed to sync all blocks. Indicate this and don't
1296 * unmount filesystems (thus forcing an fsck on reboot).
1298 printf("Giving up on %d buffers\n", nbusy);
1299 DELAY(5000000); /* 5 seconds */
1301 if (!first_buf_printf)
1302 printf("Final sync complete\n");
1304 * Unmount filesystems
1306 if (panicstr == NULL)
1310 DELAY(100000); /* wait for console output to finish */
1314 bpmap_qenter(struct buf *bp)
1317 BUF_CHECK_MAPPED(bp);
1320 * bp->b_data is relative to bp->b_offset, but
1321 * bp->b_offset may be offset into the first page.
1323 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1324 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1325 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1326 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1332 * Insert the buffer into the appropriate free list.
1335 binsfree(struct buf *bp, int qindex)
1337 struct mtx *olock, *nlock;
1339 if (qindex != QUEUE_EMPTY) {
1340 BUF_ASSERT_XLOCKED(bp);
1344 * Stick to the same clean queue for the lifetime of the buf to
1345 * limit locking below. Otherwise pick ont sequentially.
1347 if (qindex == QUEUE_CLEAN) {
1348 if (bqisclean(bp->b_qindex))
1349 qindex = bp->b_qindex;
1351 qindex = bqcleanq();
1355 * Handle delayed bremfree() processing.
1357 nlock = bqlock(qindex);
1358 if (bp->b_flags & B_REMFREE) {
1359 olock = bqlock(bp->b_qindex);
1362 if (olock != nlock) {
1369 if (bp->b_qindex != QUEUE_NONE)
1370 panic("binsfree: free buffer onto another queue???");
1372 bp->b_qindex = qindex;
1373 if (bp->b_flags & B_AGE)
1374 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1376 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1378 bq_len[bp->b_qindex]++;
1386 * Free a buffer to the buf zone once it no longer has valid contents.
1389 buf_free(struct buf *bp)
1392 if (bp->b_flags & B_REMFREE)
1394 if (bp->b_vflags & BV_BKGRDINPROG)
1395 panic("losing buffer 1");
1396 if (bp->b_rcred != NOCRED) {
1397 crfree(bp->b_rcred);
1398 bp->b_rcred = NOCRED;
1400 if (bp->b_wcred != NOCRED) {
1401 crfree(bp->b_wcred);
1402 bp->b_wcred = NOCRED;
1404 if (!LIST_EMPTY(&bp->b_dep))
1408 uma_zfree(buf_zone, bp);
1409 atomic_add_int(&numfreebuffers, 1);
1416 * Import bufs into the uma cache from the buf list. The system still
1417 * expects a static array of bufs and much of the synchronization
1418 * around bufs assumes type stable storage. As a result, UMA is used
1419 * only as a per-cpu cache of bufs still maintained on a global list.
1422 buf_import(void *arg, void **store, int cnt, int domain, int flags)
1427 mtx_lock(&bqlocks[QUEUE_EMPTY]);
1428 for (i = 0; i < cnt; i++) {
1429 bp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1435 mtx_unlock(&bqlocks[QUEUE_EMPTY]);
1443 * Release bufs from the uma cache back to the buffer queues.
1446 buf_release(void *arg, void **store, int cnt)
1450 for (i = 0; i < cnt; i++)
1451 binsfree(store[i], QUEUE_EMPTY);
1457 * Allocate an empty buffer header.
1464 bp = uma_zalloc(buf_zone, M_NOWAIT);
1466 bufspace_daemonwakeup();
1467 atomic_add_int(&numbufallocfails, 1);
1472 * Wake-up the bufspace daemon on transition.
1474 if (atomic_fetchadd_int(&numfreebuffers, -1) == lofreebuffers)
1475 bufspace_daemonwakeup();
1477 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1478 panic("getnewbuf_empty: Locked buf %p on free queue.", bp);
1480 KASSERT(bp->b_vp == NULL,
1481 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1482 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1483 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1484 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1485 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1486 KASSERT(bp->b_npages == 0,
1487 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1488 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1489 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1496 bp->b_blkno = bp->b_lblkno = 0;
1497 bp->b_offset = NOOFFSET;
1503 bp->b_dirtyoff = bp->b_dirtyend = 0;
1504 bp->b_bufobj = NULL;
1505 bp->b_data = bp->b_kvabase = unmapped_buf;
1506 bp->b_fsprivate1 = NULL;
1507 bp->b_fsprivate2 = NULL;
1508 bp->b_fsprivate3 = NULL;
1509 LIST_INIT(&bp->b_dep);
1517 * Free a buffer from the given bufqueue. kva controls whether the
1518 * freed buf must own some kva resources. This is used for
1522 buf_qrecycle(int qindex, bool kva)
1524 struct buf *bp, *nbp;
1527 atomic_add_int(&bufdefragcnt, 1);
1529 mtx_lock(&bqlocks[qindex]);
1530 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1533 * Run scan, possibly freeing data and/or kva mappings on the fly
1536 while ((bp = nbp) != NULL) {
1538 * Calculate next bp (we can only use it if we do not
1539 * release the bqlock).
1541 nbp = TAILQ_NEXT(bp, b_freelist);
1544 * If we are defragging then we need a buffer with
1545 * some kva to reclaim.
1547 if (kva && bp->b_kvasize == 0)
1550 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1554 * Skip buffers with background writes in progress.
1556 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1561 KASSERT(bp->b_qindex == qindex,
1562 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1564 * NOTE: nbp is now entirely invalid. We can only restart
1565 * the scan from this point on.
1568 mtx_unlock(&bqlocks[qindex]);
1571 * Requeue the background write buffer with error and
1574 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1576 mtx_lock(&bqlocks[qindex]);
1577 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1580 bp->b_flags |= B_INVAL;
1584 mtx_unlock(&bqlocks[qindex]);
1592 * Iterate through all clean queues until we find a buf to recycle or
1593 * exhaust the search.
1596 buf_recycle(bool kva)
1598 int qindex, first_qindex;
1600 qindex = first_qindex = bqcleanq();
1602 if (buf_qrecycle(qindex, kva) == 0)
1604 if (++qindex == QUEUE_CLEAN + clean_queues)
1605 qindex = QUEUE_CLEAN;
1606 } while (qindex != first_qindex);
1614 * Scan the clean queues looking for a buffer to recycle. needsbuffer
1615 * is set on failure so that the caller may optionally bufspace_wait()
1616 * in a race-free fashion.
1619 buf_scan(bool defrag)
1624 * To avoid heavy synchronization and wakeup races we set
1625 * needsbuffer and re-poll before failing. This ensures that
1626 * no frees can be missed between an unsuccessful poll and
1627 * going to sleep in a synchronized fashion.
1629 if ((error = buf_recycle(defrag)) != 0) {
1630 atomic_set_int(&needsbuffer, 1);
1631 bufspace_daemonwakeup();
1632 error = buf_recycle(defrag);
1635 atomic_add_int(&getnewbufrestarts, 1);
1642 * Mark the buffer for removal from the appropriate free list.
1646 bremfree(struct buf *bp)
1649 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1650 KASSERT((bp->b_flags & B_REMFREE) == 0,
1651 ("bremfree: buffer %p already marked for delayed removal.", bp));
1652 KASSERT(bp->b_qindex != QUEUE_NONE,
1653 ("bremfree: buffer %p not on a queue.", bp));
1654 BUF_ASSERT_XLOCKED(bp);
1656 bp->b_flags |= B_REMFREE;
1662 * Force an immediate removal from a free list. Used only in nfs when
1663 * it abuses the b_freelist pointer.
1666 bremfreef(struct buf *bp)
1670 qlock = bqlock(bp->b_qindex);
1679 * Removes a buffer from the free list, must be called with the
1680 * correct qlock held.
1683 bremfreel(struct buf *bp)
1686 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1687 bp, bp->b_vp, bp->b_flags);
1688 KASSERT(bp->b_qindex != QUEUE_NONE,
1689 ("bremfreel: buffer %p not on a queue.", bp));
1690 if (bp->b_qindex != QUEUE_EMPTY) {
1691 BUF_ASSERT_XLOCKED(bp);
1693 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1695 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1697 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1699 bq_len[bp->b_qindex]--;
1701 bp->b_qindex = QUEUE_NONE;
1702 bp->b_flags &= ~B_REMFREE;
1708 * Free the kva allocation for a buffer.
1712 bufkva_free(struct buf *bp)
1716 if (bp->b_kvasize == 0) {
1717 KASSERT(bp->b_kvabase == unmapped_buf &&
1718 bp->b_data == unmapped_buf,
1719 ("Leaked KVA space on %p", bp));
1720 } else if (buf_mapped(bp))
1721 BUF_CHECK_MAPPED(bp);
1723 BUF_CHECK_UNMAPPED(bp);
1725 if (bp->b_kvasize == 0)
1728 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
1729 atomic_subtract_long(&bufkvaspace, bp->b_kvasize);
1730 atomic_add_int(&buffreekvacnt, 1);
1731 bp->b_data = bp->b_kvabase = unmapped_buf;
1738 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
1741 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
1746 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
1747 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
1752 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
1755 * Buffer map is too fragmented. Request the caller
1756 * to defragment the map.
1760 bp->b_kvabase = (caddr_t)addr;
1761 bp->b_kvasize = maxsize;
1762 atomic_add_long(&bufkvaspace, bp->b_kvasize);
1763 if ((gbflags & GB_UNMAPPED) != 0) {
1764 bp->b_data = unmapped_buf;
1765 BUF_CHECK_UNMAPPED(bp);
1767 bp->b_data = bp->b_kvabase;
1768 BUF_CHECK_MAPPED(bp);
1776 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
1777 * callback that fires to avoid returning failure.
1780 bufkva_reclaim(vmem_t *vmem, int flags)
1784 for (i = 0; i < 5; i++)
1785 if (buf_scan(true) != 0)
1791 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1792 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1793 * the buffer is valid and we do not have to do anything.
1796 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize, int cnt,
1797 struct ucred * cred, int flags, void (*ckhashfunc)(struct buf *))
1802 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1803 if (inmem(vp, *rablkno))
1805 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1806 if ((rabp->b_flags & B_CACHE) != 0) {
1810 if (!TD_IS_IDLETHREAD(curthread)) {
1814 racct_add_buf(curproc, rabp, 0);
1815 PROC_UNLOCK(curproc);
1818 curthread->td_ru.ru_inblock++;
1820 rabp->b_flags |= B_ASYNC;
1821 rabp->b_flags &= ~B_INVAL;
1822 if ((flags & GB_CKHASH) != 0) {
1823 rabp->b_flags |= B_CKHASH;
1824 rabp->b_ckhashcalc = ckhashfunc;
1826 rabp->b_ioflags &= ~BIO_ERROR;
1827 rabp->b_iocmd = BIO_READ;
1828 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1829 rabp->b_rcred = crhold(cred);
1830 vfs_busy_pages(rabp, 0);
1832 rabp->b_iooffset = dbtob(rabp->b_blkno);
1838 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1840 * Get a buffer with the specified data. Look in the cache first. We
1841 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1842 * is set, the buffer is valid and we do not have to do anything, see
1843 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1845 * Always return a NULL buffer pointer (in bpp) when returning an error.
1848 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1849 int *rabsize, int cnt, struct ucred *cred, int flags,
1850 void (*ckhashfunc)(struct buf *), struct buf **bpp)
1855 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1857 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1859 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1864 * If not found in cache, do some I/O
1867 if ((bp->b_flags & B_CACHE) == 0) {
1868 if (!TD_IS_IDLETHREAD(curthread)) {
1872 racct_add_buf(curproc, bp, 0);
1873 PROC_UNLOCK(curproc);
1876 curthread->td_ru.ru_inblock++;
1878 bp->b_iocmd = BIO_READ;
1879 bp->b_flags &= ~B_INVAL;
1880 if ((flags & GB_CKHASH) != 0) {
1881 bp->b_flags |= B_CKHASH;
1882 bp->b_ckhashcalc = ckhashfunc;
1884 bp->b_ioflags &= ~BIO_ERROR;
1885 if (bp->b_rcred == NOCRED && cred != NOCRED)
1886 bp->b_rcred = crhold(cred);
1887 vfs_busy_pages(bp, 0);
1888 bp->b_iooffset = dbtob(bp->b_blkno);
1894 * Attempt to initiate asynchronous I/O on read-ahead blocks.
1896 breada(vp, rablkno, rabsize, cnt, cred, flags, ckhashfunc);
1910 * Write, release buffer on completion. (Done by iodone
1911 * if async). Do not bother writing anything if the buffer
1914 * Note that we set B_CACHE here, indicating that buffer is
1915 * fully valid and thus cacheable. This is true even of NFS
1916 * now so we set it generally. This could be set either here
1917 * or in biodone() since the I/O is synchronous. We put it
1921 bufwrite(struct buf *bp)
1928 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1929 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
1930 bp->b_flags |= B_INVAL | B_RELBUF;
1931 bp->b_flags &= ~B_CACHE;
1935 if (bp->b_flags & B_INVAL) {
1940 if (bp->b_flags & B_BARRIER)
1943 oldflags = bp->b_flags;
1945 BUF_ASSERT_HELD(bp);
1947 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1948 ("FFS background buffer should not get here %p", bp));
1952 vp_md = vp->v_vflag & VV_MD;
1957 * Mark the buffer clean. Increment the bufobj write count
1958 * before bundirty() call, to prevent other thread from seeing
1959 * empty dirty list and zero counter for writes in progress,
1960 * falsely indicating that the bufobj is clean.
1962 bufobj_wref(bp->b_bufobj);
1965 bp->b_flags &= ~B_DONE;
1966 bp->b_ioflags &= ~BIO_ERROR;
1967 bp->b_flags |= B_CACHE;
1968 bp->b_iocmd = BIO_WRITE;
1970 vfs_busy_pages(bp, 1);
1973 * Normal bwrites pipeline writes
1975 bp->b_runningbufspace = bp->b_bufsize;
1976 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1978 if (!TD_IS_IDLETHREAD(curthread)) {
1982 racct_add_buf(curproc, bp, 1);
1983 PROC_UNLOCK(curproc);
1986 curthread->td_ru.ru_oublock++;
1988 if (oldflags & B_ASYNC)
1990 bp->b_iooffset = dbtob(bp->b_blkno);
1991 buf_track(bp, __func__);
1994 if ((oldflags & B_ASYNC) == 0) {
1995 int rtval = bufwait(bp);
1998 } else if (space > hirunningspace) {
2000 * don't allow the async write to saturate the I/O
2001 * system. We will not deadlock here because
2002 * we are blocking waiting for I/O that is already in-progress
2003 * to complete. We do not block here if it is the update
2004 * or syncer daemon trying to clean up as that can lead
2007 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
2008 waitrunningbufspace();
2015 bufbdflush(struct bufobj *bo, struct buf *bp)
2019 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
2020 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
2022 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
2025 * Try to find a buffer to flush.
2027 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2028 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2030 LK_EXCLUSIVE | LK_NOWAIT, NULL))
2033 panic("bdwrite: found ourselves");
2035 /* Don't countdeps with the bo lock held. */
2036 if (buf_countdeps(nbp, 0)) {
2041 if (nbp->b_flags & B_CLUSTEROK) {
2042 vfs_bio_awrite(nbp);
2047 dirtybufferflushes++;
2056 * Delayed write. (Buffer is marked dirty). Do not bother writing
2057 * anything if the buffer is marked invalid.
2059 * Note that since the buffer must be completely valid, we can safely
2060 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2061 * biodone() in order to prevent getblk from writing the buffer
2062 * out synchronously.
2065 bdwrite(struct buf *bp)
2067 struct thread *td = curthread;
2071 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2072 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2073 KASSERT((bp->b_flags & B_BARRIER) == 0,
2074 ("Barrier request in delayed write %p", bp));
2075 BUF_ASSERT_HELD(bp);
2077 if (bp->b_flags & B_INVAL) {
2083 * If we have too many dirty buffers, don't create any more.
2084 * If we are wildly over our limit, then force a complete
2085 * cleanup. Otherwise, just keep the situation from getting
2086 * out of control. Note that we have to avoid a recursive
2087 * disaster and not try to clean up after our own cleanup!
2091 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2092 td->td_pflags |= TDP_INBDFLUSH;
2094 td->td_pflags &= ~TDP_INBDFLUSH;
2100 * Set B_CACHE, indicating that the buffer is fully valid. This is
2101 * true even of NFS now.
2103 bp->b_flags |= B_CACHE;
2106 * This bmap keeps the system from needing to do the bmap later,
2107 * perhaps when the system is attempting to do a sync. Since it
2108 * is likely that the indirect block -- or whatever other datastructure
2109 * that the filesystem needs is still in memory now, it is a good
2110 * thing to do this. Note also, that if the pageout daemon is
2111 * requesting a sync -- there might not be enough memory to do
2112 * the bmap then... So, this is important to do.
2114 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2115 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2118 buf_track(bp, __func__);
2121 * Set the *dirty* buffer range based upon the VM system dirty
2124 * Mark the buffer pages as clean. We need to do this here to
2125 * satisfy the vnode_pager and the pageout daemon, so that it
2126 * thinks that the pages have been "cleaned". Note that since
2127 * the pages are in a delayed write buffer -- the VFS layer
2128 * "will" see that the pages get written out on the next sync,
2129 * or perhaps the cluster will be completed.
2131 vfs_clean_pages_dirty_buf(bp);
2135 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2136 * due to the softdep code.
2143 * Turn buffer into delayed write request. We must clear BIO_READ and
2144 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2145 * itself to properly update it in the dirty/clean lists. We mark it
2146 * B_DONE to ensure that any asynchronization of the buffer properly
2147 * clears B_DONE ( else a panic will occur later ).
2149 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2150 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2151 * should only be called if the buffer is known-good.
2153 * Since the buffer is not on a queue, we do not update the numfreebuffers
2156 * The buffer must be on QUEUE_NONE.
2159 bdirty(struct buf *bp)
2162 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2163 bp, bp->b_vp, bp->b_flags);
2164 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2165 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2166 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2167 BUF_ASSERT_HELD(bp);
2168 bp->b_flags &= ~(B_RELBUF);
2169 bp->b_iocmd = BIO_WRITE;
2171 if ((bp->b_flags & B_DELWRI) == 0) {
2172 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2181 * Clear B_DELWRI for buffer.
2183 * Since the buffer is not on a queue, we do not update the numfreebuffers
2186 * The buffer must be on QUEUE_NONE.
2190 bundirty(struct buf *bp)
2193 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2194 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2195 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2196 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2197 BUF_ASSERT_HELD(bp);
2199 if (bp->b_flags & B_DELWRI) {
2200 bp->b_flags &= ~B_DELWRI;
2205 * Since it is now being written, we can clear its deferred write flag.
2207 bp->b_flags &= ~B_DEFERRED;
2213 * Asynchronous write. Start output on a buffer, but do not wait for
2214 * it to complete. The buffer is released when the output completes.
2216 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2217 * B_INVAL buffers. Not us.
2220 bawrite(struct buf *bp)
2223 bp->b_flags |= B_ASYNC;
2230 * Asynchronous barrier write. Start output on a buffer, but do not
2231 * wait for it to complete. Place a write barrier after this write so
2232 * that this buffer and all buffers written before it are committed to
2233 * the disk before any buffers written after this write are committed
2234 * to the disk. The buffer is released when the output completes.
2237 babarrierwrite(struct buf *bp)
2240 bp->b_flags |= B_ASYNC | B_BARRIER;
2247 * Synchronous barrier write. Start output on a buffer and wait for
2248 * it to complete. Place a write barrier after this write so that
2249 * this buffer and all buffers written before it are committed to
2250 * the disk before any buffers written after this write are committed
2251 * to the disk. The buffer is released when the output completes.
2254 bbarrierwrite(struct buf *bp)
2257 bp->b_flags |= B_BARRIER;
2258 return (bwrite(bp));
2264 * Called prior to the locking of any vnodes when we are expecting to
2265 * write. We do not want to starve the buffer cache with too many
2266 * dirty buffers so we block here. By blocking prior to the locking
2267 * of any vnodes we attempt to avoid the situation where a locked vnode
2268 * prevents the various system daemons from flushing related buffers.
2274 if (numdirtybuffers >= hidirtybuffers) {
2275 mtx_lock(&bdirtylock);
2276 while (numdirtybuffers >= hidirtybuffers) {
2278 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2281 mtx_unlock(&bdirtylock);
2286 * Return true if we have too many dirty buffers.
2289 buf_dirty_count_severe(void)
2292 return(numdirtybuffers >= hidirtybuffers);
2298 * Release a busy buffer and, if requested, free its resources. The
2299 * buffer will be stashed in the appropriate bufqueue[] allowing it
2300 * to be accessed later as a cache entity or reused for other purposes.
2303 brelse(struct buf *bp)
2308 * Many functions erroneously call brelse with a NULL bp under rare
2309 * error conditions. Simply return when called with a NULL bp.
2313 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2314 bp, bp->b_vp, bp->b_flags);
2315 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2316 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2317 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2318 ("brelse: non-VMIO buffer marked NOREUSE"));
2320 if (BUF_LOCKRECURSED(bp)) {
2322 * Do not process, in particular, do not handle the
2323 * B_INVAL/B_RELBUF and do not release to free list.
2329 if (bp->b_flags & B_MANAGED) {
2334 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2335 BO_LOCK(bp->b_bufobj);
2336 bp->b_vflags &= ~BV_BKGRDERR;
2337 BO_UNLOCK(bp->b_bufobj);
2340 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2341 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2342 !(bp->b_flags & B_INVAL)) {
2344 * Failed write, redirty. All errors except ENXIO (which
2345 * means the device is gone) are treated as being
2348 * XXX Treating EIO as transient is not correct; the
2349 * contract with the local storage device drivers is that
2350 * they will only return EIO once the I/O is no longer
2351 * retriable. Network I/O also respects this through the
2352 * guarantees of TCP and/or the internal retries of NFS.
2353 * ENOMEM might be transient, but we also have no way of
2354 * knowing when its ok to retry/reschedule. In general,
2355 * this entire case should be made obsolete through better
2356 * error handling/recovery and resource scheduling.
2358 * Do this also for buffers that failed with ENXIO, but have
2359 * non-empty dependencies - the soft updates code might need
2360 * to access the buffer to untangle them.
2362 * Must clear BIO_ERROR to prevent pages from being scrapped.
2364 bp->b_ioflags &= ~BIO_ERROR;
2366 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2367 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2369 * Either a failed read I/O, or we were asked to free or not
2370 * cache the buffer, or we failed to write to a device that's
2371 * no longer present.
2373 bp->b_flags |= B_INVAL;
2374 if (!LIST_EMPTY(&bp->b_dep))
2376 if (bp->b_flags & B_DELWRI)
2378 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2379 if ((bp->b_flags & B_VMIO) == 0) {
2387 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2388 * is called with B_DELWRI set, the underlying pages may wind up
2389 * getting freed causing a previous write (bdwrite()) to get 'lost'
2390 * because pages associated with a B_DELWRI bp are marked clean.
2392 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2393 * if B_DELWRI is set.
2395 if (bp->b_flags & B_DELWRI)
2396 bp->b_flags &= ~B_RELBUF;
2399 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2400 * constituted, not even NFS buffers now. Two flags effect this. If
2401 * B_INVAL, the struct buf is invalidated but the VM object is kept
2402 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2404 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2405 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2406 * buffer is also B_INVAL because it hits the re-dirtying code above.
2408 * Normally we can do this whether a buffer is B_DELWRI or not. If
2409 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2410 * the commit state and we cannot afford to lose the buffer. If the
2411 * buffer has a background write in progress, we need to keep it
2412 * around to prevent it from being reconstituted and starting a second
2415 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2416 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2417 !(bp->b_vp->v_mount != NULL &&
2418 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2419 !vn_isdisk(bp->b_vp, NULL) && (bp->b_flags & B_DELWRI))) {
2420 vfs_vmio_invalidate(bp);
2424 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2425 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2427 bp->b_flags &= ~B_NOREUSE;
2428 if (bp->b_vp != NULL)
2433 * If the buffer has junk contents signal it and eventually
2434 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2437 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2438 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2439 bp->b_flags |= B_INVAL;
2440 if (bp->b_flags & B_INVAL) {
2441 if (bp->b_flags & B_DELWRI)
2447 buf_track(bp, __func__);
2449 /* buffers with no memory */
2450 if (bp->b_bufsize == 0) {
2454 /* buffers with junk contents */
2455 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2456 (bp->b_ioflags & BIO_ERROR)) {
2457 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2458 if (bp->b_vflags & BV_BKGRDINPROG)
2459 panic("losing buffer 2");
2460 qindex = QUEUE_CLEAN;
2461 bp->b_flags |= B_AGE;
2462 /* remaining buffers */
2463 } else if (bp->b_flags & B_DELWRI)
2464 qindex = QUEUE_DIRTY;
2466 qindex = QUEUE_CLEAN;
2468 binsfree(bp, qindex);
2470 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
2471 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2472 panic("brelse: not dirty");
2475 if (qindex == QUEUE_CLEAN)
2480 * Release a buffer back to the appropriate queue but do not try to free
2481 * it. The buffer is expected to be used again soon.
2483 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2484 * biodone() to requeue an async I/O on completion. It is also used when
2485 * known good buffers need to be requeued but we think we may need the data
2488 * XXX we should be able to leave the B_RELBUF hint set on completion.
2491 bqrelse(struct buf *bp)
2495 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2496 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2497 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2499 qindex = QUEUE_NONE;
2500 if (BUF_LOCKRECURSED(bp)) {
2501 /* do not release to free list */
2505 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2507 if (bp->b_flags & B_MANAGED) {
2508 if (bp->b_flags & B_REMFREE)
2513 /* buffers with stale but valid contents */
2514 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2515 BV_BKGRDERR)) == BV_BKGRDERR) {
2516 BO_LOCK(bp->b_bufobj);
2517 bp->b_vflags &= ~BV_BKGRDERR;
2518 BO_UNLOCK(bp->b_bufobj);
2519 qindex = QUEUE_DIRTY;
2521 if ((bp->b_flags & B_DELWRI) == 0 &&
2522 (bp->b_xflags & BX_VNDIRTY))
2523 panic("bqrelse: not dirty");
2524 if ((bp->b_flags & B_NOREUSE) != 0) {
2528 qindex = QUEUE_CLEAN;
2530 binsfree(bp, qindex);
2533 buf_track(bp, __func__);
2536 if (qindex == QUEUE_CLEAN)
2541 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2542 * restore bogus pages.
2545 vfs_vmio_iodone(struct buf *bp)
2551 int i, iosize, resid;
2554 obj = bp->b_bufobj->bo_object;
2555 KASSERT(obj->paging_in_progress >= bp->b_npages,
2556 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2557 obj->paging_in_progress, bp->b_npages));
2560 KASSERT(vp->v_holdcnt > 0,
2561 ("vfs_vmio_iodone: vnode %p has zero hold count", vp));
2562 KASSERT(vp->v_object != NULL,
2563 ("vfs_vmio_iodone: vnode %p has no vm_object", vp));
2565 foff = bp->b_offset;
2566 KASSERT(bp->b_offset != NOOFFSET,
2567 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2570 iosize = bp->b_bcount - bp->b_resid;
2571 VM_OBJECT_WLOCK(obj);
2572 for (i = 0; i < bp->b_npages; i++) {
2573 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2578 * cleanup bogus pages, restoring the originals
2581 if (m == bogus_page) {
2583 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2585 panic("biodone: page disappeared!");
2587 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2589 * In the write case, the valid and clean bits are
2590 * already changed correctly ( see bdwrite() ), so we
2591 * only need to do this here in the read case.
2593 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2594 resid)) == 0, ("vfs_vmio_iodone: page %p "
2595 "has unexpected dirty bits", m));
2596 vfs_page_set_valid(bp, foff, m);
2598 KASSERT(OFF_TO_IDX(foff) == m->pindex,
2599 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
2600 (intmax_t)foff, (uintmax_t)m->pindex));
2603 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2606 vm_object_pip_wakeupn(obj, bp->b_npages);
2607 VM_OBJECT_WUNLOCK(obj);
2608 if (bogus && buf_mapped(bp)) {
2609 BUF_CHECK_MAPPED(bp);
2610 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2611 bp->b_pages, bp->b_npages);
2616 * Unwire a page held by a buf and place it on the appropriate vm queue.
2619 vfs_vmio_unwire(struct buf *bp, vm_page_t m)
2624 if (vm_page_unwire_noq(m)) {
2626 * Determine if the page should be freed before adding
2627 * it to the inactive queue.
2629 if (m->valid == 0) {
2630 freed = !vm_page_busied(m);
2633 } else if ((bp->b_flags & B_DIRECT) != 0)
2634 freed = vm_page_try_to_free(m);
2639 * If the page is unlikely to be reused, let the
2640 * VM know. Otherwise, maintain LRU.
2642 if ((bp->b_flags & B_NOREUSE) != 0)
2643 vm_page_deactivate_noreuse(m);
2644 else if (m->queue == PQ_ACTIVE)
2645 vm_page_reference(m);
2646 else if (m->queue != PQ_INACTIVE)
2647 vm_page_deactivate(m);
2656 * Perform page invalidation when a buffer is released. The fully invalid
2657 * pages will be reclaimed later in vfs_vmio_truncate().
2660 vfs_vmio_invalidate(struct buf *bp)
2664 int i, resid, poffset, presid;
2666 if (buf_mapped(bp)) {
2667 BUF_CHECK_MAPPED(bp);
2668 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
2670 BUF_CHECK_UNMAPPED(bp);
2672 * Get the base offset and length of the buffer. Note that
2673 * in the VMIO case if the buffer block size is not
2674 * page-aligned then b_data pointer may not be page-aligned.
2675 * But our b_pages[] array *IS* page aligned.
2677 * block sizes less then DEV_BSIZE (usually 512) are not
2678 * supported due to the page granularity bits (m->valid,
2679 * m->dirty, etc...).
2681 * See man buf(9) for more information
2683 obj = bp->b_bufobj->bo_object;
2684 resid = bp->b_bufsize;
2685 poffset = bp->b_offset & PAGE_MASK;
2686 VM_OBJECT_WLOCK(obj);
2687 for (i = 0; i < bp->b_npages; i++) {
2689 if (m == bogus_page)
2690 panic("vfs_vmio_invalidate: Unexpected bogus page.");
2691 bp->b_pages[i] = NULL;
2693 presid = resid > (PAGE_SIZE - poffset) ?
2694 (PAGE_SIZE - poffset) : resid;
2695 KASSERT(presid >= 0, ("brelse: extra page"));
2696 while (vm_page_xbusied(m)) {
2698 VM_OBJECT_WUNLOCK(obj);
2699 vm_page_busy_sleep(m, "mbncsh", true);
2700 VM_OBJECT_WLOCK(obj);
2702 if (pmap_page_wired_mappings(m) == 0)
2703 vm_page_set_invalid(m, poffset, presid);
2704 vfs_vmio_unwire(bp, m);
2708 VM_OBJECT_WUNLOCK(obj);
2713 * Page-granular truncation of an existing VMIO buffer.
2716 vfs_vmio_truncate(struct buf *bp, int desiredpages)
2722 if (bp->b_npages == desiredpages)
2725 if (buf_mapped(bp)) {
2726 BUF_CHECK_MAPPED(bp);
2727 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
2728 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
2730 BUF_CHECK_UNMAPPED(bp);
2731 obj = bp->b_bufobj->bo_object;
2733 VM_OBJECT_WLOCK(obj);
2734 for (i = desiredpages; i < bp->b_npages; i++) {
2736 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
2737 bp->b_pages[i] = NULL;
2738 vfs_vmio_unwire(bp, m);
2741 VM_OBJECT_WUNLOCK(obj);
2742 bp->b_npages = desiredpages;
2746 * Byte granular extension of VMIO buffers.
2749 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
2752 * We are growing the buffer, possibly in a
2753 * byte-granular fashion.
2761 * Step 1, bring in the VM pages from the object, allocating
2762 * them if necessary. We must clear B_CACHE if these pages
2763 * are not valid for the range covered by the buffer.
2765 obj = bp->b_bufobj->bo_object;
2766 VM_OBJECT_WLOCK(obj);
2767 if (bp->b_npages < desiredpages) {
2769 * We must allocate system pages since blocking
2770 * here could interfere with paging I/O, no
2771 * matter which process we are.
2773 * Only exclusive busy can be tested here.
2774 * Blocking on shared busy might lead to
2775 * deadlocks once allocbuf() is called after
2776 * pages are vfs_busy_pages().
2778 (void)vm_page_grab_pages(obj,
2779 OFF_TO_IDX(bp->b_offset) + bp->b_npages,
2780 VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
2781 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
2782 &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
2783 bp->b_npages = desiredpages;
2787 * Step 2. We've loaded the pages into the buffer,
2788 * we have to figure out if we can still have B_CACHE
2789 * set. Note that B_CACHE is set according to the
2790 * byte-granular range ( bcount and size ), not the
2791 * aligned range ( newbsize ).
2793 * The VM test is against m->valid, which is DEV_BSIZE
2794 * aligned. Needless to say, the validity of the data
2795 * needs to also be DEV_BSIZE aligned. Note that this
2796 * fails with NFS if the server or some other client
2797 * extends the file's EOF. If our buffer is resized,
2798 * B_CACHE may remain set! XXX
2800 toff = bp->b_bcount;
2801 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2802 while ((bp->b_flags & B_CACHE) && toff < size) {
2805 if (tinc > (size - toff))
2807 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
2808 m = bp->b_pages[pi];
2809 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
2813 VM_OBJECT_WUNLOCK(obj);
2816 * Step 3, fixup the KVA pmap.
2821 BUF_CHECK_UNMAPPED(bp);
2825 * Check to see if a block at a particular lbn is available for a clustered
2829 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
2836 /* If the buf isn't in core skip it */
2837 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
2840 /* If the buf is busy we don't want to wait for it */
2841 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2844 /* Only cluster with valid clusterable delayed write buffers */
2845 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
2846 (B_DELWRI | B_CLUSTEROK))
2849 if (bpa->b_bufsize != size)
2853 * Check to see if it is in the expected place on disk and that the
2854 * block has been mapped.
2856 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
2866 * Implement clustered async writes for clearing out B_DELWRI buffers.
2867 * This is much better then the old way of writing only one buffer at
2868 * a time. Note that we may not be presented with the buffers in the
2869 * correct order, so we search for the cluster in both directions.
2872 vfs_bio_awrite(struct buf *bp)
2877 daddr_t lblkno = bp->b_lblkno;
2878 struct vnode *vp = bp->b_vp;
2886 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
2888 * right now we support clustered writing only to regular files. If
2889 * we find a clusterable block we could be in the middle of a cluster
2890 * rather then at the beginning.
2892 if ((vp->v_type == VREG) &&
2893 (vp->v_mount != 0) && /* Only on nodes that have the size info */
2894 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2896 size = vp->v_mount->mnt_stat.f_iosize;
2897 maxcl = MAXPHYS / size;
2900 for (i = 1; i < maxcl; i++)
2901 if (vfs_bio_clcheck(vp, size, lblkno + i,
2902 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2905 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2906 if (vfs_bio_clcheck(vp, size, lblkno - j,
2907 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2913 * this is a possible cluster write
2917 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2923 bp->b_flags |= B_ASYNC;
2925 * default (old) behavior, writing out only one block
2927 * XXX returns b_bufsize instead of b_bcount for nwritten?
2929 nwritten = bp->b_bufsize;
2938 * Allocate KVA for an empty buf header according to gbflags.
2941 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
2944 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
2946 * In order to keep fragmentation sane we only allocate kva
2947 * in BKVASIZE chunks. XXX with vmem we can do page size.
2949 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2951 if (maxsize != bp->b_kvasize &&
2952 bufkva_alloc(bp, maxsize, gbflags))
2961 * Find and initialize a new buffer header, freeing up existing buffers
2962 * in the bufqueues as necessary. The new buffer is returned locked.
2965 * We have insufficient buffer headers
2966 * We have insufficient buffer space
2967 * buffer_arena is too fragmented ( space reservation fails )
2968 * If we have to flush dirty buffers ( but we try to avoid this )
2970 * The caller is responsible for releasing the reserved bufspace after
2971 * allocbuf() is called.
2974 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
2977 bool metadata, reserved;
2980 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2981 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2982 if (!unmapped_buf_allowed)
2983 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2985 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2990 atomic_add_int(&getnewbufcalls, 1);
2993 if (reserved == false &&
2994 bufspace_reserve(maxsize, metadata) != 0)
2997 if ((bp = buf_alloc()) == NULL)
2999 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
3002 } while(buf_scan(false) == 0);
3005 atomic_subtract_long(&bufspace, maxsize);
3007 bp->b_flags |= B_INVAL;
3010 bufspace_wait(vp, gbflags, slpflag, slptimeo);
3018 * buffer flushing daemon. Buffers are normally flushed by the
3019 * update daemon but if it cannot keep up this process starts to
3020 * take the load in an attempt to prevent getnewbuf() from blocking.
3022 static struct kproc_desc buf_kp = {
3027 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3030 buf_flush(struct vnode *vp, int target)
3034 flushed = flushbufqueues(vp, target, 0);
3037 * Could not find any buffers without rollback
3038 * dependencies, so just write the first one
3039 * in the hopes of eventually making progress.
3041 if (vp != NULL && target > 2)
3043 flushbufqueues(vp, target, 1);
3054 * This process needs to be suspended prior to shutdown sync.
3056 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
3060 * This process is allowed to take the buffer cache to the limit
3062 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3066 mtx_unlock(&bdlock);
3068 kproc_suspend_check(bufdaemonproc);
3069 lodirty = lodirtybuffers;
3070 if (bd_speedupreq) {
3071 lodirty = numdirtybuffers / 2;
3075 * Do the flush. Limit the amount of in-transit I/O we
3076 * allow to build up, otherwise we would completely saturate
3079 while (numdirtybuffers > lodirty) {
3080 if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
3082 kern_yield(PRI_USER);
3086 * Only clear bd_request if we have reached our low water
3087 * mark. The buf_daemon normally waits 1 second and
3088 * then incrementally flushes any dirty buffers that have
3089 * built up, within reason.
3091 * If we were unable to hit our low water mark and couldn't
3092 * find any flushable buffers, we sleep for a short period
3093 * to avoid endless loops on unlockable buffers.
3096 if (numdirtybuffers <= lodirtybuffers) {
3098 * We reached our low water mark, reset the
3099 * request and sleep until we are needed again.
3100 * The sleep is just so the suspend code works.
3104 * Do an extra wakeup in case dirty threshold
3105 * changed via sysctl and the explicit transition
3106 * out of shortfall was missed.
3109 if (runningbufspace <= lorunningspace)
3111 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3114 * We couldn't find any flushable dirty buffers but
3115 * still have too many dirty buffers, we
3116 * have to sleep and try again. (rare)
3118 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3126 * Try to flush a buffer in the dirty queue. We must be careful to
3127 * free up B_INVAL buffers instead of write them, which NFS is
3128 * particularly sensitive to.
3130 static int flushwithdeps = 0;
3131 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
3132 0, "Number of buffers flushed with dependecies that require rollbacks");
3135 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
3137 struct buf *sentinel;
3148 queue = QUEUE_DIRTY;
3150 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3151 sentinel->b_qindex = QUEUE_SENTINEL;
3152 mtx_lock(&bqlocks[queue]);
3153 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
3154 mtx_unlock(&bqlocks[queue]);
3155 while (flushed != target) {
3157 mtx_lock(&bqlocks[queue]);
3158 bp = TAILQ_NEXT(sentinel, b_freelist);
3160 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3161 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
3164 mtx_unlock(&bqlocks[queue]);
3168 * Skip sentinels inserted by other invocations of the
3169 * flushbufqueues(), taking care to not reorder them.
3171 * Only flush the buffers that belong to the
3172 * vnode locked by the curthread.
3174 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3176 mtx_unlock(&bqlocks[queue]);
3179 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3180 mtx_unlock(&bqlocks[queue]);
3185 * BKGRDINPROG can only be set with the buf and bufobj
3186 * locks both held. We tolerate a race to clear it here.
3188 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3189 (bp->b_flags & B_DELWRI) == 0) {
3193 if (bp->b_flags & B_INVAL) {
3200 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3201 if (flushdeps == 0) {
3209 * We must hold the lock on a vnode before writing
3210 * one of its buffers. Otherwise we may confuse, or
3211 * in the case of a snapshot vnode, deadlock the
3214 * The lock order here is the reverse of the normal
3215 * of vnode followed by buf lock. This is ok because
3216 * the NOWAIT will prevent deadlock.
3219 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3225 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3227 ASSERT_VOP_LOCKED(vp, "getbuf");
3229 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3230 vn_lock(vp, LK_TRYUPGRADE);
3233 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3234 bp, bp->b_vp, bp->b_flags);
3235 if (curproc == bufdaemonproc) {
3242 vn_finished_write(mp);
3245 flushwithdeps += hasdeps;
3249 * Sleeping on runningbufspace while holding
3250 * vnode lock leads to deadlock.
3252 if (curproc == bufdaemonproc &&
3253 runningbufspace > hirunningspace)
3254 waitrunningbufspace();
3257 vn_finished_write(mp);
3260 mtx_lock(&bqlocks[queue]);
3261 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3262 mtx_unlock(&bqlocks[queue]);
3263 free(sentinel, M_TEMP);
3268 * Check to see if a block is currently memory resident.
3271 incore(struct bufobj *bo, daddr_t blkno)
3276 bp = gbincore(bo, blkno);
3282 * Returns true if no I/O is needed to access the
3283 * associated VM object. This is like incore except
3284 * it also hunts around in the VM system for the data.
3288 inmem(struct vnode * vp, daddr_t blkno)
3291 vm_offset_t toff, tinc, size;
3295 ASSERT_VOP_LOCKED(vp, "inmem");
3297 if (incore(&vp->v_bufobj, blkno))
3299 if (vp->v_mount == NULL)
3306 if (size > vp->v_mount->mnt_stat.f_iosize)
3307 size = vp->v_mount->mnt_stat.f_iosize;
3308 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3310 VM_OBJECT_RLOCK(obj);
3311 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3312 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
3316 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3317 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3318 if (vm_page_is_valid(m,
3319 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
3322 VM_OBJECT_RUNLOCK(obj);
3326 VM_OBJECT_RUNLOCK(obj);
3331 * Set the dirty range for a buffer based on the status of the dirty
3332 * bits in the pages comprising the buffer. The range is limited
3333 * to the size of the buffer.
3335 * Tell the VM system that the pages associated with this buffer
3336 * are clean. This is used for delayed writes where the data is
3337 * going to go to disk eventually without additional VM intevention.
3339 * Note that while we only really need to clean through to b_bcount, we
3340 * just go ahead and clean through to b_bufsize.
3343 vfs_clean_pages_dirty_buf(struct buf *bp)
3345 vm_ooffset_t foff, noff, eoff;
3349 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3352 foff = bp->b_offset;
3353 KASSERT(bp->b_offset != NOOFFSET,
3354 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3356 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3357 vfs_drain_busy_pages(bp);
3358 vfs_setdirty_locked_object(bp);
3359 for (i = 0; i < bp->b_npages; i++) {
3360 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3362 if (eoff > bp->b_offset + bp->b_bufsize)
3363 eoff = bp->b_offset + bp->b_bufsize;
3365 vfs_page_set_validclean(bp, foff, m);
3366 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3369 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3373 vfs_setdirty_locked_object(struct buf *bp)
3378 object = bp->b_bufobj->bo_object;
3379 VM_OBJECT_ASSERT_WLOCKED(object);
3382 * We qualify the scan for modified pages on whether the
3383 * object has been flushed yet.
3385 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
3386 vm_offset_t boffset;
3387 vm_offset_t eoffset;
3390 * test the pages to see if they have been modified directly
3391 * by users through the VM system.
3393 for (i = 0; i < bp->b_npages; i++)
3394 vm_page_test_dirty(bp->b_pages[i]);
3397 * Calculate the encompassing dirty range, boffset and eoffset,
3398 * (eoffset - boffset) bytes.
3401 for (i = 0; i < bp->b_npages; i++) {
3402 if (bp->b_pages[i]->dirty)
3405 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3407 for (i = bp->b_npages - 1; i >= 0; --i) {
3408 if (bp->b_pages[i]->dirty) {
3412 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3415 * Fit it to the buffer.
3418 if (eoffset > bp->b_bcount)
3419 eoffset = bp->b_bcount;
3422 * If we have a good dirty range, merge with the existing
3426 if (boffset < eoffset) {
3427 if (bp->b_dirtyoff > boffset)
3428 bp->b_dirtyoff = boffset;
3429 if (bp->b_dirtyend < eoffset)
3430 bp->b_dirtyend = eoffset;
3436 * Allocate the KVA mapping for an existing buffer.
3437 * If an unmapped buffer is provided but a mapped buffer is requested, take
3438 * also care to properly setup mappings between pages and KVA.
3441 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3443 int bsize, maxsize, need_mapping, need_kva;
3446 need_mapping = bp->b_data == unmapped_buf &&
3447 (gbflags & GB_UNMAPPED) == 0;
3448 need_kva = bp->b_kvabase == unmapped_buf &&
3449 bp->b_data == unmapped_buf &&
3450 (gbflags & GB_KVAALLOC) != 0;
3451 if (!need_mapping && !need_kva)
3454 BUF_CHECK_UNMAPPED(bp);
3456 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3458 * Buffer is not mapped, but the KVA was already
3459 * reserved at the time of the instantiation. Use the
3466 * Calculate the amount of the address space we would reserve
3467 * if the buffer was mapped.
3469 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3470 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3471 offset = blkno * bsize;
3472 maxsize = size + (offset & PAGE_MASK);
3473 maxsize = imax(maxsize, bsize);
3475 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3476 if ((gbflags & GB_NOWAIT_BD) != 0) {
3478 * XXXKIB: defragmentation cannot
3479 * succeed, not sure what else to do.
3481 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3483 atomic_add_int(&mappingrestarts, 1);
3484 bufspace_wait(bp->b_vp, gbflags, 0, 0);
3488 /* b_offset is handled by bpmap_qenter. */
3489 bp->b_data = bp->b_kvabase;
3490 BUF_CHECK_MAPPED(bp);
3498 * Get a block given a specified block and offset into a file/device.
3499 * The buffers B_DONE bit will be cleared on return, making it almost
3500 * ready for an I/O initiation. B_INVAL may or may not be set on
3501 * return. The caller should clear B_INVAL prior to initiating a
3504 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3505 * an existing buffer.
3507 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3508 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3509 * and then cleared based on the backing VM. If the previous buffer is
3510 * non-0-sized but invalid, B_CACHE will be cleared.
3512 * If getblk() must create a new buffer, the new buffer is returned with
3513 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3514 * case it is returned with B_INVAL clear and B_CACHE set based on the
3517 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3518 * B_CACHE bit is clear.
3520 * What this means, basically, is that the caller should use B_CACHE to
3521 * determine whether the buffer is fully valid or not and should clear
3522 * B_INVAL prior to issuing a read. If the caller intends to validate
3523 * the buffer by loading its data area with something, the caller needs
3524 * to clear B_INVAL. If the caller does this without issuing an I/O,
3525 * the caller should set B_CACHE ( as an optimization ), else the caller
3526 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3527 * a write attempt or if it was a successful read. If the caller
3528 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3529 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3532 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3537 int bsize, error, maxsize, vmio;
3540 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3541 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3542 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3543 ASSERT_VOP_LOCKED(vp, "getblk");
3544 if (size > maxbcachebuf)
3545 panic("getblk: size(%d) > maxbcachebuf(%d)\n", size,
3547 if (!unmapped_buf_allowed)
3548 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3553 bp = gbincore(bo, blkno);
3557 * Buffer is in-core. If the buffer is not busy nor managed,
3558 * it must be on a queue.
3560 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3562 if (flags & GB_LOCK_NOWAIT)
3563 lockflags |= LK_NOWAIT;
3565 error = BUF_TIMELOCK(bp, lockflags,
3566 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3569 * If we slept and got the lock we have to restart in case
3570 * the buffer changed identities.
3572 if (error == ENOLCK)
3574 /* We timed out or were interrupted. */
3577 /* If recursed, assume caller knows the rules. */
3578 else if (BUF_LOCKRECURSED(bp))
3582 * The buffer is locked. B_CACHE is cleared if the buffer is
3583 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3584 * and for a VMIO buffer B_CACHE is adjusted according to the
3587 if (bp->b_flags & B_INVAL)
3588 bp->b_flags &= ~B_CACHE;
3589 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3590 bp->b_flags |= B_CACHE;
3591 if (bp->b_flags & B_MANAGED)
3592 MPASS(bp->b_qindex == QUEUE_NONE);
3597 * check for size inconsistencies for non-VMIO case.
3599 if (bp->b_bcount != size) {
3600 if ((bp->b_flags & B_VMIO) == 0 ||
3601 (size > bp->b_kvasize)) {
3602 if (bp->b_flags & B_DELWRI) {
3603 bp->b_flags |= B_NOCACHE;
3606 if (LIST_EMPTY(&bp->b_dep)) {
3607 bp->b_flags |= B_RELBUF;
3610 bp->b_flags |= B_NOCACHE;
3619 * Handle the case of unmapped buffer which should
3620 * become mapped, or the buffer for which KVA
3621 * reservation is requested.
3623 bp_unmapped_get_kva(bp, blkno, size, flags);
3626 * If the size is inconsistent in the VMIO case, we can resize
3627 * the buffer. This might lead to B_CACHE getting set or
3628 * cleared. If the size has not changed, B_CACHE remains
3629 * unchanged from its previous state.
3633 KASSERT(bp->b_offset != NOOFFSET,
3634 ("getblk: no buffer offset"));
3637 * A buffer with B_DELWRI set and B_CACHE clear must
3638 * be committed before we can return the buffer in
3639 * order to prevent the caller from issuing a read
3640 * ( due to B_CACHE not being set ) and overwriting
3643 * Most callers, including NFS and FFS, need this to
3644 * operate properly either because they assume they
3645 * can issue a read if B_CACHE is not set, or because
3646 * ( for example ) an uncached B_DELWRI might loop due
3647 * to softupdates re-dirtying the buffer. In the latter
3648 * case, B_CACHE is set after the first write completes,
3649 * preventing further loops.
3650 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3651 * above while extending the buffer, we cannot allow the
3652 * buffer to remain with B_CACHE set after the write
3653 * completes or it will represent a corrupt state. To
3654 * deal with this we set B_NOCACHE to scrap the buffer
3657 * We might be able to do something fancy, like setting
3658 * B_CACHE in bwrite() except if B_DELWRI is already set,
3659 * so the below call doesn't set B_CACHE, but that gets real
3660 * confusing. This is much easier.
3663 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3664 bp->b_flags |= B_NOCACHE;
3668 bp->b_flags &= ~B_DONE;
3671 * Buffer is not in-core, create new buffer. The buffer
3672 * returned by getnewbuf() is locked. Note that the returned
3673 * buffer is also considered valid (not marked B_INVAL).
3677 * If the user does not want us to create the buffer, bail out
3680 if (flags & GB_NOCREAT)
3682 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3685 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3686 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3687 offset = blkno * bsize;
3688 vmio = vp->v_object != NULL;
3690 maxsize = size + (offset & PAGE_MASK);
3693 /* Do not allow non-VMIO notmapped buffers. */
3694 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3696 maxsize = imax(maxsize, bsize);
3698 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
3700 if (slpflag || slptimeo)
3703 * XXX This is here until the sleep path is diagnosed
3704 * enough to work under very low memory conditions.
3706 * There's an issue on low memory, 4BSD+non-preempt
3707 * systems (eg MIPS routers with 32MB RAM) where buffer
3708 * exhaustion occurs without sleeping for buffer
3709 * reclaimation. This just sticks in a loop and
3710 * constantly attempts to allocate a buffer, which
3711 * hits exhaustion and tries to wakeup bufdaemon.
3712 * This never happens because we never yield.
3714 * The real solution is to identify and fix these cases
3715 * so we aren't effectively busy-waiting in a loop
3716 * until the reclaimation path has cycles to run.
3718 kern_yield(PRI_USER);
3723 * This code is used to make sure that a buffer is not
3724 * created while the getnewbuf routine is blocked.
3725 * This can be a problem whether the vnode is locked or not.
3726 * If the buffer is created out from under us, we have to
3727 * throw away the one we just created.
3729 * Note: this must occur before we associate the buffer
3730 * with the vp especially considering limitations in
3731 * the splay tree implementation when dealing with duplicate
3735 if (gbincore(bo, blkno)) {
3737 bp->b_flags |= B_INVAL;
3739 bufspace_release(maxsize);
3744 * Insert the buffer into the hash, so that it can
3745 * be found by incore.
3747 bp->b_blkno = bp->b_lblkno = blkno;
3748 bp->b_offset = offset;
3753 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3754 * buffer size starts out as 0, B_CACHE will be set by
3755 * allocbuf() for the VMIO case prior to it testing the
3756 * backing store for validity.
3760 bp->b_flags |= B_VMIO;
3761 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3762 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3763 bp, vp->v_object, bp->b_bufobj->bo_object));
3765 bp->b_flags &= ~B_VMIO;
3766 KASSERT(bp->b_bufobj->bo_object == NULL,
3767 ("ARGH! has b_bufobj->bo_object %p %p\n",
3768 bp, bp->b_bufobj->bo_object));
3769 BUF_CHECK_MAPPED(bp);
3773 bufspace_release(maxsize);
3774 bp->b_flags &= ~B_DONE;
3776 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3777 BUF_ASSERT_HELD(bp);
3779 buf_track(bp, __func__);
3780 KASSERT(bp->b_bufobj == bo,
3781 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3786 * Get an empty, disassociated buffer of given size. The buffer is initially
3790 geteblk(int size, int flags)
3795 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3796 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
3797 if ((flags & GB_NOWAIT_BD) &&
3798 (curthread->td_pflags & TDP_BUFNEED) != 0)
3802 bufspace_release(maxsize);
3803 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3804 BUF_ASSERT_HELD(bp);
3809 * Truncate the backing store for a non-vmio buffer.
3812 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
3815 if (bp->b_flags & B_MALLOC) {
3817 * malloced buffers are not shrunk
3819 if (newbsize == 0) {
3820 bufmallocadjust(bp, 0);
3821 free(bp->b_data, M_BIOBUF);
3822 bp->b_data = bp->b_kvabase;
3823 bp->b_flags &= ~B_MALLOC;
3827 vm_hold_free_pages(bp, newbsize);
3828 bufspace_adjust(bp, newbsize);
3832 * Extend the backing for a non-VMIO buffer.
3835 vfs_nonvmio_extend(struct buf *bp, int newbsize)
3841 * We only use malloced memory on the first allocation.
3842 * and revert to page-allocated memory when the buffer
3845 * There is a potential smp race here that could lead
3846 * to bufmallocspace slightly passing the max. It
3847 * is probably extremely rare and not worth worrying
3850 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
3851 bufmallocspace < maxbufmallocspace) {
3852 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
3853 bp->b_flags |= B_MALLOC;
3854 bufmallocadjust(bp, newbsize);
3859 * If the buffer is growing on its other-than-first
3860 * allocation then we revert to the page-allocation
3865 if (bp->b_flags & B_MALLOC) {
3866 origbuf = bp->b_data;
3867 origbufsize = bp->b_bufsize;
3868 bp->b_data = bp->b_kvabase;
3869 bufmallocadjust(bp, 0);
3870 bp->b_flags &= ~B_MALLOC;
3871 newbsize = round_page(newbsize);
3873 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
3874 (vm_offset_t) bp->b_data + newbsize);
3875 if (origbuf != NULL) {
3876 bcopy(origbuf, bp->b_data, origbufsize);
3877 free(origbuf, M_BIOBUF);
3879 bufspace_adjust(bp, newbsize);
3883 * This code constitutes the buffer memory from either anonymous system
3884 * memory (in the case of non-VMIO operations) or from an associated
3885 * VM object (in the case of VMIO operations). This code is able to
3886 * resize a buffer up or down.
3888 * Note that this code is tricky, and has many complications to resolve
3889 * deadlock or inconsistent data situations. Tread lightly!!!
3890 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3891 * the caller. Calling this code willy nilly can result in the loss of data.
3893 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3894 * B_CACHE for the non-VMIO case.
3897 allocbuf(struct buf *bp, int size)
3901 BUF_ASSERT_HELD(bp);
3903 if (bp->b_bcount == size)
3906 if (bp->b_kvasize != 0 && bp->b_kvasize < size)
3907 panic("allocbuf: buffer too small");
3909 newbsize = roundup2(size, DEV_BSIZE);
3910 if ((bp->b_flags & B_VMIO) == 0) {
3911 if ((bp->b_flags & B_MALLOC) == 0)
3912 newbsize = round_page(newbsize);
3914 * Just get anonymous memory from the kernel. Don't
3915 * mess with B_CACHE.
3917 if (newbsize < bp->b_bufsize)
3918 vfs_nonvmio_truncate(bp, newbsize);
3919 else if (newbsize > bp->b_bufsize)
3920 vfs_nonvmio_extend(bp, newbsize);
3924 desiredpages = (size == 0) ? 0 :
3925 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3927 if (bp->b_flags & B_MALLOC)
3928 panic("allocbuf: VMIO buffer can't be malloced");
3930 * Set B_CACHE initially if buffer is 0 length or will become
3933 if (size == 0 || bp->b_bufsize == 0)
3934 bp->b_flags |= B_CACHE;
3936 if (newbsize < bp->b_bufsize)
3937 vfs_vmio_truncate(bp, desiredpages);
3938 /* XXX This looks as if it should be newbsize > b_bufsize */
3939 else if (size > bp->b_bcount)
3940 vfs_vmio_extend(bp, desiredpages, size);
3941 bufspace_adjust(bp, newbsize);
3943 bp->b_bcount = size; /* requested buffer size. */
3947 extern int inflight_transient_maps;
3950 biodone(struct bio *bp)
3953 void (*done)(struct bio *);
3954 vm_offset_t start, end;
3956 biotrack(bp, __func__);
3957 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3958 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3959 bp->bio_flags |= BIO_UNMAPPED;
3960 start = trunc_page((vm_offset_t)bp->bio_data);
3961 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3962 bp->bio_data = unmapped_buf;
3963 pmap_qremove(start, atop(end - start));
3964 vmem_free(transient_arena, start, end - start);
3965 atomic_add_int(&inflight_transient_maps, -1);
3967 done = bp->bio_done;
3969 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3971 bp->bio_flags |= BIO_DONE;
3979 * Wait for a BIO to finish.
3982 biowait(struct bio *bp, const char *wchan)
3986 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3988 while ((bp->bio_flags & BIO_DONE) == 0)
3989 msleep(bp, mtxp, PRIBIO, wchan, 0);
3991 if (bp->bio_error != 0)
3992 return (bp->bio_error);
3993 if (!(bp->bio_flags & BIO_ERROR))
3999 biofinish(struct bio *bp, struct devstat *stat, int error)
4003 bp->bio_error = error;
4004 bp->bio_flags |= BIO_ERROR;
4007 devstat_end_transaction_bio(stat, bp);
4011 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4013 biotrack_buf(struct bio *bp, const char *location)
4016 buf_track(bp->bio_track_bp, location);
4023 * Wait for buffer I/O completion, returning error status. The buffer
4024 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
4025 * error and cleared.
4028 bufwait(struct buf *bp)
4030 if (bp->b_iocmd == BIO_READ)
4031 bwait(bp, PRIBIO, "biord");
4033 bwait(bp, PRIBIO, "biowr");
4034 if (bp->b_flags & B_EINTR) {
4035 bp->b_flags &= ~B_EINTR;
4038 if (bp->b_ioflags & BIO_ERROR) {
4039 return (bp->b_error ? bp->b_error : EIO);
4048 * Finish I/O on a buffer, optionally calling a completion function.
4049 * This is usually called from an interrupt so process blocking is
4052 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4053 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
4054 * assuming B_INVAL is clear.
4056 * For the VMIO case, we set B_CACHE if the op was a read and no
4057 * read error occurred, or if the op was a write. B_CACHE is never
4058 * set if the buffer is invalid or otherwise uncacheable.
4060 * biodone does not mess with B_INVAL, allowing the I/O routine or the
4061 * initiator to leave B_INVAL set to brelse the buffer out of existence
4062 * in the biodone routine.
4065 bufdone(struct buf *bp)
4067 struct bufobj *dropobj;
4068 void (*biodone)(struct buf *);
4070 buf_track(bp, __func__);
4071 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4074 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4075 BUF_ASSERT_HELD(bp);
4077 runningbufwakeup(bp);
4078 if (bp->b_iocmd == BIO_WRITE)
4079 dropobj = bp->b_bufobj;
4080 /* call optional completion function if requested */
4081 if (bp->b_iodone != NULL) {
4082 biodone = bp->b_iodone;
4083 bp->b_iodone = NULL;
4086 bufobj_wdrop(dropobj);
4093 bufobj_wdrop(dropobj);
4097 bufdone_finish(struct buf *bp)
4099 BUF_ASSERT_HELD(bp);
4101 if (!LIST_EMPTY(&bp->b_dep))
4104 if (bp->b_flags & B_VMIO) {
4106 * Set B_CACHE if the op was a normal read and no error
4107 * occurred. B_CACHE is set for writes in the b*write()
4110 if (bp->b_iocmd == BIO_READ &&
4111 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4112 !(bp->b_ioflags & BIO_ERROR))
4113 bp->b_flags |= B_CACHE;
4114 vfs_vmio_iodone(bp);
4116 if ((bp->b_flags & B_CKHASH) != 0) {
4117 KASSERT(bp->b_iocmd == BIO_READ,
4118 ("bufdone_finish: b_iocmd %d not BIO_READ", bp->b_iocmd));
4119 KASSERT(buf_mapped(bp),
4120 ("bufdone_finish: bp %p not mapped", bp));
4121 (*bp->b_ckhashcalc)(bp);
4125 * For asynchronous completions, release the buffer now. The brelse
4126 * will do a wakeup there if necessary - so no need to do a wakeup
4127 * here in the async case. The sync case always needs to do a wakeup.
4129 if (bp->b_flags & B_ASYNC) {
4130 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4131 (bp->b_ioflags & BIO_ERROR))
4140 * This routine is called in lieu of iodone in the case of
4141 * incomplete I/O. This keeps the busy status for pages
4145 vfs_unbusy_pages(struct buf *bp)
4151 runningbufwakeup(bp);
4152 if (!(bp->b_flags & B_VMIO))
4155 obj = bp->b_bufobj->bo_object;
4156 VM_OBJECT_WLOCK(obj);
4157 for (i = 0; i < bp->b_npages; i++) {
4159 if (m == bogus_page) {
4160 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4162 panic("vfs_unbusy_pages: page missing\n");
4164 if (buf_mapped(bp)) {
4165 BUF_CHECK_MAPPED(bp);
4166 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4167 bp->b_pages, bp->b_npages);
4169 BUF_CHECK_UNMAPPED(bp);
4173 vm_object_pip_wakeupn(obj, bp->b_npages);
4174 VM_OBJECT_WUNLOCK(obj);
4178 * vfs_page_set_valid:
4180 * Set the valid bits in a page based on the supplied offset. The
4181 * range is restricted to the buffer's size.
4183 * This routine is typically called after a read completes.
4186 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4191 * Compute the end offset, eoff, such that [off, eoff) does not span a
4192 * page boundary and eoff is not greater than the end of the buffer.
4193 * The end of the buffer, in this case, is our file EOF, not the
4194 * allocation size of the buffer.
4196 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4197 if (eoff > bp->b_offset + bp->b_bcount)
4198 eoff = bp->b_offset + bp->b_bcount;
4201 * Set valid range. This is typically the entire buffer and thus the
4205 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4209 * vfs_page_set_validclean:
4211 * Set the valid bits and clear the dirty bits in a page based on the
4212 * supplied offset. The range is restricted to the buffer's size.
4215 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4217 vm_ooffset_t soff, eoff;
4220 * Start and end offsets in buffer. eoff - soff may not cross a
4221 * page boundary or cross the end of the buffer. The end of the
4222 * buffer, in this case, is our file EOF, not the allocation size
4226 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4227 if (eoff > bp->b_offset + bp->b_bcount)
4228 eoff = bp->b_offset + bp->b_bcount;
4231 * Set valid range. This is typically the entire buffer and thus the
4235 vm_page_set_validclean(
4237 (vm_offset_t) (soff & PAGE_MASK),
4238 (vm_offset_t) (eoff - soff)
4244 * Ensure that all buffer pages are not exclusive busied. If any page is
4245 * exclusive busy, drain it.
4248 vfs_drain_busy_pages(struct buf *bp)
4253 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4255 for (i = 0; i < bp->b_npages; i++) {
4257 if (vm_page_xbusied(m)) {
4258 for (; last_busied < i; last_busied++)
4259 vm_page_sbusy(bp->b_pages[last_busied]);
4260 while (vm_page_xbusied(m)) {
4262 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4263 vm_page_busy_sleep(m, "vbpage", true);
4264 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4268 for (i = 0; i < last_busied; i++)
4269 vm_page_sunbusy(bp->b_pages[i]);
4273 * This routine is called before a device strategy routine.
4274 * It is used to tell the VM system that paging I/O is in
4275 * progress, and treat the pages associated with the buffer
4276 * almost as being exclusive busy. Also the object paging_in_progress
4277 * flag is handled to make sure that the object doesn't become
4280 * Since I/O has not been initiated yet, certain buffer flags
4281 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4282 * and should be ignored.
4285 vfs_busy_pages(struct buf *bp, int clear_modify)
4293 if (!(bp->b_flags & B_VMIO))
4296 obj = bp->b_bufobj->bo_object;
4297 foff = bp->b_offset;
4298 KASSERT(bp->b_offset != NOOFFSET,
4299 ("vfs_busy_pages: no buffer offset"));
4300 VM_OBJECT_WLOCK(obj);
4301 vfs_drain_busy_pages(bp);
4302 if (bp->b_bufsize != 0)
4303 vfs_setdirty_locked_object(bp);
4305 for (i = 0; i < bp->b_npages; i++) {
4308 if ((bp->b_flags & B_CLUSTER) == 0) {
4309 vm_object_pip_add(obj, 1);
4313 * When readying a buffer for a read ( i.e
4314 * clear_modify == 0 ), it is important to do
4315 * bogus_page replacement for valid pages in
4316 * partially instantiated buffers. Partially
4317 * instantiated buffers can, in turn, occur when
4318 * reconstituting a buffer from its VM backing store
4319 * base. We only have to do this if B_CACHE is
4320 * clear ( which causes the I/O to occur in the
4321 * first place ). The replacement prevents the read
4322 * I/O from overwriting potentially dirty VM-backed
4323 * pages. XXX bogus page replacement is, uh, bogus.
4324 * It may not work properly with small-block devices.
4325 * We need to find a better way.
4328 pmap_remove_write(m);
4329 vfs_page_set_validclean(bp, foff, m);
4330 } else if (m->valid == VM_PAGE_BITS_ALL &&
4331 (bp->b_flags & B_CACHE) == 0) {
4332 bp->b_pages[i] = bogus_page;
4335 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4337 VM_OBJECT_WUNLOCK(obj);
4338 if (bogus && buf_mapped(bp)) {
4339 BUF_CHECK_MAPPED(bp);
4340 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4341 bp->b_pages, bp->b_npages);
4346 * vfs_bio_set_valid:
4348 * Set the range within the buffer to valid. The range is
4349 * relative to the beginning of the buffer, b_offset. Note that
4350 * b_offset itself may be offset from the beginning of the first
4354 vfs_bio_set_valid(struct buf *bp, int base, int size)
4359 if (!(bp->b_flags & B_VMIO))
4363 * Fixup base to be relative to beginning of first page.
4364 * Set initial n to be the maximum number of bytes in the
4365 * first page that can be validated.
4367 base += (bp->b_offset & PAGE_MASK);
4368 n = PAGE_SIZE - (base & PAGE_MASK);
4370 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4371 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4375 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4380 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4386 * If the specified buffer is a non-VMIO buffer, clear the entire
4387 * buffer. If the specified buffer is a VMIO buffer, clear and
4388 * validate only the previously invalid portions of the buffer.
4389 * This routine essentially fakes an I/O, so we need to clear
4390 * BIO_ERROR and B_INVAL.
4392 * Note that while we only theoretically need to clear through b_bcount,
4393 * we go ahead and clear through b_bufsize.
4396 vfs_bio_clrbuf(struct buf *bp)
4398 int i, j, mask, sa, ea, slide;
4400 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4404 bp->b_flags &= ~B_INVAL;
4405 bp->b_ioflags &= ~BIO_ERROR;
4406 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4407 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4408 (bp->b_offset & PAGE_MASK) == 0) {
4409 if (bp->b_pages[0] == bogus_page)
4411 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4412 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4413 if ((bp->b_pages[0]->valid & mask) == mask)
4415 if ((bp->b_pages[0]->valid & mask) == 0) {
4416 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4417 bp->b_pages[0]->valid |= mask;
4421 sa = bp->b_offset & PAGE_MASK;
4423 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4424 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4425 ea = slide & PAGE_MASK;
4428 if (bp->b_pages[i] == bogus_page)
4431 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4432 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4433 if ((bp->b_pages[i]->valid & mask) == mask)
4435 if ((bp->b_pages[i]->valid & mask) == 0)
4436 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4438 for (; sa < ea; sa += DEV_BSIZE, j++) {
4439 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4440 pmap_zero_page_area(bp->b_pages[i],
4445 bp->b_pages[i]->valid |= mask;
4448 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4453 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4458 if (buf_mapped(bp)) {
4459 BUF_CHECK_MAPPED(bp);
4460 bzero(bp->b_data + base, size);
4462 BUF_CHECK_UNMAPPED(bp);
4463 n = PAGE_SIZE - (base & PAGE_MASK);
4464 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4468 pmap_zero_page_area(m, base & PAGE_MASK, n);
4477 * Update buffer flags based on I/O request parameters, optionally releasing the
4478 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM,
4479 * where they may be placed on a page queue (VMIO) or freed immediately (direct
4480 * I/O). Otherwise the buffer is released to the cache.
4483 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4486 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4487 ("buf %p non-VMIO noreuse", bp));
4489 if ((ioflag & IO_DIRECT) != 0)
4490 bp->b_flags |= B_DIRECT;
4491 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4492 bp->b_flags |= B_RELBUF;
4493 if ((ioflag & IO_NOREUSE) != 0)
4494 bp->b_flags |= B_NOREUSE;
4502 vfs_bio_brelse(struct buf *bp, int ioflag)
4505 b_io_dismiss(bp, ioflag, true);
4509 vfs_bio_set_flags(struct buf *bp, int ioflag)
4512 b_io_dismiss(bp, ioflag, false);
4516 * vm_hold_load_pages and vm_hold_free_pages get pages into
4517 * a buffers address space. The pages are anonymous and are
4518 * not associated with a file object.
4521 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4527 BUF_CHECK_MAPPED(bp);
4529 to = round_page(to);
4530 from = round_page(from);
4531 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4533 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4535 * note: must allocate system pages since blocking here
4536 * could interfere with paging I/O, no matter which
4539 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4540 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) |
4542 pmap_qenter(pg, &p, 1);
4543 bp->b_pages[index] = p;
4545 bp->b_npages = index;
4548 /* Return pages associated with this buf to the vm system */
4550 vm_hold_free_pages(struct buf *bp, int newbsize)
4554 int index, newnpages;
4556 BUF_CHECK_MAPPED(bp);
4558 from = round_page((vm_offset_t)bp->b_data + newbsize);
4559 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4560 if (bp->b_npages > newnpages)
4561 pmap_qremove(from, bp->b_npages - newnpages);
4562 for (index = newnpages; index < bp->b_npages; index++) {
4563 p = bp->b_pages[index];
4564 bp->b_pages[index] = NULL;
4568 atomic_subtract_int(&vm_cnt.v_wire_count, bp->b_npages - newnpages);
4569 bp->b_npages = newnpages;
4573 * Map an IO request into kernel virtual address space.
4575 * All requests are (re)mapped into kernel VA space.
4576 * Notice that we use b_bufsize for the size of the buffer
4577 * to be mapped. b_bcount might be modified by the driver.
4579 * Note that even if the caller determines that the address space should
4580 * be valid, a race or a smaller-file mapped into a larger space may
4581 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4582 * check the return value.
4584 * This function only works with pager buffers.
4587 vmapbuf(struct buf *bp, int mapbuf)
4592 if (bp->b_bufsize < 0)
4594 prot = VM_PROT_READ;
4595 if (bp->b_iocmd == BIO_READ)
4596 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4597 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4598 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4599 btoc(MAXPHYS))) < 0)
4601 bp->b_npages = pidx;
4602 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4603 if (mapbuf || !unmapped_buf_allowed) {
4604 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
4605 bp->b_data = bp->b_kvabase + bp->b_offset;
4607 bp->b_data = unmapped_buf;
4612 * Free the io map PTEs associated with this IO operation.
4613 * We also invalidate the TLB entries and restore the original b_addr.
4615 * This function only works with pager buffers.
4618 vunmapbuf(struct buf *bp)
4622 npages = bp->b_npages;
4624 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4625 vm_page_unhold_pages(bp->b_pages, npages);
4627 bp->b_data = unmapped_buf;
4631 bdone(struct buf *bp)
4635 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4637 bp->b_flags |= B_DONE;
4643 bwait(struct buf *bp, u_char pri, const char *wchan)
4647 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4649 while ((bp->b_flags & B_DONE) == 0)
4650 msleep(bp, mtxp, pri, wchan, 0);
4655 bufsync(struct bufobj *bo, int waitfor)
4658 return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
4662 bufstrategy(struct bufobj *bo, struct buf *bp)
4668 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4669 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4670 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4671 i = VOP_STRATEGY(vp, bp);
4672 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4676 bufobj_wrefl(struct bufobj *bo)
4679 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4680 ASSERT_BO_WLOCKED(bo);
4685 bufobj_wref(struct bufobj *bo)
4688 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4695 bufobj_wdrop(struct bufobj *bo)
4698 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4700 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4701 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4702 bo->bo_flag &= ~BO_WWAIT;
4703 wakeup(&bo->bo_numoutput);
4709 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4713 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4714 ASSERT_BO_WLOCKED(bo);
4716 while (bo->bo_numoutput) {
4717 bo->bo_flag |= BO_WWAIT;
4718 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4719 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4727 * Set bio_data or bio_ma for struct bio from the struct buf.
4730 bdata2bio(struct buf *bp, struct bio *bip)
4733 if (!buf_mapped(bp)) {
4734 KASSERT(unmapped_buf_allowed, ("unmapped"));
4735 bip->bio_ma = bp->b_pages;
4736 bip->bio_ma_n = bp->b_npages;
4737 bip->bio_data = unmapped_buf;
4738 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4739 bip->bio_flags |= BIO_UNMAPPED;
4740 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4741 PAGE_SIZE == bp->b_npages,
4742 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4743 (long long)bip->bio_length, bip->bio_ma_n));
4745 bip->bio_data = bp->b_data;
4751 * The MIPS pmap code currently doesn't handle aliased pages.
4752 * The VIPT caches may not handle page aliasing themselves, leading
4753 * to data corruption.
4755 * As such, this code makes a system extremely unhappy if said
4756 * system doesn't support unaliasing the above situation in hardware.
4757 * Some "recent" systems (eg some mips24k/mips74k cores) don't enable
4758 * this feature at build time, so it has to be handled in software.
4760 * Once the MIPS pmap/cache code grows to support this function on
4761 * earlier chips, it should be flipped back off.
4764 static int buf_pager_relbuf = 1;
4766 static int buf_pager_relbuf = 0;
4768 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
4769 &buf_pager_relbuf, 0,
4770 "Make buffer pager release buffers after reading");
4773 * The buffer pager. It uses buffer reads to validate pages.
4775 * In contrast to the generic local pager from vm/vnode_pager.c, this
4776 * pager correctly and easily handles volumes where the underlying
4777 * device block size is greater than the machine page size. The
4778 * buffer cache transparently extends the requested page run to be
4779 * aligned at the block boundary, and does the necessary bogus page
4780 * replacements in the addends to avoid obliterating already valid
4783 * The only non-trivial issue is that the exclusive busy state for
4784 * pages, which is assumed by the vm_pager_getpages() interface, is
4785 * incompatible with the VMIO buffer cache's desire to share-busy the
4786 * pages. This function performs a trivial downgrade of the pages'
4787 * state before reading buffers, and a less trivial upgrade from the
4788 * shared-busy to excl-busy state after the read.
4791 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
4792 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
4793 vbg_get_blksize_t get_blksize)
4800 vm_ooffset_t la, lb, poff, poffe;
4802 int bo_bs, br_flags, error, i, pgsin, pgsin_a, pgsin_b;
4805 object = vp->v_object;
4807 la = IDX_TO_OFF(ma[count - 1]->pindex);
4808 if (la >= object->un_pager.vnp.vnp_size)
4809 return (VM_PAGER_BAD);
4812 * Change the meaning of la from where the last requested page starts
4813 * to where it ends, because that's the end of the requested region
4814 * and the start of the potential read-ahead region.
4817 lpart = la > object->un_pager.vnp.vnp_size;
4818 bo_bs = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)));
4821 * Calculate read-ahead, behind and total pages.
4824 lb = IDX_TO_OFF(ma[0]->pindex);
4825 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
4827 if (rbehind != NULL)
4829 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
4830 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
4831 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
4836 VM_CNT_INC(v_vnodein);
4837 VM_CNT_ADD(v_vnodepgsin, pgsin);
4839 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
4840 != 0) ? GB_UNMAPPED : 0;
4841 VM_OBJECT_WLOCK(object);
4843 for (i = 0; i < count; i++)
4844 vm_page_busy_downgrade(ma[i]);
4845 VM_OBJECT_WUNLOCK(object);
4848 for (i = 0; i < count; i++) {
4852 * Pages are shared busy and the object lock is not
4853 * owned, which together allow for the pages'
4854 * invalidation. The racy test for validity avoids
4855 * useless creation of the buffer for the most typical
4856 * case when invalidation is not used in redo or for
4857 * parallel read. The shared->excl upgrade loop at
4858 * the end of the function catches the race in a
4859 * reliable way (protected by the object lock).
4861 if (m->valid == VM_PAGE_BITS_ALL)
4864 poff = IDX_TO_OFF(m->pindex);
4865 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
4866 for (; poff < poffe; poff += bsize) {
4867 lbn = get_lblkno(vp, poff);
4872 bsize = get_blksize(vp, lbn);
4873 error = bread_gb(vp, lbn, bsize, curthread->td_ucred,
4877 if (LIST_EMPTY(&bp->b_dep)) {
4879 * Invalidation clears m->valid, but
4880 * may leave B_CACHE flag if the
4881 * buffer existed at the invalidation
4882 * time. In this case, recycle the
4883 * buffer to do real read on next
4884 * bread() after redo.
4886 * Otherwise B_RELBUF is not strictly
4887 * necessary, enable to reduce buf
4890 if (buf_pager_relbuf ||
4891 m->valid != VM_PAGE_BITS_ALL)
4892 bp->b_flags |= B_RELBUF;
4894 bp->b_flags &= ~B_NOCACHE;
4900 KASSERT(1 /* racy, enable for debugging */ ||
4901 m->valid == VM_PAGE_BITS_ALL || i == count - 1,
4902 ("buf %d %p invalid", i, m));
4903 if (i == count - 1 && lpart) {
4904 VM_OBJECT_WLOCK(object);
4905 if (m->valid != 0 &&
4906 m->valid != VM_PAGE_BITS_ALL)
4907 vm_page_zero_invalid(m, TRUE);
4908 VM_OBJECT_WUNLOCK(object);
4914 VM_OBJECT_WLOCK(object);
4916 for (i = 0; i < count; i++) {
4917 vm_page_sunbusy(ma[i]);
4918 ma[i] = vm_page_grab(object, ma[i]->pindex, VM_ALLOC_NORMAL);
4921 * Since the pages were only sbusy while neither the
4922 * buffer nor the object lock was held by us, or
4923 * reallocated while vm_page_grab() slept for busy
4924 * relinguish, they could have been invalidated.
4925 * Recheck the valid bits and re-read as needed.
4927 * Note that the last page is made fully valid in the
4928 * read loop, and partial validity for the page at
4929 * index count - 1 could mean that the page was
4930 * invalidated or removed, so we must restart for
4933 if (ma[i]->valid != VM_PAGE_BITS_ALL)
4936 if (redo && error == 0)
4938 VM_OBJECT_WUNLOCK(object);
4939 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
4942 #include "opt_ddb.h"
4944 #include <ddb/ddb.h>
4946 /* DDB command to show buffer data */
4947 DB_SHOW_COMMAND(buffer, db_show_buffer)
4950 struct buf *bp = (struct buf *)addr;
4951 #ifdef FULL_BUF_TRACKING
4956 db_printf("usage: show buffer <addr>\n");
4960 db_printf("buf at %p\n", bp);
4961 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4962 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4963 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4965 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4966 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4968 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4969 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4970 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4971 db_printf("b_kvabase = %p, b_kvasize = %d\n",
4972 bp->b_kvabase, bp->b_kvasize);
4975 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4976 for (i = 0; i < bp->b_npages; i++) {
4980 db_printf("(%p, 0x%lx, 0x%lx)", m->object,
4982 (u_long)VM_PAGE_TO_PHYS(m));
4984 db_printf("( ??? )");
4985 if ((i + 1) < bp->b_npages)
4990 #if defined(FULL_BUF_TRACKING)
4991 db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
4993 i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
4994 for (j = 1; j <= BUF_TRACKING_SIZE; j++) {
4995 if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL)
4997 db_printf(" %2u: %s\n", j,
4998 bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
5000 #elif defined(BUF_TRACKING)
5001 db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
5004 BUF_LOCKPRINTINFO(bp);
5007 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
5012 for (i = 0; i < nbuf; i++) {
5014 if (BUF_ISLOCKED(bp)) {
5015 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5023 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
5029 db_printf("usage: show vnodebufs <addr>\n");
5032 vp = (struct vnode *)addr;
5033 db_printf("Clean buffers:\n");
5034 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
5035 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5038 db_printf("Dirty buffers:\n");
5039 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5040 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5045 DB_COMMAND(countfreebufs, db_coundfreebufs)
5048 int i, used = 0, nfree = 0;
5051 db_printf("usage: countfreebufs\n");
5055 for (i = 0; i < nbuf; i++) {
5057 if (bp->b_qindex == QUEUE_EMPTY)
5063 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5065 db_printf("numfreebuffers is %d\n", numfreebuffers);