2 * Copyright (c) 2004 Poul-Henning Kamp
3 * Copyright (c) 1994,1997 John S. Dyson
4 * Copyright (c) 2013 The FreeBSD Foundation
7 * Portions of this software were developed by Konstantin Belousov
8 * under sponsorship from the FreeBSD Foundation.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * this file contains a new buffer I/O scheme implementing a coherent
34 * VM object and buffer cache scheme. Pains have been taken to make
35 * sure that the performance degradation associated with schemes such
36 * as this is not realized.
38 * Author: John S. Dyson
39 * Significant help during the development and debugging phases
40 * had been provided by David Greenman, also of the FreeBSD core team.
42 * see man buf(9) for more info.
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
49 #include <sys/systm.h>
53 #include <sys/devicestat.h>
54 #include <sys/eventhandler.h>
56 #include <sys/limits.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mutex.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
64 #include <sys/racct.h>
65 #include <sys/resourcevar.h>
66 #include <sys/rwlock.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysproto.h>
71 #include <sys/vmmeter.h>
72 #include <sys/vnode.h>
73 #include <sys/watchdog.h>
74 #include <geom/geom.h>
76 #include <vm/vm_param.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_object.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_pageout.h>
81 #include <vm/vm_pager.h>
82 #include <vm/vm_extern.h>
83 #include <vm/vm_map.h>
84 #include <vm/swap_pager.h>
85 #include "opt_compat.h"
88 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
90 struct bio_ops bioops; /* I/O operation notification */
92 struct buf_ops buf_ops_bio = {
93 .bop_name = "buf_ops_bio",
94 .bop_write = bufwrite,
95 .bop_strategy = bufstrategy,
97 .bop_bdflush = bufbdflush,
100 static struct buf *buf; /* buffer header pool */
101 extern struct buf *swbuf; /* Swap buffer header pool. */
102 caddr_t unmapped_buf;
104 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
105 struct proc *bufdaemonproc;
106 struct proc *bufspacedaemonproc;
108 static int inmem(struct vnode *vp, daddr_t blkno);
109 static void vm_hold_free_pages(struct buf *bp, int newbsize);
110 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
112 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
113 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
115 static void vfs_clean_pages_dirty_buf(struct buf *bp);
116 static void vfs_setdirty_locked_object(struct buf *bp);
117 static void vfs_vmio_invalidate(struct buf *bp);
118 static void vfs_vmio_truncate(struct buf *bp, int npages);
119 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
120 static int vfs_bio_clcheck(struct vnode *vp, int size,
121 daddr_t lblkno, daddr_t blkno);
122 static int buf_flush(struct vnode *vp, int);
123 static int buf_recycle(bool);
124 static int buf_scan(bool);
125 static int flushbufqueues(struct vnode *, int, int);
126 static void buf_daemon(void);
127 static void bremfreel(struct buf *bp);
128 static __inline void bd_wakeup(void);
129 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
130 static void bufkva_reclaim(vmem_t *, int);
131 static void bufkva_free(struct buf *);
132 static int buf_import(void *, void **, int, int);
133 static void buf_release(void *, void **, int);
134 static void maxbcachebuf_adjust(void);
136 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
137 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
138 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
141 int vmiodirenable = TRUE;
142 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
143 "Use the VM system for directory writes");
144 long runningbufspace;
145 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
146 "Amount of presently outstanding async buffer io");
147 static long bufspace;
148 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
149 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
150 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
151 &bufspace, 0, sysctl_bufspace, "L", "Virtual memory used for buffers");
153 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
154 "Physical memory used for buffers");
156 static long bufkvaspace;
157 SYSCTL_LONG(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace, 0,
158 "Kernel virtual memory used for buffers");
159 static long maxbufspace;
160 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RW, &maxbufspace, 0,
161 "Maximum allowed value of bufspace (including metadata)");
162 static long bufmallocspace;
163 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
164 "Amount of malloced memory for buffers");
165 static long maxbufmallocspace;
166 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
167 0, "Maximum amount of malloced memory for buffers");
168 static long lobufspace;
169 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RW, &lobufspace, 0,
170 "Minimum amount of buffers we want to have");
172 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RW, &hibufspace, 0,
173 "Maximum allowed value of bufspace (excluding metadata)");
175 SYSCTL_LONG(_vfs, OID_AUTO, bufspacethresh, CTLFLAG_RW, &bufspacethresh,
176 0, "Bufspace consumed before waking the daemon to free some");
177 static int buffreekvacnt;
178 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0,
179 "Number of times we have freed the KVA space from some buffer");
180 static int bufdefragcnt;
181 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0,
182 "Number of times we have had to repeat buffer allocation to defragment");
183 static long lorunningspace;
184 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
185 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
186 "Minimum preferred space used for in-progress I/O");
187 static long hirunningspace;
188 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
189 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
190 "Maximum amount of space to use for in-progress I/O");
191 int dirtybufferflushes;
192 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
193 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
195 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
196 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
197 int altbufferflushes;
198 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes,
199 0, "Number of fsync flushes to limit dirty buffers");
200 static int recursiveflushes;
201 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes,
202 0, "Number of flushes skipped due to being recursive");
203 static int numdirtybuffers;
204 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
205 "Number of buffers that are dirty (has unwritten changes) at the moment");
206 static int lodirtybuffers;
207 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
208 "How many buffers we want to have free before bufdaemon can sleep");
209 static int hidirtybuffers;
210 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
211 "When the number of dirty buffers is considered severe");
213 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh,
214 0, "Number of bdwrite to bawrite conversions to clear dirty buffers");
215 static int numfreebuffers;
216 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
217 "Number of free buffers");
218 static int lofreebuffers;
219 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
220 "Target number of free buffers");
221 static int hifreebuffers;
222 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
223 "Threshold for clean buffer recycling");
224 static int getnewbufcalls;
225 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0,
226 "Number of calls to getnewbuf");
227 static int getnewbufrestarts;
228 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0,
229 "Number of times getnewbuf has had to restart a buffer acquisition");
230 static int mappingrestarts;
231 SYSCTL_INT(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RW, &mappingrestarts, 0,
232 "Number of times getblk has had to restart a buffer mapping for "
234 static int numbufallocfails;
235 SYSCTL_INT(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW, &numbufallocfails, 0,
236 "Number of times buffer allocations failed");
237 static int flushbufqtarget = 100;
238 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
239 "Amount of work to do in flushbufqueues when helping bufdaemon");
240 static long notbufdflushes;
241 SYSCTL_LONG(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 0,
242 "Number of dirty buffer flushes done by the bufdaemon helpers");
243 static long barrierwrites;
244 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW, &barrierwrites, 0,
245 "Number of barrier writes");
246 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, CTLFLAG_RD,
247 &unmapped_buf_allowed, 0,
248 "Permit the use of the unmapped i/o");
249 int maxbcachebuf = MAXBCACHEBUF;
250 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0,
251 "Maximum size of a buffer cache block");
254 * This lock synchronizes access to bd_request.
256 static struct mtx_padalign __exclusive_cache_line bdlock;
259 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
260 * waitrunningbufspace().
262 static struct mtx_padalign __exclusive_cache_line rbreqlock;
265 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it.
267 static struct rwlock_padalign __exclusive_cache_line nblock;
270 * Lock that protects bdirtywait.
272 static struct mtx_padalign __exclusive_cache_line bdirtylock;
275 * Wakeup point for bufdaemon, as well as indicator of whether it is already
276 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
279 static int bd_request;
282 * Request/wakeup point for the bufspace daemon.
284 static int bufspace_request;
287 * Request for the buf daemon to write more buffers than is indicated by
288 * lodirtybuf. This may be necessary to push out excess dependencies or
289 * defragment the address space where a simple count of the number of dirty
290 * buffers is insufficient to characterize the demand for flushing them.
292 static int bd_speedupreq;
295 * bogus page -- for I/O to/from partially complete buffers
296 * this is a temporary solution to the problem, but it is not
297 * really that bad. it would be better to split the buffer
298 * for input in the case of buffers partially already in memory,
299 * but the code is intricate enough already.
301 vm_page_t bogus_page;
304 * Synchronization (sleep/wakeup) variable for active buffer space requests.
305 * Set when wait starts, cleared prior to wakeup().
306 * Used in runningbufwakeup() and waitrunningbufspace().
308 static int runningbufreq;
311 * Synchronization (sleep/wakeup) variable for buffer requests.
312 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done
314 * Used in numdirtywakeup(), bufspace_wakeup(), bwillwrite(),
315 * getnewbuf(), and getblk().
317 static volatile int needsbuffer;
320 * Synchronization for bwillwrite() waiters.
322 static int bdirtywait;
325 * Definitions for the buffer free lists.
327 #define QUEUE_NONE 0 /* on no queue */
328 #define QUEUE_EMPTY 1 /* empty buffer headers */
329 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
330 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
331 #define QUEUE_SENTINEL 1024 /* not an queue index, but mark for sentinel */
333 /* Maximum number of clean buffer queues. */
334 #define CLEAN_QUEUES 16
336 /* Configured number of clean queues. */
337 static int clean_queues;
339 /* Maximum number of buffer queues. */
340 #define BUFFER_QUEUES (QUEUE_CLEAN + CLEAN_QUEUES)
342 /* Queues for free buffers with various properties */
343 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } };
345 static int bq_len[BUFFER_QUEUES];
349 * Lock for each bufqueue
351 static struct mtx_padalign __exclusive_cache_line bqlocks[BUFFER_QUEUES];
354 * per-cpu empty buffer cache.
359 * Single global constant for BUF_WMESG, to avoid getting multiple references.
360 * buf_wmesg is referred from macros.
362 const char *buf_wmesg = BUF_WMESG;
365 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
370 value = *(long *)arg1;
371 error = sysctl_handle_long(oidp, &value, 0, req);
372 if (error != 0 || req->newptr == NULL)
374 mtx_lock(&rbreqlock);
375 if (arg1 == &hirunningspace) {
376 if (value < lorunningspace)
379 hirunningspace = value;
381 KASSERT(arg1 == &lorunningspace,
382 ("%s: unknown arg1", __func__));
383 if (value > hirunningspace)
386 lorunningspace = value;
388 mtx_unlock(&rbreqlock);
392 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
393 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
395 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
400 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
401 return (sysctl_handle_long(oidp, arg1, arg2, req));
402 lvalue = *(long *)arg1;
403 if (lvalue > INT_MAX)
404 /* On overflow, still write out a long to trigger ENOMEM. */
405 return (sysctl_handle_long(oidp, &lvalue, 0, req));
407 return (sysctl_handle_int(oidp, &ivalue, 0, req));
416 return ((atomic_fetchadd_int(&nextq, 1) % clean_queues) + QUEUE_CLEAN);
420 bqisclean(int qindex)
423 return (qindex >= QUEUE_CLEAN && qindex < QUEUE_CLEAN + CLEAN_QUEUES);
429 * Return the appropriate queue lock based on the index.
431 static inline struct mtx *
435 return (struct mtx *)&bqlocks[qindex];
441 * Wakeup any bwillwrite() waiters.
446 mtx_lock(&bdirtylock);
451 mtx_unlock(&bdirtylock);
457 * Decrement the numdirtybuffers count by one and wakeup any
458 * threads blocked in bwillwrite().
464 if (atomic_fetchadd_int(&numdirtybuffers, -1) ==
465 (lodirtybuffers + hidirtybuffers) / 2)
472 * Increment the numdirtybuffers count by one and wakeup the buf
480 * Only do the wakeup once as we cross the boundary. The
481 * buf daemon will keep running until the condition clears.
483 if (atomic_fetchadd_int(&numdirtybuffers, 1) ==
484 (lodirtybuffers + hidirtybuffers) / 2)
491 * Called when buffer space is potentially available for recovery.
492 * getnewbuf() will block on this flag when it is unable to free
493 * sufficient buffer space. Buffer space becomes recoverable when
494 * bp's get placed back in the queues.
497 bufspace_wakeup(void)
501 * If someone is waiting for bufspace, wake them up.
503 * Since needsbuffer is set prior to doing an additional queue
504 * scan it is safe to check for the flag prior to acquiring the
505 * lock. The thread that is preparing to scan again before
506 * blocking would discover the buf we released.
510 if (atomic_cmpset_int(&needsbuffer, 1, 0) == 1)
511 wakeup(__DEVOLATILE(void *, &needsbuffer));
517 * bufspace_daemonwakeup:
519 * Wakeup the daemon responsible for freeing clean bufs.
522 bufspace_daemonwakeup(void)
525 if (bufspace_request == 0) {
526 bufspace_request = 1;
527 wakeup(&bufspace_request);
535 * Adjust the reported bufspace for a KVA managed buffer, possibly
536 * waking any waiters.
539 bufspace_adjust(struct buf *bp, int bufsize)
544 KASSERT((bp->b_flags & B_MALLOC) == 0,
545 ("bufspace_adjust: malloc buf %p", bp));
546 diff = bufsize - bp->b_bufsize;
548 atomic_subtract_long(&bufspace, -diff);
551 space = atomic_fetchadd_long(&bufspace, diff);
552 /* Wake up the daemon on the transition. */
553 if (space < bufspacethresh && space + diff >= bufspacethresh)
554 bufspace_daemonwakeup();
556 bp->b_bufsize = bufsize;
562 * Reserve bufspace before calling allocbuf(). metadata has a
563 * different space limit than data.
566 bufspace_reserve(int size, bool metadata)
577 if (space + size > limit)
579 } while (atomic_cmpset_long(&bufspace, space, space + size) == 0);
581 /* Wake up the daemon on the transition. */
582 if (space < bufspacethresh && space + size >= bufspacethresh)
583 bufspace_daemonwakeup();
591 * Release reserved bufspace after bufspace_adjust() has consumed it.
594 bufspace_release(int size)
596 atomic_subtract_long(&bufspace, size);
603 * Wait for bufspace, acting as the buf daemon if a locked vnode is
604 * supplied. needsbuffer must be set in a safe fashion prior to
605 * polling for space. The operation must be re-tried on return.
608 bufspace_wait(struct vnode *vp, int gbflags, int slpflag, int slptimeo)
611 int error, fl, norunbuf;
613 if ((gbflags & GB_NOWAIT_BD) != 0)
618 while (needsbuffer != 0) {
619 if (vp != NULL && vp->v_type != VCHR &&
620 (td->td_pflags & TDP_BUFNEED) == 0) {
623 * getblk() is called with a vnode locked, and
624 * some majority of the dirty buffers may as
625 * well belong to the vnode. Flushing the
626 * buffers there would make a progress that
627 * cannot be achieved by the buf_daemon, that
628 * cannot lock the vnode.
630 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
631 (td->td_pflags & TDP_NORUNNINGBUF);
634 * Play bufdaemon. The getnewbuf() function
635 * may be called while the thread owns lock
636 * for another dirty buffer for the same
637 * vnode, which makes it impossible to use
638 * VOP_FSYNC() there, due to the buffer lock
641 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
642 fl = buf_flush(vp, flushbufqtarget);
643 td->td_pflags &= norunbuf;
647 if (needsbuffer == 0)
650 error = rw_sleep(__DEVOLATILE(void *, &needsbuffer), &nblock,
651 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
662 * buffer space management daemon. Tries to maintain some marginal
663 * amount of free buffer space so that requesting processes neither
664 * block nor work to reclaim buffers.
667 bufspace_daemon(void)
670 kproc_suspend_check(bufspacedaemonproc);
673 * Free buffers from the clean queue until we meet our
676 * Theory of operation: The buffer cache is most efficient
677 * when some free buffer headers and space are always
678 * available to getnewbuf(). This daemon attempts to prevent
679 * the excessive blocking and synchronization associated
680 * with shortfall. It goes through three phases according
683 * 1) The daemon wakes up voluntarily once per-second
684 * during idle periods when the counters are below
685 * the wakeup thresholds (bufspacethresh, lofreebuffers).
687 * 2) The daemon wakes up as we cross the thresholds
688 * ahead of any potential blocking. This may bounce
689 * slightly according to the rate of consumption and
692 * 3) The daemon and consumers are starved for working
693 * clean buffers. This is the 'bufspace' sleep below
694 * which will inefficiently trade bufs with bqrelse
695 * until we return to condition 2.
697 while (bufspace > lobufspace ||
698 numfreebuffers < hifreebuffers) {
699 if (buf_recycle(false) != 0) {
700 atomic_set_int(&needsbuffer, 1);
701 if (buf_recycle(false) != 0) {
704 rw_sleep(__DEVOLATILE(void *,
705 &needsbuffer), &nblock,
706 PRIBIO|PDROP, "bufspace",
716 * Re-check our limits under the exclusive nblock.
719 if (bufspace < bufspacethresh &&
720 numfreebuffers > lofreebuffers) {
721 bufspace_request = 0;
722 rw_sleep(&bufspace_request, &nblock, PRIBIO|PDROP,
729 static struct kproc_desc bufspace_kp = {
734 SYSINIT(bufspacedaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start,
740 * Adjust the reported bufspace for a malloc managed buffer, possibly
741 * waking any waiters.
744 bufmallocadjust(struct buf *bp, int bufsize)
748 KASSERT((bp->b_flags & B_MALLOC) != 0,
749 ("bufmallocadjust: non-malloc buf %p", bp));
750 diff = bufsize - bp->b_bufsize;
752 atomic_subtract_long(&bufmallocspace, -diff);
754 atomic_add_long(&bufmallocspace, diff);
755 bp->b_bufsize = bufsize;
761 * Wake up processes that are waiting on asynchronous writes to fall
762 * below lorunningspace.
768 mtx_lock(&rbreqlock);
771 wakeup(&runningbufreq);
773 mtx_unlock(&rbreqlock);
779 * Decrement the outstanding write count according.
782 runningbufwakeup(struct buf *bp)
786 bspace = bp->b_runningbufspace;
789 space = atomic_fetchadd_long(&runningbufspace, -bspace);
790 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
792 bp->b_runningbufspace = 0;
794 * Only acquire the lock and wakeup on the transition from exceeding
795 * the threshold to falling below it.
797 if (space < lorunningspace)
799 if (space - bspace > lorunningspace)
805 * waitrunningbufspace()
807 * runningbufspace is a measure of the amount of I/O currently
808 * running. This routine is used in async-write situations to
809 * prevent creating huge backups of pending writes to a device.
810 * Only asynchronous writes are governed by this function.
812 * This does NOT turn an async write into a sync write. It waits
813 * for earlier writes to complete and generally returns before the
814 * caller's write has reached the device.
817 waitrunningbufspace(void)
820 mtx_lock(&rbreqlock);
821 while (runningbufspace > hirunningspace) {
823 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
825 mtx_unlock(&rbreqlock);
830 * vfs_buf_test_cache:
832 * Called when a buffer is extended. This function clears the B_CACHE
833 * bit if the newly extended portion of the buffer does not contain
837 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
838 vm_offset_t size, vm_page_t m)
841 VM_OBJECT_ASSERT_LOCKED(m->object);
842 if (bp->b_flags & B_CACHE) {
843 int base = (foff + off) & PAGE_MASK;
844 if (vm_page_is_valid(m, base, size) == 0)
845 bp->b_flags &= ~B_CACHE;
849 /* Wake up the buffer daemon if necessary */
855 if (bd_request == 0) {
863 * Adjust the maxbcachbuf tunable.
866 maxbcachebuf_adjust(void)
871 * maxbcachebuf must be a power of 2 >= MAXBSIZE.
874 while (i * 2 <= maxbcachebuf)
877 if (maxbcachebuf < MAXBSIZE)
878 maxbcachebuf = MAXBSIZE;
879 if (maxbcachebuf > MAXPHYS)
880 maxbcachebuf = MAXPHYS;
881 if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF)
882 printf("maxbcachebuf=%d\n", maxbcachebuf);
886 * bd_speedup - speedup the buffer cache flushing code
895 if (bd_speedupreq == 0 || bd_request == 0)
905 #define NSWBUF_MIN 16
909 #define TRANSIENT_DENOM 5
911 #define TRANSIENT_DENOM 10
915 * Calculating buffer cache scaling values and reserve space for buffer
916 * headers. This is called during low level kernel initialization and
917 * may be called more then once. We CANNOT write to the memory area
918 * being reserved at this time.
921 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
924 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
927 * physmem_est is in pages. Convert it to kilobytes (assumes
928 * PAGE_SIZE is >= 1K)
930 physmem_est = physmem_est * (PAGE_SIZE / 1024);
932 maxbcachebuf_adjust();
934 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
935 * For the first 64MB of ram nominally allocate sufficient buffers to
936 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
937 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
938 * the buffer cache we limit the eventual kva reservation to
941 * factor represents the 1/4 x ram conversion.
944 int factor = 4 * BKVASIZE / 1024;
947 if (physmem_est > 4096)
948 nbuf += min((physmem_est - 4096) / factor,
950 if (physmem_est > 65536)
951 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
952 32 * 1024 * 1024 / (factor * 5));
954 if (maxbcache && nbuf > maxbcache / BKVASIZE)
955 nbuf = maxbcache / BKVASIZE;
960 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
961 maxbuf = (LONG_MAX / 3) / BKVASIZE;
964 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
970 * Ideal allocation size for the transient bio submap is 10%
971 * of the maximal space buffer map. This roughly corresponds
972 * to the amount of the buffer mapped for typical UFS load.
974 * Clip the buffer map to reserve space for the transient
975 * BIOs, if its extent is bigger than 90% (80% on i386) of the
976 * maximum buffer map extent on the platform.
978 * The fall-back to the maxbuf in case of maxbcache unset,
979 * allows to not trim the buffer KVA for the architectures
980 * with ample KVA space.
982 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
983 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
984 buf_sz = (long)nbuf * BKVASIZE;
985 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
986 (TRANSIENT_DENOM - 1)) {
988 * There is more KVA than memory. Do not
989 * adjust buffer map size, and assign the rest
990 * of maxbuf to transient map.
992 biotmap_sz = maxbuf_sz - buf_sz;
995 * Buffer map spans all KVA we could afford on
996 * this platform. Give 10% (20% on i386) of
997 * the buffer map to the transient bio map.
999 biotmap_sz = buf_sz / TRANSIENT_DENOM;
1000 buf_sz -= biotmap_sz;
1002 if (biotmap_sz / INT_MAX > MAXPHYS)
1003 bio_transient_maxcnt = INT_MAX;
1005 bio_transient_maxcnt = biotmap_sz / MAXPHYS;
1007 * Artificially limit to 1024 simultaneous in-flight I/Os
1008 * using the transient mapping.
1010 if (bio_transient_maxcnt > 1024)
1011 bio_transient_maxcnt = 1024;
1013 nbuf = buf_sz / BKVASIZE;
1017 * swbufs are used as temporary holders for I/O, such as paging I/O.
1018 * We have no less then 16 and no more then 256.
1020 nswbuf = min(nbuf / 4, 256);
1021 TUNABLE_INT_FETCH("kern.nswbuf", &nswbuf);
1022 if (nswbuf < NSWBUF_MIN)
1023 nswbuf = NSWBUF_MIN;
1026 * Reserve space for the buffer cache buffers
1029 v = (caddr_t)(swbuf + nswbuf);
1031 v = (caddr_t)(buf + nbuf);
1036 /* Initialize the buffer subsystem. Called before use of any buffers. */
1043 KASSERT(maxbcachebuf >= MAXBSIZE,
1044 ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf,
1046 mtx_init(&bqlocks[QUEUE_DIRTY], "bufq dirty lock", NULL, MTX_DEF);
1047 mtx_init(&bqlocks[QUEUE_EMPTY], "bufq empty lock", NULL, MTX_DEF);
1048 for (i = QUEUE_CLEAN; i < QUEUE_CLEAN + CLEAN_QUEUES; i++)
1049 mtx_init(&bqlocks[i], "bufq clean lock", NULL, MTX_DEF);
1050 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1051 rw_init(&nblock, "needsbuffer lock");
1052 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1053 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1055 /* next, make a null set of free lists */
1056 for (i = 0; i < BUFFER_QUEUES; i++)
1057 TAILQ_INIT(&bufqueues[i]);
1059 unmapped_buf = (caddr_t)kva_alloc(MAXPHYS);
1061 /* finally, initialize each buffer header and stick on empty q */
1062 for (i = 0; i < nbuf; i++) {
1064 bzero(bp, sizeof *bp);
1065 bp->b_flags = B_INVAL;
1066 bp->b_rcred = NOCRED;
1067 bp->b_wcred = NOCRED;
1068 bp->b_qindex = QUEUE_EMPTY;
1070 bp->b_data = bp->b_kvabase = unmapped_buf;
1071 LIST_INIT(&bp->b_dep);
1073 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
1075 bq_len[QUEUE_EMPTY]++;
1080 * maxbufspace is the absolute maximum amount of buffer space we are
1081 * allowed to reserve in KVM and in real terms. The absolute maximum
1082 * is nominally used by metadata. hibufspace is the nominal maximum
1083 * used by most other requests. The differential is required to
1084 * ensure that metadata deadlocks don't occur.
1086 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1087 * this may result in KVM fragmentation which is not handled optimally
1088 * by the system. XXX This is less true with vmem. We could use
1091 maxbufspace = (long)nbuf * BKVASIZE;
1092 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10);
1093 lobufspace = (hibufspace / 20) * 19; /* 95% */
1094 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1097 * Note: The 16 MiB upper limit for hirunningspace was chosen
1098 * arbitrarily and may need further tuning. It corresponds to
1099 * 128 outstanding write IO requests (if IO size is 128 KiB),
1100 * which fits with many RAID controllers' tagged queuing limits.
1101 * The lower 1 MiB limit is the historical upper limit for
1104 hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf),
1105 16 * 1024 * 1024), 1024 * 1024);
1106 lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf);
1109 * Limit the amount of malloc memory since it is wired permanently into
1110 * the kernel space. Even though this is accounted for in the buffer
1111 * allocation, we don't want the malloced region to grow uncontrolled.
1112 * The malloc scheme improves memory utilization significantly on
1113 * average (small) directories.
1115 maxbufmallocspace = hibufspace / 20;
1118 * Reduce the chance of a deadlock occurring by limiting the number
1119 * of delayed-write dirty buffers we allow to stack up.
1121 hidirtybuffers = nbuf / 4 + 20;
1122 dirtybufthresh = hidirtybuffers * 9 / 10;
1123 numdirtybuffers = 0;
1125 * To support extreme low-memory systems, make sure hidirtybuffers
1126 * cannot eat up all available buffer space. This occurs when our
1127 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1128 * buffer space assuming BKVASIZE'd buffers.
1130 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1131 hidirtybuffers >>= 1;
1133 lodirtybuffers = hidirtybuffers / 2;
1136 * lofreebuffers should be sufficient to avoid stalling waiting on
1137 * buf headers under heavy utilization. The bufs in per-cpu caches
1138 * are counted as free but will be unavailable to threads executing
1141 * hifreebuffers is the free target for the bufspace daemon. This
1142 * should be set appropriately to limit work per-iteration.
1144 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1145 hifreebuffers = (3 * lofreebuffers) / 2;
1146 numfreebuffers = nbuf;
1148 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
1149 VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
1151 /* Setup the kva and free list allocators. */
1152 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1153 buf_zone = uma_zcache_create("buf free cache", sizeof(struct buf),
1154 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1157 * Size the clean queue according to the amount of buffer space.
1158 * One queue per-256mb up to the max. More queues gives better
1159 * concurrency but less accurate LRU.
1161 clean_queues = MIN(howmany(maxbufspace, 256*1024*1024), CLEAN_QUEUES);
1167 vfs_buf_check_mapped(struct buf *bp)
1170 KASSERT(bp->b_kvabase != unmapped_buf,
1171 ("mapped buf: b_kvabase was not updated %p", bp));
1172 KASSERT(bp->b_data != unmapped_buf,
1173 ("mapped buf: b_data was not updated %p", bp));
1174 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1175 MAXPHYS, ("b_data + b_offset unmapped %p", bp));
1179 vfs_buf_check_unmapped(struct buf *bp)
1182 KASSERT(bp->b_data == unmapped_buf,
1183 ("unmapped buf: corrupted b_data %p", bp));
1186 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1187 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1189 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1190 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1194 isbufbusy(struct buf *bp)
1196 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1197 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1203 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1206 bufshutdown(int show_busybufs)
1208 static int first_buf_printf = 1;
1210 int iter, nbusy, pbusy;
1216 * Sync filesystems for shutdown
1218 wdog_kern_pat(WD_LASTVAL);
1219 sys_sync(curthread, NULL);
1222 * With soft updates, some buffers that are
1223 * written will be remarked as dirty until other
1224 * buffers are written.
1226 for (iter = pbusy = 0; iter < 20; iter++) {
1228 for (bp = &buf[nbuf]; --bp >= buf; )
1232 if (first_buf_printf)
1233 printf("All buffers synced.");
1236 if (first_buf_printf) {
1237 printf("Syncing disks, buffers remaining... ");
1238 first_buf_printf = 0;
1240 printf("%d ", nbusy);
1245 wdog_kern_pat(WD_LASTVAL);
1246 sys_sync(curthread, NULL);
1250 * Drop Giant and spin for a while to allow
1251 * interrupt threads to run.
1254 DELAY(50000 * iter);
1258 * Drop Giant and context switch several times to
1259 * allow interrupt threads to run.
1262 for (subiter = 0; subiter < 50 * iter; subiter++) {
1263 thread_lock(curthread);
1264 mi_switch(SW_VOL, NULL);
1265 thread_unlock(curthread);
1273 * Count only busy local buffers to prevent forcing
1274 * a fsck if we're just a client of a wedged NFS server
1277 for (bp = &buf[nbuf]; --bp >= buf; ) {
1278 if (isbufbusy(bp)) {
1280 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1281 if (bp->b_dev == NULL) {
1282 TAILQ_REMOVE(&mountlist,
1283 bp->b_vp->v_mount, mnt_list);
1288 if (show_busybufs > 0) {
1290 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1291 nbusy, bp, bp->b_vp, bp->b_flags,
1292 (intmax_t)bp->b_blkno,
1293 (intmax_t)bp->b_lblkno);
1294 BUF_LOCKPRINTINFO(bp);
1295 if (show_busybufs > 1)
1303 * Failed to sync all blocks. Indicate this and don't
1304 * unmount filesystems (thus forcing an fsck on reboot).
1306 printf("Giving up on %d buffers\n", nbusy);
1307 DELAY(5000000); /* 5 seconds */
1309 if (!first_buf_printf)
1310 printf("Final sync complete\n");
1312 * Unmount filesystems
1314 if (panicstr == NULL)
1318 DELAY(100000); /* wait for console output to finish */
1322 bpmap_qenter(struct buf *bp)
1325 BUF_CHECK_MAPPED(bp);
1328 * bp->b_data is relative to bp->b_offset, but
1329 * bp->b_offset may be offset into the first page.
1331 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1332 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1333 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1334 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1340 * Insert the buffer into the appropriate free list.
1343 binsfree(struct buf *bp, int qindex)
1345 struct mtx *olock, *nlock;
1347 if (qindex != QUEUE_EMPTY) {
1348 BUF_ASSERT_XLOCKED(bp);
1352 * Stick to the same clean queue for the lifetime of the buf to
1353 * limit locking below. Otherwise pick ont sequentially.
1355 if (qindex == QUEUE_CLEAN) {
1356 if (bqisclean(bp->b_qindex))
1357 qindex = bp->b_qindex;
1359 qindex = bqcleanq();
1363 * Handle delayed bremfree() processing.
1365 nlock = bqlock(qindex);
1366 if (bp->b_flags & B_REMFREE) {
1367 olock = bqlock(bp->b_qindex);
1370 if (olock != nlock) {
1377 if (bp->b_qindex != QUEUE_NONE)
1378 panic("binsfree: free buffer onto another queue???");
1380 bp->b_qindex = qindex;
1381 if (bp->b_flags & B_AGE)
1382 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1384 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1386 bq_len[bp->b_qindex]++;
1394 * Free a buffer to the buf zone once it no longer has valid contents.
1397 buf_free(struct buf *bp)
1400 if (bp->b_flags & B_REMFREE)
1402 if (bp->b_vflags & BV_BKGRDINPROG)
1403 panic("losing buffer 1");
1404 if (bp->b_rcred != NOCRED) {
1405 crfree(bp->b_rcred);
1406 bp->b_rcred = NOCRED;
1408 if (bp->b_wcred != NOCRED) {
1409 crfree(bp->b_wcred);
1410 bp->b_wcred = NOCRED;
1412 if (!LIST_EMPTY(&bp->b_dep))
1416 uma_zfree(buf_zone, bp);
1417 atomic_add_int(&numfreebuffers, 1);
1424 * Import bufs into the uma cache from the buf list. The system still
1425 * expects a static array of bufs and much of the synchronization
1426 * around bufs assumes type stable storage. As a result, UMA is used
1427 * only as a per-cpu cache of bufs still maintained on a global list.
1430 buf_import(void *arg, void **store, int cnt, int flags)
1435 mtx_lock(&bqlocks[QUEUE_EMPTY]);
1436 for (i = 0; i < cnt; i++) {
1437 bp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1443 mtx_unlock(&bqlocks[QUEUE_EMPTY]);
1451 * Release bufs from the uma cache back to the buffer queues.
1454 buf_release(void *arg, void **store, int cnt)
1458 for (i = 0; i < cnt; i++)
1459 binsfree(store[i], QUEUE_EMPTY);
1465 * Allocate an empty buffer header.
1472 bp = uma_zalloc(buf_zone, M_NOWAIT);
1474 bufspace_daemonwakeup();
1475 atomic_add_int(&numbufallocfails, 1);
1480 * Wake-up the bufspace daemon on transition.
1482 if (atomic_fetchadd_int(&numfreebuffers, -1) == lofreebuffers)
1483 bufspace_daemonwakeup();
1485 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1486 panic("getnewbuf_empty: Locked buf %p on free queue.", bp);
1488 KASSERT(bp->b_vp == NULL,
1489 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1490 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1491 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1492 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1493 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1494 KASSERT(bp->b_npages == 0,
1495 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1496 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1497 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1504 bp->b_blkno = bp->b_lblkno = 0;
1505 bp->b_offset = NOOFFSET;
1511 bp->b_dirtyoff = bp->b_dirtyend = 0;
1512 bp->b_bufobj = NULL;
1513 bp->b_pin_count = 0;
1514 bp->b_data = bp->b_kvabase = unmapped_buf;
1515 bp->b_fsprivate1 = NULL;
1516 bp->b_fsprivate2 = NULL;
1517 bp->b_fsprivate3 = NULL;
1518 LIST_INIT(&bp->b_dep);
1526 * Free a buffer from the given bufqueue. kva controls whether the
1527 * freed buf must own some kva resources. This is used for
1531 buf_qrecycle(int qindex, bool kva)
1533 struct buf *bp, *nbp;
1536 atomic_add_int(&bufdefragcnt, 1);
1538 mtx_lock(&bqlocks[qindex]);
1539 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1542 * Run scan, possibly freeing data and/or kva mappings on the fly
1545 while ((bp = nbp) != NULL) {
1547 * Calculate next bp (we can only use it if we do not
1548 * release the bqlock).
1550 nbp = TAILQ_NEXT(bp, b_freelist);
1553 * If we are defragging then we need a buffer with
1554 * some kva to reclaim.
1556 if (kva && bp->b_kvasize == 0)
1559 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1563 * Skip buffers with background writes in progress.
1565 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1570 KASSERT(bp->b_qindex == qindex,
1571 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1573 * NOTE: nbp is now entirely invalid. We can only restart
1574 * the scan from this point on.
1577 mtx_unlock(&bqlocks[qindex]);
1580 * Requeue the background write buffer with error and
1583 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1585 mtx_lock(&bqlocks[qindex]);
1586 nbp = TAILQ_FIRST(&bufqueues[qindex]);
1589 bp->b_flags |= B_INVAL;
1593 mtx_unlock(&bqlocks[qindex]);
1601 * Iterate through all clean queues until we find a buf to recycle or
1602 * exhaust the search.
1605 buf_recycle(bool kva)
1607 int qindex, first_qindex;
1609 qindex = first_qindex = bqcleanq();
1611 if (buf_qrecycle(qindex, kva) == 0)
1613 if (++qindex == QUEUE_CLEAN + clean_queues)
1614 qindex = QUEUE_CLEAN;
1615 } while (qindex != first_qindex);
1623 * Scan the clean queues looking for a buffer to recycle. needsbuffer
1624 * is set on failure so that the caller may optionally bufspace_wait()
1625 * in a race-free fashion.
1628 buf_scan(bool defrag)
1633 * To avoid heavy synchronization and wakeup races we set
1634 * needsbuffer and re-poll before failing. This ensures that
1635 * no frees can be missed between an unsuccessful poll and
1636 * going to sleep in a synchronized fashion.
1638 if ((error = buf_recycle(defrag)) != 0) {
1639 atomic_set_int(&needsbuffer, 1);
1640 bufspace_daemonwakeup();
1641 error = buf_recycle(defrag);
1644 atomic_add_int(&getnewbufrestarts, 1);
1651 * Mark the buffer for removal from the appropriate free list.
1655 bremfree(struct buf *bp)
1658 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1659 KASSERT((bp->b_flags & B_REMFREE) == 0,
1660 ("bremfree: buffer %p already marked for delayed removal.", bp));
1661 KASSERT(bp->b_qindex != QUEUE_NONE,
1662 ("bremfree: buffer %p not on a queue.", bp));
1663 BUF_ASSERT_XLOCKED(bp);
1665 bp->b_flags |= B_REMFREE;
1671 * Force an immediate removal from a free list. Used only in nfs when
1672 * it abuses the b_freelist pointer.
1675 bremfreef(struct buf *bp)
1679 qlock = bqlock(bp->b_qindex);
1688 * Removes a buffer from the free list, must be called with the
1689 * correct qlock held.
1692 bremfreel(struct buf *bp)
1695 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X",
1696 bp, bp->b_vp, bp->b_flags);
1697 KASSERT(bp->b_qindex != QUEUE_NONE,
1698 ("bremfreel: buffer %p not on a queue.", bp));
1699 if (bp->b_qindex != QUEUE_EMPTY) {
1700 BUF_ASSERT_XLOCKED(bp);
1702 mtx_assert(bqlock(bp->b_qindex), MA_OWNED);
1704 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
1706 KASSERT(bq_len[bp->b_qindex] >= 1, ("queue %d underflow",
1708 bq_len[bp->b_qindex]--;
1710 bp->b_qindex = QUEUE_NONE;
1711 bp->b_flags &= ~B_REMFREE;
1717 * Free the kva allocation for a buffer.
1721 bufkva_free(struct buf *bp)
1725 if (bp->b_kvasize == 0) {
1726 KASSERT(bp->b_kvabase == unmapped_buf &&
1727 bp->b_data == unmapped_buf,
1728 ("Leaked KVA space on %p", bp));
1729 } else if (buf_mapped(bp))
1730 BUF_CHECK_MAPPED(bp);
1732 BUF_CHECK_UNMAPPED(bp);
1734 if (bp->b_kvasize == 0)
1737 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
1738 atomic_subtract_long(&bufkvaspace, bp->b_kvasize);
1739 atomic_add_int(&buffreekvacnt, 1);
1740 bp->b_data = bp->b_kvabase = unmapped_buf;
1747 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
1750 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
1755 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
1756 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
1761 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
1764 * Buffer map is too fragmented. Request the caller
1765 * to defragment the map.
1769 bp->b_kvabase = (caddr_t)addr;
1770 bp->b_kvasize = maxsize;
1771 atomic_add_long(&bufkvaspace, bp->b_kvasize);
1772 if ((gbflags & GB_UNMAPPED) != 0) {
1773 bp->b_data = unmapped_buf;
1774 BUF_CHECK_UNMAPPED(bp);
1776 bp->b_data = bp->b_kvabase;
1777 BUF_CHECK_MAPPED(bp);
1785 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
1786 * callback that fires to avoid returning failure.
1789 bufkva_reclaim(vmem_t *vmem, int flags)
1793 for (i = 0; i < 5; i++)
1794 if (buf_scan(true) != 0)
1801 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
1802 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
1803 * the buffer is valid and we do not have to do anything.
1806 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize,
1807 int cnt, struct ucred * cred)
1812 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
1813 if (inmem(vp, *rablkno))
1815 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
1817 if ((rabp->b_flags & B_CACHE) == 0) {
1818 if (!TD_IS_IDLETHREAD(curthread)) {
1822 racct_add_buf(curproc, rabp, 0);
1823 PROC_UNLOCK(curproc);
1826 curthread->td_ru.ru_inblock++;
1828 rabp->b_flags |= B_ASYNC;
1829 rabp->b_flags &= ~B_INVAL;
1830 rabp->b_ioflags &= ~BIO_ERROR;
1831 rabp->b_iocmd = BIO_READ;
1832 if (rabp->b_rcred == NOCRED && cred != NOCRED)
1833 rabp->b_rcred = crhold(cred);
1834 vfs_busy_pages(rabp, 0);
1836 rabp->b_iooffset = dbtob(rabp->b_blkno);
1845 * Entry point for bread() and breadn() via #defines in sys/buf.h.
1847 * Get a buffer with the specified data. Look in the cache first. We
1848 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
1849 * is set, the buffer is valid and we do not have to do anything, see
1850 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
1852 * Always return a NULL buffer pointer (in bpp) when returning an error.
1855 breadn_flags(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablkno,
1856 int *rabsize, int cnt, struct ucred *cred, int flags, struct buf **bpp)
1859 int rv = 0, readwait = 0;
1861 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
1863 * Can only return NULL if GB_LOCK_NOWAIT flag is specified.
1865 *bpp = bp = getblk(vp, blkno, size, 0, 0, flags);
1869 /* if not found in cache, do some I/O */
1870 if ((bp->b_flags & B_CACHE) == 0) {
1871 if (!TD_IS_IDLETHREAD(curthread)) {
1875 racct_add_buf(curproc, bp, 0);
1876 PROC_UNLOCK(curproc);
1879 curthread->td_ru.ru_inblock++;
1881 bp->b_iocmd = BIO_READ;
1882 bp->b_flags &= ~B_INVAL;
1883 bp->b_ioflags &= ~BIO_ERROR;
1884 if (bp->b_rcred == NOCRED && cred != NOCRED)
1885 bp->b_rcred = crhold(cred);
1886 vfs_busy_pages(bp, 0);
1887 bp->b_iooffset = dbtob(bp->b_blkno);
1892 breada(vp, rablkno, rabsize, cnt, cred);
1905 * Write, release buffer on completion. (Done by iodone
1906 * if async). Do not bother writing anything if the buffer
1909 * Note that we set B_CACHE here, indicating that buffer is
1910 * fully valid and thus cacheable. This is true even of NFS
1911 * now so we set it generally. This could be set either here
1912 * or in biodone() since the I/O is synchronous. We put it
1916 bufwrite(struct buf *bp)
1923 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1924 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
1925 bp->b_flags |= B_INVAL | B_RELBUF;
1926 bp->b_flags &= ~B_CACHE;
1930 if (bp->b_flags & B_INVAL) {
1935 if (bp->b_flags & B_BARRIER)
1936 atomic_add_long(&barrierwrites, 1);
1938 oldflags = bp->b_flags;
1940 BUF_ASSERT_HELD(bp);
1942 if (bp->b_pin_count > 0)
1945 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
1946 ("FFS background buffer should not get here %p", bp));
1950 vp_md = vp->v_vflag & VV_MD;
1955 * Mark the buffer clean. Increment the bufobj write count
1956 * before bundirty() call, to prevent other thread from seeing
1957 * empty dirty list and zero counter for writes in progress,
1958 * falsely indicating that the bufobj is clean.
1960 bufobj_wref(bp->b_bufobj);
1963 bp->b_flags &= ~B_DONE;
1964 bp->b_ioflags &= ~BIO_ERROR;
1965 bp->b_flags |= B_CACHE;
1966 bp->b_iocmd = BIO_WRITE;
1968 vfs_busy_pages(bp, 1);
1971 * Normal bwrites pipeline writes
1973 bp->b_runningbufspace = bp->b_bufsize;
1974 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
1976 if (!TD_IS_IDLETHREAD(curthread)) {
1980 racct_add_buf(curproc, bp, 1);
1981 PROC_UNLOCK(curproc);
1984 curthread->td_ru.ru_oublock++;
1986 if (oldflags & B_ASYNC)
1988 bp->b_iooffset = dbtob(bp->b_blkno);
1991 if ((oldflags & B_ASYNC) == 0) {
1992 int rtval = bufwait(bp);
1995 } else if (space > hirunningspace) {
1997 * don't allow the async write to saturate the I/O
1998 * system. We will not deadlock here because
1999 * we are blocking waiting for I/O that is already in-progress
2000 * to complete. We do not block here if it is the update
2001 * or syncer daemon trying to clean up as that can lead
2004 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
2005 waitrunningbufspace();
2012 bufbdflush(struct bufobj *bo, struct buf *bp)
2016 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) {
2017 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
2019 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) {
2022 * Try to find a buffer to flush.
2024 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2025 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2027 LK_EXCLUSIVE | LK_NOWAIT, NULL))
2030 panic("bdwrite: found ourselves");
2032 /* Don't countdeps with the bo lock held. */
2033 if (buf_countdeps(nbp, 0)) {
2038 if (nbp->b_flags & B_CLUSTEROK) {
2039 vfs_bio_awrite(nbp);
2044 dirtybufferflushes++;
2053 * Delayed write. (Buffer is marked dirty). Do not bother writing
2054 * anything if the buffer is marked invalid.
2056 * Note that since the buffer must be completely valid, we can safely
2057 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2058 * biodone() in order to prevent getblk from writing the buffer
2059 * out synchronously.
2062 bdwrite(struct buf *bp)
2064 struct thread *td = curthread;
2068 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2069 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2070 KASSERT((bp->b_flags & B_BARRIER) == 0,
2071 ("Barrier request in delayed write %p", bp));
2072 BUF_ASSERT_HELD(bp);
2074 if (bp->b_flags & B_INVAL) {
2080 * If we have too many dirty buffers, don't create any more.
2081 * If we are wildly over our limit, then force a complete
2082 * cleanup. Otherwise, just keep the situation from getting
2083 * out of control. Note that we have to avoid a recursive
2084 * disaster and not try to clean up after our own cleanup!
2088 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2089 td->td_pflags |= TDP_INBDFLUSH;
2091 td->td_pflags &= ~TDP_INBDFLUSH;
2097 * Set B_CACHE, indicating that the buffer is fully valid. This is
2098 * true even of NFS now.
2100 bp->b_flags |= B_CACHE;
2103 * This bmap keeps the system from needing to do the bmap later,
2104 * perhaps when the system is attempting to do a sync. Since it
2105 * is likely that the indirect block -- or whatever other datastructure
2106 * that the filesystem needs is still in memory now, it is a good
2107 * thing to do this. Note also, that if the pageout daemon is
2108 * requesting a sync -- there might not be enough memory to do
2109 * the bmap then... So, this is important to do.
2111 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2112 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2116 * Set the *dirty* buffer range based upon the VM system dirty
2119 * Mark the buffer pages as clean. We need to do this here to
2120 * satisfy the vnode_pager and the pageout daemon, so that it
2121 * thinks that the pages have been "cleaned". Note that since
2122 * the pages are in a delayed write buffer -- the VFS layer
2123 * "will" see that the pages get written out on the next sync,
2124 * or perhaps the cluster will be completed.
2126 vfs_clean_pages_dirty_buf(bp);
2130 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2131 * due to the softdep code.
2138 * Turn buffer into delayed write request. We must clear BIO_READ and
2139 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2140 * itself to properly update it in the dirty/clean lists. We mark it
2141 * B_DONE to ensure that any asynchronization of the buffer properly
2142 * clears B_DONE ( else a panic will occur later ).
2144 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2145 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2146 * should only be called if the buffer is known-good.
2148 * Since the buffer is not on a queue, we do not update the numfreebuffers
2151 * The buffer must be on QUEUE_NONE.
2154 bdirty(struct buf *bp)
2157 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2158 bp, bp->b_vp, bp->b_flags);
2159 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2160 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2161 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2162 BUF_ASSERT_HELD(bp);
2163 bp->b_flags &= ~(B_RELBUF);
2164 bp->b_iocmd = BIO_WRITE;
2166 if ((bp->b_flags & B_DELWRI) == 0) {
2167 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2176 * Clear B_DELWRI for buffer.
2178 * Since the buffer is not on a queue, we do not update the numfreebuffers
2181 * The buffer must be on QUEUE_NONE.
2185 bundirty(struct buf *bp)
2188 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2189 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2190 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2191 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2192 BUF_ASSERT_HELD(bp);
2194 if (bp->b_flags & B_DELWRI) {
2195 bp->b_flags &= ~B_DELWRI;
2200 * Since it is now being written, we can clear its deferred write flag.
2202 bp->b_flags &= ~B_DEFERRED;
2208 * Asynchronous write. Start output on a buffer, but do not wait for
2209 * it to complete. The buffer is released when the output completes.
2211 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2212 * B_INVAL buffers. Not us.
2215 bawrite(struct buf *bp)
2218 bp->b_flags |= B_ASYNC;
2225 * Asynchronous barrier write. Start output on a buffer, but do not
2226 * wait for it to complete. Place a write barrier after this write so
2227 * that this buffer and all buffers written before it are committed to
2228 * the disk before any buffers written after this write are committed
2229 * to the disk. The buffer is released when the output completes.
2232 babarrierwrite(struct buf *bp)
2235 bp->b_flags |= B_ASYNC | B_BARRIER;
2242 * Synchronous barrier write. Start output on a buffer and wait for
2243 * it to complete. Place a write barrier after this write so that
2244 * this buffer and all buffers written before it are committed to
2245 * the disk before any buffers written after this write are committed
2246 * to the disk. The buffer is released when the output completes.
2249 bbarrierwrite(struct buf *bp)
2252 bp->b_flags |= B_BARRIER;
2253 return (bwrite(bp));
2259 * Called prior to the locking of any vnodes when we are expecting to
2260 * write. We do not want to starve the buffer cache with too many
2261 * dirty buffers so we block here. By blocking prior to the locking
2262 * of any vnodes we attempt to avoid the situation where a locked vnode
2263 * prevents the various system daemons from flushing related buffers.
2269 if (numdirtybuffers >= hidirtybuffers) {
2270 mtx_lock(&bdirtylock);
2271 while (numdirtybuffers >= hidirtybuffers) {
2273 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2276 mtx_unlock(&bdirtylock);
2281 * Return true if we have too many dirty buffers.
2284 buf_dirty_count_severe(void)
2287 return(numdirtybuffers >= hidirtybuffers);
2293 * Release a busy buffer and, if requested, free its resources. The
2294 * buffer will be stashed in the appropriate bufqueue[] allowing it
2295 * to be accessed later as a cache entity or reused for other purposes.
2298 brelse(struct buf *bp)
2303 * Many functions erroneously call brelse with a NULL bp under rare
2304 * error conditions. Simply return when called with a NULL bp.
2308 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2309 bp, bp->b_vp, bp->b_flags);
2310 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2311 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2312 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2313 ("brelse: non-VMIO buffer marked NOREUSE"));
2315 if (BUF_LOCKRECURSED(bp)) {
2317 * Do not process, in particular, do not handle the
2318 * B_INVAL/B_RELBUF and do not release to free list.
2324 if (bp->b_flags & B_MANAGED) {
2329 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2330 BO_LOCK(bp->b_bufobj);
2331 bp->b_vflags &= ~BV_BKGRDERR;
2332 BO_UNLOCK(bp->b_bufobj);
2335 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2336 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2337 !(bp->b_flags & B_INVAL)) {
2339 * Failed write, redirty. All errors except ENXIO (which
2340 * means the device is gone) are expected to be potentially
2341 * transient - underlying media might work if tried again
2342 * after EIO, and memory might be available after an ENOMEM.
2344 * Do this also for buffers that failed with ENXIO, but have
2345 * non-empty dependencies - the soft updates code might need
2346 * to access the buffer to untangle them.
2348 * Must clear BIO_ERROR to prevent pages from being scrapped.
2350 bp->b_ioflags &= ~BIO_ERROR;
2352 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2353 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2355 * Either a failed read I/O, or we were asked to free or not
2356 * cache the buffer, or we failed to write to a device that's
2357 * no longer present.
2359 bp->b_flags |= B_INVAL;
2360 if (!LIST_EMPTY(&bp->b_dep))
2362 if (bp->b_flags & B_DELWRI)
2364 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2365 if ((bp->b_flags & B_VMIO) == 0) {
2373 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2374 * is called with B_DELWRI set, the underlying pages may wind up
2375 * getting freed causing a previous write (bdwrite()) to get 'lost'
2376 * because pages associated with a B_DELWRI bp are marked clean.
2378 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2379 * if B_DELWRI is set.
2381 if (bp->b_flags & B_DELWRI)
2382 bp->b_flags &= ~B_RELBUF;
2385 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2386 * constituted, not even NFS buffers now. Two flags effect this. If
2387 * B_INVAL, the struct buf is invalidated but the VM object is kept
2388 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2390 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2391 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2392 * buffer is also B_INVAL because it hits the re-dirtying code above.
2394 * Normally we can do this whether a buffer is B_DELWRI or not. If
2395 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2396 * the commit state and we cannot afford to lose the buffer. If the
2397 * buffer has a background write in progress, we need to keep it
2398 * around to prevent it from being reconstituted and starting a second
2401 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2402 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2403 !(bp->b_vp->v_mount != NULL &&
2404 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2405 !vn_isdisk(bp->b_vp, NULL) && (bp->b_flags & B_DELWRI))) {
2406 vfs_vmio_invalidate(bp);
2410 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2411 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2413 bp->b_flags &= ~B_NOREUSE;
2414 if (bp->b_vp != NULL)
2419 * If the buffer has junk contents signal it and eventually
2420 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2423 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2424 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2425 bp->b_flags |= B_INVAL;
2426 if (bp->b_flags & B_INVAL) {
2427 if (bp->b_flags & B_DELWRI)
2433 /* buffers with no memory */
2434 if (bp->b_bufsize == 0) {
2438 /* buffers with junk contents */
2439 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2440 (bp->b_ioflags & BIO_ERROR)) {
2441 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2442 if (bp->b_vflags & BV_BKGRDINPROG)
2443 panic("losing buffer 2");
2444 qindex = QUEUE_CLEAN;
2445 bp->b_flags |= B_AGE;
2446 /* remaining buffers */
2447 } else if (bp->b_flags & B_DELWRI)
2448 qindex = QUEUE_DIRTY;
2450 qindex = QUEUE_CLEAN;
2452 binsfree(bp, qindex);
2454 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT);
2455 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2456 panic("brelse: not dirty");
2459 if (qindex == QUEUE_CLEAN)
2464 * Release a buffer back to the appropriate queue but do not try to free
2465 * it. The buffer is expected to be used again soon.
2467 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2468 * biodone() to requeue an async I/O on completion. It is also used when
2469 * known good buffers need to be requeued but we think we may need the data
2472 * XXX we should be able to leave the B_RELBUF hint set on completion.
2475 bqrelse(struct buf *bp)
2479 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2480 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2481 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2483 qindex = QUEUE_NONE;
2484 if (BUF_LOCKRECURSED(bp)) {
2485 /* do not release to free list */
2489 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2491 if (bp->b_flags & B_MANAGED) {
2492 if (bp->b_flags & B_REMFREE)
2497 /* buffers with stale but valid contents */
2498 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2499 BV_BKGRDERR)) == BV_BKGRDERR) {
2500 BO_LOCK(bp->b_bufobj);
2501 bp->b_vflags &= ~BV_BKGRDERR;
2502 BO_UNLOCK(bp->b_bufobj);
2503 qindex = QUEUE_DIRTY;
2505 if ((bp->b_flags & B_DELWRI) == 0 &&
2506 (bp->b_xflags & BX_VNDIRTY))
2507 panic("bqrelse: not dirty");
2508 if ((bp->b_flags & B_NOREUSE) != 0) {
2512 qindex = QUEUE_CLEAN;
2514 binsfree(bp, qindex);
2519 if (qindex == QUEUE_CLEAN)
2524 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2525 * restore bogus pages.
2528 vfs_vmio_iodone(struct buf *bp)
2534 int i, iosize, resid;
2537 obj = bp->b_bufobj->bo_object;
2538 KASSERT(obj->paging_in_progress >= bp->b_npages,
2539 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2540 obj->paging_in_progress, bp->b_npages));
2543 KASSERT(vp->v_holdcnt > 0,
2544 ("vfs_vmio_iodone: vnode %p has zero hold count", vp));
2545 KASSERT(vp->v_object != NULL,
2546 ("vfs_vmio_iodone: vnode %p has no vm_object", vp));
2548 foff = bp->b_offset;
2549 KASSERT(bp->b_offset != NOOFFSET,
2550 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2553 iosize = bp->b_bcount - bp->b_resid;
2554 VM_OBJECT_WLOCK(obj);
2555 for (i = 0; i < bp->b_npages; i++) {
2556 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2561 * cleanup bogus pages, restoring the originals
2564 if (m == bogus_page) {
2566 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2568 panic("biodone: page disappeared!");
2570 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2572 * In the write case, the valid and clean bits are
2573 * already changed correctly ( see bdwrite() ), so we
2574 * only need to do this here in the read case.
2576 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2577 resid)) == 0, ("vfs_vmio_iodone: page %p "
2578 "has unexpected dirty bits", m));
2579 vfs_page_set_valid(bp, foff, m);
2581 KASSERT(OFF_TO_IDX(foff) == m->pindex,
2582 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
2583 (intmax_t)foff, (uintmax_t)m->pindex));
2586 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2589 vm_object_pip_wakeupn(obj, bp->b_npages);
2590 VM_OBJECT_WUNLOCK(obj);
2591 if (bogus && buf_mapped(bp)) {
2592 BUF_CHECK_MAPPED(bp);
2593 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2594 bp->b_pages, bp->b_npages);
2599 * Unwire a page held by a buf and place it on the appropriate vm queue.
2602 vfs_vmio_unwire(struct buf *bp, vm_page_t m)
2607 if (vm_page_unwire(m, PQ_NONE)) {
2609 * Determine if the page should be freed before adding
2610 * it to the inactive queue.
2612 if (m->valid == 0) {
2613 freed = !vm_page_busied(m);
2616 } else if ((bp->b_flags & B_DIRECT) != 0)
2617 freed = vm_page_try_to_free(m);
2622 * If the page is unlikely to be reused, let the
2623 * VM know. Otherwise, maintain LRU page
2624 * ordering and put the page at the tail of the
2627 if ((bp->b_flags & B_NOREUSE) != 0)
2628 vm_page_deactivate_noreuse(m);
2630 vm_page_deactivate(m);
2637 * Perform page invalidation when a buffer is released. The fully invalid
2638 * pages will be reclaimed later in vfs_vmio_truncate().
2641 vfs_vmio_invalidate(struct buf *bp)
2645 int i, resid, poffset, presid;
2647 if (buf_mapped(bp)) {
2648 BUF_CHECK_MAPPED(bp);
2649 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
2651 BUF_CHECK_UNMAPPED(bp);
2653 * Get the base offset and length of the buffer. Note that
2654 * in the VMIO case if the buffer block size is not
2655 * page-aligned then b_data pointer may not be page-aligned.
2656 * But our b_pages[] array *IS* page aligned.
2658 * block sizes less then DEV_BSIZE (usually 512) are not
2659 * supported due to the page granularity bits (m->valid,
2660 * m->dirty, etc...).
2662 * See man buf(9) for more information
2664 obj = bp->b_bufobj->bo_object;
2665 resid = bp->b_bufsize;
2666 poffset = bp->b_offset & PAGE_MASK;
2667 VM_OBJECT_WLOCK(obj);
2668 for (i = 0; i < bp->b_npages; i++) {
2670 if (m == bogus_page)
2671 panic("vfs_vmio_invalidate: Unexpected bogus page.");
2672 bp->b_pages[i] = NULL;
2674 presid = resid > (PAGE_SIZE - poffset) ?
2675 (PAGE_SIZE - poffset) : resid;
2676 KASSERT(presid >= 0, ("brelse: extra page"));
2677 while (vm_page_xbusied(m)) {
2679 VM_OBJECT_WUNLOCK(obj);
2680 vm_page_busy_sleep(m, "mbncsh", true);
2681 VM_OBJECT_WLOCK(obj);
2683 if (pmap_page_wired_mappings(m) == 0)
2684 vm_page_set_invalid(m, poffset, presid);
2685 vfs_vmio_unwire(bp, m);
2689 VM_OBJECT_WUNLOCK(obj);
2694 * Page-granular truncation of an existing VMIO buffer.
2697 vfs_vmio_truncate(struct buf *bp, int desiredpages)
2703 if (bp->b_npages == desiredpages)
2706 if (buf_mapped(bp)) {
2707 BUF_CHECK_MAPPED(bp);
2708 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
2709 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
2711 BUF_CHECK_UNMAPPED(bp);
2712 obj = bp->b_bufobj->bo_object;
2714 VM_OBJECT_WLOCK(obj);
2715 for (i = desiredpages; i < bp->b_npages; i++) {
2717 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
2718 bp->b_pages[i] = NULL;
2719 vfs_vmio_unwire(bp, m);
2722 VM_OBJECT_WUNLOCK(obj);
2723 bp->b_npages = desiredpages;
2727 * Byte granular extension of VMIO buffers.
2730 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
2733 * We are growing the buffer, possibly in a
2734 * byte-granular fashion.
2742 * Step 1, bring in the VM pages from the object, allocating
2743 * them if necessary. We must clear B_CACHE if these pages
2744 * are not valid for the range covered by the buffer.
2746 obj = bp->b_bufobj->bo_object;
2747 VM_OBJECT_WLOCK(obj);
2748 if (bp->b_npages < desiredpages) {
2750 * We must allocate system pages since blocking
2751 * here could interfere with paging I/O, no
2752 * matter which process we are.
2754 * Only exclusive busy can be tested here.
2755 * Blocking on shared busy might lead to
2756 * deadlocks once allocbuf() is called after
2757 * pages are vfs_busy_pages().
2759 (void)vm_page_grab_pages(obj,
2760 OFF_TO_IDX(bp->b_offset) + bp->b_npages,
2761 VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
2762 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
2763 &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
2764 bp->b_npages = desiredpages;
2768 * Step 2. We've loaded the pages into the buffer,
2769 * we have to figure out if we can still have B_CACHE
2770 * set. Note that B_CACHE is set according to the
2771 * byte-granular range ( bcount and size ), not the
2772 * aligned range ( newbsize ).
2774 * The VM test is against m->valid, which is DEV_BSIZE
2775 * aligned. Needless to say, the validity of the data
2776 * needs to also be DEV_BSIZE aligned. Note that this
2777 * fails with NFS if the server or some other client
2778 * extends the file's EOF. If our buffer is resized,
2779 * B_CACHE may remain set! XXX
2781 toff = bp->b_bcount;
2782 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2783 while ((bp->b_flags & B_CACHE) && toff < size) {
2786 if (tinc > (size - toff))
2788 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
2789 m = bp->b_pages[pi];
2790 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
2794 VM_OBJECT_WUNLOCK(obj);
2797 * Step 3, fixup the KVA pmap.
2802 BUF_CHECK_UNMAPPED(bp);
2806 * Check to see if a block at a particular lbn is available for a clustered
2810 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
2817 /* If the buf isn't in core skip it */
2818 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
2821 /* If the buf is busy we don't want to wait for it */
2822 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
2825 /* Only cluster with valid clusterable delayed write buffers */
2826 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
2827 (B_DELWRI | B_CLUSTEROK))
2830 if (bpa->b_bufsize != size)
2834 * Check to see if it is in the expected place on disk and that the
2835 * block has been mapped.
2837 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
2847 * Implement clustered async writes for clearing out B_DELWRI buffers.
2848 * This is much better then the old way of writing only one buffer at
2849 * a time. Note that we may not be presented with the buffers in the
2850 * correct order, so we search for the cluster in both directions.
2853 vfs_bio_awrite(struct buf *bp)
2858 daddr_t lblkno = bp->b_lblkno;
2859 struct vnode *vp = bp->b_vp;
2867 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
2869 * right now we support clustered writing only to regular files. If
2870 * we find a clusterable block we could be in the middle of a cluster
2871 * rather then at the beginning.
2873 if ((vp->v_type == VREG) &&
2874 (vp->v_mount != 0) && /* Only on nodes that have the size info */
2875 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
2877 size = vp->v_mount->mnt_stat.f_iosize;
2878 maxcl = MAXPHYS / size;
2881 for (i = 1; i < maxcl; i++)
2882 if (vfs_bio_clcheck(vp, size, lblkno + i,
2883 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
2886 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
2887 if (vfs_bio_clcheck(vp, size, lblkno - j,
2888 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
2894 * this is a possible cluster write
2898 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
2904 bp->b_flags |= B_ASYNC;
2906 * default (old) behavior, writing out only one block
2908 * XXX returns b_bufsize instead of b_bcount for nwritten?
2910 nwritten = bp->b_bufsize;
2919 * Allocate KVA for an empty buf header according to gbflags.
2922 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
2925 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
2927 * In order to keep fragmentation sane we only allocate kva
2928 * in BKVASIZE chunks. XXX with vmem we can do page size.
2930 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2932 if (maxsize != bp->b_kvasize &&
2933 bufkva_alloc(bp, maxsize, gbflags))
2942 * Find and initialize a new buffer header, freeing up existing buffers
2943 * in the bufqueues as necessary. The new buffer is returned locked.
2946 * We have insufficient buffer headers
2947 * We have insufficient buffer space
2948 * buffer_arena is too fragmented ( space reservation fails )
2949 * If we have to flush dirty buffers ( but we try to avoid this )
2951 * The caller is responsible for releasing the reserved bufspace after
2952 * allocbuf() is called.
2955 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
2958 bool metadata, reserved;
2961 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
2962 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
2963 if (!unmapped_buf_allowed)
2964 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
2966 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
2971 atomic_add_int(&getnewbufcalls, 1);
2974 if (reserved == false &&
2975 bufspace_reserve(maxsize, metadata) != 0)
2978 if ((bp = buf_alloc()) == NULL)
2980 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
2983 } while(buf_scan(false) == 0);
2986 atomic_subtract_long(&bufspace, maxsize);
2988 bp->b_flags |= B_INVAL;
2991 bufspace_wait(vp, gbflags, slpflag, slptimeo);
2999 * buffer flushing daemon. Buffers are normally flushed by the
3000 * update daemon but if it cannot keep up this process starts to
3001 * take the load in an attempt to prevent getnewbuf() from blocking.
3003 static struct kproc_desc buf_kp = {
3008 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3011 buf_flush(struct vnode *vp, int target)
3015 flushed = flushbufqueues(vp, target, 0);
3018 * Could not find any buffers without rollback
3019 * dependencies, so just write the first one
3020 * in the hopes of eventually making progress.
3022 if (vp != NULL && target > 2)
3024 flushbufqueues(vp, target, 1);
3035 * This process needs to be suspended prior to shutdown sync.
3037 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc,
3041 * This process is allowed to take the buffer cache to the limit
3043 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3047 mtx_unlock(&bdlock);
3049 kproc_suspend_check(bufdaemonproc);
3050 lodirty = lodirtybuffers;
3051 if (bd_speedupreq) {
3052 lodirty = numdirtybuffers / 2;
3056 * Do the flush. Limit the amount of in-transit I/O we
3057 * allow to build up, otherwise we would completely saturate
3060 while (numdirtybuffers > lodirty) {
3061 if (buf_flush(NULL, numdirtybuffers - lodirty) == 0)
3063 kern_yield(PRI_USER);
3067 * Only clear bd_request if we have reached our low water
3068 * mark. The buf_daemon normally waits 1 second and
3069 * then incrementally flushes any dirty buffers that have
3070 * built up, within reason.
3072 * If we were unable to hit our low water mark and couldn't
3073 * find any flushable buffers, we sleep for a short period
3074 * to avoid endless loops on unlockable buffers.
3077 if (numdirtybuffers <= lodirtybuffers) {
3079 * We reached our low water mark, reset the
3080 * request and sleep until we are needed again.
3081 * The sleep is just so the suspend code works.
3085 * Do an extra wakeup in case dirty threshold
3086 * changed via sysctl and the explicit transition
3087 * out of shortfall was missed.
3090 if (runningbufspace <= lorunningspace)
3092 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3095 * We couldn't find any flushable dirty buffers but
3096 * still have too many dirty buffers, we
3097 * have to sleep and try again. (rare)
3099 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3107 * Try to flush a buffer in the dirty queue. We must be careful to
3108 * free up B_INVAL buffers instead of write them, which NFS is
3109 * particularly sensitive to.
3111 static int flushwithdeps = 0;
3112 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps,
3113 0, "Number of buffers flushed with dependecies that require rollbacks");
3116 flushbufqueues(struct vnode *lvp, int target, int flushdeps)
3118 struct buf *sentinel;
3129 queue = QUEUE_DIRTY;
3131 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3132 sentinel->b_qindex = QUEUE_SENTINEL;
3133 mtx_lock(&bqlocks[queue]);
3134 TAILQ_INSERT_HEAD(&bufqueues[queue], sentinel, b_freelist);
3135 mtx_unlock(&bqlocks[queue]);
3136 while (flushed != target) {
3138 mtx_lock(&bqlocks[queue]);
3139 bp = TAILQ_NEXT(sentinel, b_freelist);
3141 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3142 TAILQ_INSERT_AFTER(&bufqueues[queue], bp, sentinel,
3145 mtx_unlock(&bqlocks[queue]);
3149 * Skip sentinels inserted by other invocations of the
3150 * flushbufqueues(), taking care to not reorder them.
3152 * Only flush the buffers that belong to the
3153 * vnode locked by the curthread.
3155 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3157 mtx_unlock(&bqlocks[queue]);
3160 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3161 mtx_unlock(&bqlocks[queue]);
3164 if (bp->b_pin_count > 0) {
3169 * BKGRDINPROG can only be set with the buf and bufobj
3170 * locks both held. We tolerate a race to clear it here.
3172 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3173 (bp->b_flags & B_DELWRI) == 0) {
3177 if (bp->b_flags & B_INVAL) {
3184 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3185 if (flushdeps == 0) {
3193 * We must hold the lock on a vnode before writing
3194 * one of its buffers. Otherwise we may confuse, or
3195 * in the case of a snapshot vnode, deadlock the
3198 * The lock order here is the reverse of the normal
3199 * of vnode followed by buf lock. This is ok because
3200 * the NOWAIT will prevent deadlock.
3203 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3209 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3211 ASSERT_VOP_LOCKED(vp, "getbuf");
3213 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3214 vn_lock(vp, LK_TRYUPGRADE);
3217 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3218 bp, bp->b_vp, bp->b_flags);
3219 if (curproc == bufdaemonproc) {
3226 vn_finished_write(mp);
3229 flushwithdeps += hasdeps;
3233 * Sleeping on runningbufspace while holding
3234 * vnode lock leads to deadlock.
3236 if (curproc == bufdaemonproc &&
3237 runningbufspace > hirunningspace)
3238 waitrunningbufspace();
3241 vn_finished_write(mp);
3244 mtx_lock(&bqlocks[queue]);
3245 TAILQ_REMOVE(&bufqueues[queue], sentinel, b_freelist);
3246 mtx_unlock(&bqlocks[queue]);
3247 free(sentinel, M_TEMP);
3252 * Check to see if a block is currently memory resident.
3255 incore(struct bufobj *bo, daddr_t blkno)
3260 bp = gbincore(bo, blkno);
3266 * Returns true if no I/O is needed to access the
3267 * associated VM object. This is like incore except
3268 * it also hunts around in the VM system for the data.
3272 inmem(struct vnode * vp, daddr_t blkno)
3275 vm_offset_t toff, tinc, size;
3279 ASSERT_VOP_LOCKED(vp, "inmem");
3281 if (incore(&vp->v_bufobj, blkno))
3283 if (vp->v_mount == NULL)
3290 if (size > vp->v_mount->mnt_stat.f_iosize)
3291 size = vp->v_mount->mnt_stat.f_iosize;
3292 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3294 VM_OBJECT_RLOCK(obj);
3295 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3296 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
3300 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3301 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3302 if (vm_page_is_valid(m,
3303 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
3306 VM_OBJECT_RUNLOCK(obj);
3310 VM_OBJECT_RUNLOCK(obj);
3315 * Set the dirty range for a buffer based on the status of the dirty
3316 * bits in the pages comprising the buffer. The range is limited
3317 * to the size of the buffer.
3319 * Tell the VM system that the pages associated with this buffer
3320 * are clean. This is used for delayed writes where the data is
3321 * going to go to disk eventually without additional VM intevention.
3323 * Note that while we only really need to clean through to b_bcount, we
3324 * just go ahead and clean through to b_bufsize.
3327 vfs_clean_pages_dirty_buf(struct buf *bp)
3329 vm_ooffset_t foff, noff, eoff;
3333 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3336 foff = bp->b_offset;
3337 KASSERT(bp->b_offset != NOOFFSET,
3338 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3340 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
3341 vfs_drain_busy_pages(bp);
3342 vfs_setdirty_locked_object(bp);
3343 for (i = 0; i < bp->b_npages; i++) {
3344 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3346 if (eoff > bp->b_offset + bp->b_bufsize)
3347 eoff = bp->b_offset + bp->b_bufsize;
3349 vfs_page_set_validclean(bp, foff, m);
3350 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3353 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
3357 vfs_setdirty_locked_object(struct buf *bp)
3362 object = bp->b_bufobj->bo_object;
3363 VM_OBJECT_ASSERT_WLOCKED(object);
3366 * We qualify the scan for modified pages on whether the
3367 * object has been flushed yet.
3369 if ((object->flags & OBJ_MIGHTBEDIRTY) != 0) {
3370 vm_offset_t boffset;
3371 vm_offset_t eoffset;
3374 * test the pages to see if they have been modified directly
3375 * by users through the VM system.
3377 for (i = 0; i < bp->b_npages; i++)
3378 vm_page_test_dirty(bp->b_pages[i]);
3381 * Calculate the encompassing dirty range, boffset and eoffset,
3382 * (eoffset - boffset) bytes.
3385 for (i = 0; i < bp->b_npages; i++) {
3386 if (bp->b_pages[i]->dirty)
3389 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3391 for (i = bp->b_npages - 1; i >= 0; --i) {
3392 if (bp->b_pages[i]->dirty) {
3396 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3399 * Fit it to the buffer.
3402 if (eoffset > bp->b_bcount)
3403 eoffset = bp->b_bcount;
3406 * If we have a good dirty range, merge with the existing
3410 if (boffset < eoffset) {
3411 if (bp->b_dirtyoff > boffset)
3412 bp->b_dirtyoff = boffset;
3413 if (bp->b_dirtyend < eoffset)
3414 bp->b_dirtyend = eoffset;
3420 * Allocate the KVA mapping for an existing buffer.
3421 * If an unmapped buffer is provided but a mapped buffer is requested, take
3422 * also care to properly setup mappings between pages and KVA.
3425 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3427 int bsize, maxsize, need_mapping, need_kva;
3430 need_mapping = bp->b_data == unmapped_buf &&
3431 (gbflags & GB_UNMAPPED) == 0;
3432 need_kva = bp->b_kvabase == unmapped_buf &&
3433 bp->b_data == unmapped_buf &&
3434 (gbflags & GB_KVAALLOC) != 0;
3435 if (!need_mapping && !need_kva)
3438 BUF_CHECK_UNMAPPED(bp);
3440 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3442 * Buffer is not mapped, but the KVA was already
3443 * reserved at the time of the instantiation. Use the
3450 * Calculate the amount of the address space we would reserve
3451 * if the buffer was mapped.
3453 bsize = vn_isdisk(bp->b_vp, NULL) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3454 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3455 offset = blkno * bsize;
3456 maxsize = size + (offset & PAGE_MASK);
3457 maxsize = imax(maxsize, bsize);
3459 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3460 if ((gbflags & GB_NOWAIT_BD) != 0) {
3462 * XXXKIB: defragmentation cannot
3463 * succeed, not sure what else to do.
3465 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3467 atomic_add_int(&mappingrestarts, 1);
3468 bufspace_wait(bp->b_vp, gbflags, 0, 0);
3472 /* b_offset is handled by bpmap_qenter. */
3473 bp->b_data = bp->b_kvabase;
3474 BUF_CHECK_MAPPED(bp);
3482 * Get a block given a specified block and offset into a file/device.
3483 * The buffers B_DONE bit will be cleared on return, making it almost
3484 * ready for an I/O initiation. B_INVAL may or may not be set on
3485 * return. The caller should clear B_INVAL prior to initiating a
3488 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3489 * an existing buffer.
3491 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3492 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3493 * and then cleared based on the backing VM. If the previous buffer is
3494 * non-0-sized but invalid, B_CACHE will be cleared.
3496 * If getblk() must create a new buffer, the new buffer is returned with
3497 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3498 * case it is returned with B_INVAL clear and B_CACHE set based on the
3501 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
3502 * B_CACHE bit is clear.
3504 * What this means, basically, is that the caller should use B_CACHE to
3505 * determine whether the buffer is fully valid or not and should clear
3506 * B_INVAL prior to issuing a read. If the caller intends to validate
3507 * the buffer by loading its data area with something, the caller needs
3508 * to clear B_INVAL. If the caller does this without issuing an I/O,
3509 * the caller should set B_CACHE ( as an optimization ), else the caller
3510 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3511 * a write attempt or if it was a successful read. If the caller
3512 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3513 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3516 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3521 int bsize, error, maxsize, vmio;
3524 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3525 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3526 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3527 ASSERT_VOP_LOCKED(vp, "getblk");
3528 if (size > maxbcachebuf)
3529 panic("getblk: size(%d) > maxbcachebuf(%d)\n", size,
3531 if (!unmapped_buf_allowed)
3532 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3537 bp = gbincore(bo, blkno);
3541 * Buffer is in-core. If the buffer is not busy nor managed,
3542 * it must be on a queue.
3544 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK;
3546 if (flags & GB_LOCK_NOWAIT)
3547 lockflags |= LK_NOWAIT;
3549 error = BUF_TIMELOCK(bp, lockflags,
3550 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
3553 * If we slept and got the lock we have to restart in case
3554 * the buffer changed identities.
3556 if (error == ENOLCK)
3558 /* We timed out or were interrupted. */
3561 /* If recursed, assume caller knows the rules. */
3562 else if (BUF_LOCKRECURSED(bp))
3566 * The buffer is locked. B_CACHE is cleared if the buffer is
3567 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
3568 * and for a VMIO buffer B_CACHE is adjusted according to the
3571 if (bp->b_flags & B_INVAL)
3572 bp->b_flags &= ~B_CACHE;
3573 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
3574 bp->b_flags |= B_CACHE;
3575 if (bp->b_flags & B_MANAGED)
3576 MPASS(bp->b_qindex == QUEUE_NONE);
3581 * check for size inconsistencies for non-VMIO case.
3583 if (bp->b_bcount != size) {
3584 if ((bp->b_flags & B_VMIO) == 0 ||
3585 (size > bp->b_kvasize)) {
3586 if (bp->b_flags & B_DELWRI) {
3588 * If buffer is pinned and caller does
3589 * not want sleep waiting for it to be
3590 * unpinned, bail out
3592 if (bp->b_pin_count > 0) {
3593 if (flags & GB_LOCK_NOWAIT) {
3600 bp->b_flags |= B_NOCACHE;
3603 if (LIST_EMPTY(&bp->b_dep)) {
3604 bp->b_flags |= B_RELBUF;
3607 bp->b_flags |= B_NOCACHE;
3616 * Handle the case of unmapped buffer which should
3617 * become mapped, or the buffer for which KVA
3618 * reservation is requested.
3620 bp_unmapped_get_kva(bp, blkno, size, flags);
3623 * If the size is inconsistent in the VMIO case, we can resize
3624 * the buffer. This might lead to B_CACHE getting set or
3625 * cleared. If the size has not changed, B_CACHE remains
3626 * unchanged from its previous state.
3630 KASSERT(bp->b_offset != NOOFFSET,
3631 ("getblk: no buffer offset"));
3634 * A buffer with B_DELWRI set and B_CACHE clear must
3635 * be committed before we can return the buffer in
3636 * order to prevent the caller from issuing a read
3637 * ( due to B_CACHE not being set ) and overwriting
3640 * Most callers, including NFS and FFS, need this to
3641 * operate properly either because they assume they
3642 * can issue a read if B_CACHE is not set, or because
3643 * ( for example ) an uncached B_DELWRI might loop due
3644 * to softupdates re-dirtying the buffer. In the latter
3645 * case, B_CACHE is set after the first write completes,
3646 * preventing further loops.
3647 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3648 * above while extending the buffer, we cannot allow the
3649 * buffer to remain with B_CACHE set after the write
3650 * completes or it will represent a corrupt state. To
3651 * deal with this we set B_NOCACHE to scrap the buffer
3654 * We might be able to do something fancy, like setting
3655 * B_CACHE in bwrite() except if B_DELWRI is already set,
3656 * so the below call doesn't set B_CACHE, but that gets real
3657 * confusing. This is much easier.
3660 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3661 bp->b_flags |= B_NOCACHE;
3665 bp->b_flags &= ~B_DONE;
3668 * Buffer is not in-core, create new buffer. The buffer
3669 * returned by getnewbuf() is locked. Note that the returned
3670 * buffer is also considered valid (not marked B_INVAL).
3674 * If the user does not want us to create the buffer, bail out
3677 if (flags & GB_NOCREAT)
3679 if (numfreebuffers == 0 && TD_IS_IDLETHREAD(curthread))
3682 bsize = vn_isdisk(vp, NULL) ? DEV_BSIZE : bo->bo_bsize;
3683 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3684 offset = blkno * bsize;
3685 vmio = vp->v_object != NULL;
3687 maxsize = size + (offset & PAGE_MASK);
3690 /* Do not allow non-VMIO notmapped buffers. */
3691 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3693 maxsize = imax(maxsize, bsize);
3695 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
3697 if (slpflag || slptimeo)
3700 * XXX This is here until the sleep path is diagnosed
3701 * enough to work under very low memory conditions.
3703 * There's an issue on low memory, 4BSD+non-preempt
3704 * systems (eg MIPS routers with 32MB RAM) where buffer
3705 * exhaustion occurs without sleeping for buffer
3706 * reclaimation. This just sticks in a loop and
3707 * constantly attempts to allocate a buffer, which
3708 * hits exhaustion and tries to wakeup bufdaemon.
3709 * This never happens because we never yield.
3711 * The real solution is to identify and fix these cases
3712 * so we aren't effectively busy-waiting in a loop
3713 * until the reclaimation path has cycles to run.
3715 kern_yield(PRI_USER);
3720 * This code is used to make sure that a buffer is not
3721 * created while the getnewbuf routine is blocked.
3722 * This can be a problem whether the vnode is locked or not.
3723 * If the buffer is created out from under us, we have to
3724 * throw away the one we just created.
3726 * Note: this must occur before we associate the buffer
3727 * with the vp especially considering limitations in
3728 * the splay tree implementation when dealing with duplicate
3732 if (gbincore(bo, blkno)) {
3734 bp->b_flags |= B_INVAL;
3736 bufspace_release(maxsize);
3741 * Insert the buffer into the hash, so that it can
3742 * be found by incore.
3744 bp->b_blkno = bp->b_lblkno = blkno;
3745 bp->b_offset = offset;
3750 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
3751 * buffer size starts out as 0, B_CACHE will be set by
3752 * allocbuf() for the VMIO case prior to it testing the
3753 * backing store for validity.
3757 bp->b_flags |= B_VMIO;
3758 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
3759 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
3760 bp, vp->v_object, bp->b_bufobj->bo_object));
3762 bp->b_flags &= ~B_VMIO;
3763 KASSERT(bp->b_bufobj->bo_object == NULL,
3764 ("ARGH! has b_bufobj->bo_object %p %p\n",
3765 bp, bp->b_bufobj->bo_object));
3766 BUF_CHECK_MAPPED(bp);
3770 bufspace_release(maxsize);
3771 bp->b_flags &= ~B_DONE;
3773 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
3774 BUF_ASSERT_HELD(bp);
3776 KASSERT(bp->b_bufobj == bo,
3777 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3782 * Get an empty, disassociated buffer of given size. The buffer is initially
3786 geteblk(int size, int flags)
3791 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3792 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
3793 if ((flags & GB_NOWAIT_BD) &&
3794 (curthread->td_pflags & TDP_BUFNEED) != 0)
3798 bufspace_release(maxsize);
3799 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3800 BUF_ASSERT_HELD(bp);
3805 * Truncate the backing store for a non-vmio buffer.
3808 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
3811 if (bp->b_flags & B_MALLOC) {
3813 * malloced buffers are not shrunk
3815 if (newbsize == 0) {
3816 bufmallocadjust(bp, 0);
3817 free(bp->b_data, M_BIOBUF);
3818 bp->b_data = bp->b_kvabase;
3819 bp->b_flags &= ~B_MALLOC;
3823 vm_hold_free_pages(bp, newbsize);
3824 bufspace_adjust(bp, newbsize);
3828 * Extend the backing for a non-VMIO buffer.
3831 vfs_nonvmio_extend(struct buf *bp, int newbsize)
3837 * We only use malloced memory on the first allocation.
3838 * and revert to page-allocated memory when the buffer
3841 * There is a potential smp race here that could lead
3842 * to bufmallocspace slightly passing the max. It
3843 * is probably extremely rare and not worth worrying
3846 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
3847 bufmallocspace < maxbufmallocspace) {
3848 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
3849 bp->b_flags |= B_MALLOC;
3850 bufmallocadjust(bp, newbsize);
3855 * If the buffer is growing on its other-than-first
3856 * allocation then we revert to the page-allocation
3861 if (bp->b_flags & B_MALLOC) {
3862 origbuf = bp->b_data;
3863 origbufsize = bp->b_bufsize;
3864 bp->b_data = bp->b_kvabase;
3865 bufmallocadjust(bp, 0);
3866 bp->b_flags &= ~B_MALLOC;
3867 newbsize = round_page(newbsize);
3869 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
3870 (vm_offset_t) bp->b_data + newbsize);
3871 if (origbuf != NULL) {
3872 bcopy(origbuf, bp->b_data, origbufsize);
3873 free(origbuf, M_BIOBUF);
3875 bufspace_adjust(bp, newbsize);
3879 * This code constitutes the buffer memory from either anonymous system
3880 * memory (in the case of non-VMIO operations) or from an associated
3881 * VM object (in the case of VMIO operations). This code is able to
3882 * resize a buffer up or down.
3884 * Note that this code is tricky, and has many complications to resolve
3885 * deadlock or inconsistent data situations. Tread lightly!!!
3886 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3887 * the caller. Calling this code willy nilly can result in the loss of data.
3889 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3890 * B_CACHE for the non-VMIO case.
3893 allocbuf(struct buf *bp, int size)
3897 BUF_ASSERT_HELD(bp);
3899 if (bp->b_bcount == size)
3902 if (bp->b_kvasize != 0 && bp->b_kvasize < size)
3903 panic("allocbuf: buffer too small");
3905 newbsize = roundup2(size, DEV_BSIZE);
3906 if ((bp->b_flags & B_VMIO) == 0) {
3907 if ((bp->b_flags & B_MALLOC) == 0)
3908 newbsize = round_page(newbsize);
3910 * Just get anonymous memory from the kernel. Don't
3911 * mess with B_CACHE.
3913 if (newbsize < bp->b_bufsize)
3914 vfs_nonvmio_truncate(bp, newbsize);
3915 else if (newbsize > bp->b_bufsize)
3916 vfs_nonvmio_extend(bp, newbsize);
3920 desiredpages = (size == 0) ? 0 :
3921 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
3923 if (bp->b_flags & B_MALLOC)
3924 panic("allocbuf: VMIO buffer can't be malloced");
3926 * Set B_CACHE initially if buffer is 0 length or will become
3929 if (size == 0 || bp->b_bufsize == 0)
3930 bp->b_flags |= B_CACHE;
3932 if (newbsize < bp->b_bufsize)
3933 vfs_vmio_truncate(bp, desiredpages);
3934 /* XXX This looks as if it should be newbsize > b_bufsize */
3935 else if (size > bp->b_bcount)
3936 vfs_vmio_extend(bp, desiredpages, size);
3937 bufspace_adjust(bp, newbsize);
3939 bp->b_bcount = size; /* requested buffer size. */
3943 extern int inflight_transient_maps;
3945 static struct bio_queue nondump_bios;
3948 biodone(struct bio *bp)
3951 void (*done)(struct bio *);
3952 vm_offset_t start, end;
3956 * Avoid completing I/O when dumping after a panic since that may
3957 * result in a deadlock in the filesystem or pager code. Note that
3958 * this doesn't affect dumps that were started manually since we aim
3959 * to keep the system usable after it has been resumed.
3961 if (__predict_false(dumping && SCHEDULER_STOPPED())) {
3962 TAILQ_INSERT_HEAD(&nondump_bios, bp, bio_queue);
3965 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
3966 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
3967 bp->bio_flags |= BIO_UNMAPPED;
3968 start = trunc_page((vm_offset_t)bp->bio_data);
3969 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
3970 bp->bio_data = unmapped_buf;
3971 pmap_qremove(start, atop(end - start));
3972 vmem_free(transient_arena, start, end - start);
3973 atomic_add_int(&inflight_transient_maps, -1);
3975 done = bp->bio_done;
3977 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3979 bp->bio_flags |= BIO_DONE;
3987 * Wait for a BIO to finish.
3990 biowait(struct bio *bp, const char *wchan)
3994 mtxp = mtx_pool_find(mtxpool_sleep, bp);
3996 while ((bp->bio_flags & BIO_DONE) == 0)
3997 msleep(bp, mtxp, PRIBIO, wchan, 0);
3999 if (bp->bio_error != 0)
4000 return (bp->bio_error);
4001 if (!(bp->bio_flags & BIO_ERROR))
4007 biofinish(struct bio *bp, struct devstat *stat, int error)
4011 bp->bio_error = error;
4012 bp->bio_flags |= BIO_ERROR;
4015 devstat_end_transaction_bio(stat, bp);
4022 * Wait for buffer I/O completion, returning error status. The buffer
4023 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
4024 * error and cleared.
4027 bufwait(struct buf *bp)
4029 if (bp->b_iocmd == BIO_READ)
4030 bwait(bp, PRIBIO, "biord");
4032 bwait(bp, PRIBIO, "biowr");
4033 if (bp->b_flags & B_EINTR) {
4034 bp->b_flags &= ~B_EINTR;
4037 if (bp->b_ioflags & BIO_ERROR) {
4038 return (bp->b_error ? bp->b_error : EIO);
4047 * Finish I/O on a buffer, optionally calling a completion function.
4048 * This is usually called from an interrupt so process blocking is
4051 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4052 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
4053 * assuming B_INVAL is clear.
4055 * For the VMIO case, we set B_CACHE if the op was a read and no
4056 * read error occurred, or if the op was a write. B_CACHE is never
4057 * set if the buffer is invalid or otherwise uncacheable.
4059 * bufdone does not mess with B_INVAL, allowing the I/O routine or the
4060 * initiator to leave B_INVAL set to brelse the buffer out of existence
4061 * in the biodone routine.
4064 bufdone(struct buf *bp)
4066 struct bufobj *dropobj;
4067 void (*biodone)(struct buf *);
4069 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4072 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4073 BUF_ASSERT_HELD(bp);
4075 runningbufwakeup(bp);
4076 if (bp->b_iocmd == BIO_WRITE)
4077 dropobj = bp->b_bufobj;
4078 /* call optional completion function if requested */
4079 if (bp->b_iodone != NULL) {
4080 biodone = bp->b_iodone;
4081 bp->b_iodone = NULL;
4084 bufobj_wdrop(dropobj);
4091 bufobj_wdrop(dropobj);
4095 bufdone_finish(struct buf *bp)
4097 BUF_ASSERT_HELD(bp);
4099 if (!LIST_EMPTY(&bp->b_dep))
4102 if (bp->b_flags & B_VMIO) {
4104 * Set B_CACHE if the op was a normal read and no error
4105 * occurred. B_CACHE is set for writes in the b*write()
4108 if (bp->b_iocmd == BIO_READ &&
4109 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4110 !(bp->b_ioflags & BIO_ERROR))
4111 bp->b_flags |= B_CACHE;
4112 vfs_vmio_iodone(bp);
4116 * For asynchronous completions, release the buffer now. The brelse
4117 * will do a wakeup there if necessary - so no need to do a wakeup
4118 * here in the async case. The sync case always needs to do a wakeup.
4120 if (bp->b_flags & B_ASYNC) {
4121 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4122 (bp->b_ioflags & BIO_ERROR))
4131 * This routine is called in lieu of iodone in the case of
4132 * incomplete I/O. This keeps the busy status for pages
4136 vfs_unbusy_pages(struct buf *bp)
4142 runningbufwakeup(bp);
4143 if (!(bp->b_flags & B_VMIO))
4146 obj = bp->b_bufobj->bo_object;
4147 VM_OBJECT_WLOCK(obj);
4148 for (i = 0; i < bp->b_npages; i++) {
4150 if (m == bogus_page) {
4151 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4153 panic("vfs_unbusy_pages: page missing\n");
4155 if (buf_mapped(bp)) {
4156 BUF_CHECK_MAPPED(bp);
4157 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4158 bp->b_pages, bp->b_npages);
4160 BUF_CHECK_UNMAPPED(bp);
4164 vm_object_pip_wakeupn(obj, bp->b_npages);
4165 VM_OBJECT_WUNLOCK(obj);
4169 * vfs_page_set_valid:
4171 * Set the valid bits in a page based on the supplied offset. The
4172 * range is restricted to the buffer's size.
4174 * This routine is typically called after a read completes.
4177 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4182 * Compute the end offset, eoff, such that [off, eoff) does not span a
4183 * page boundary and eoff is not greater than the end of the buffer.
4184 * The end of the buffer, in this case, is our file EOF, not the
4185 * allocation size of the buffer.
4187 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4188 if (eoff > bp->b_offset + bp->b_bcount)
4189 eoff = bp->b_offset + bp->b_bcount;
4192 * Set valid range. This is typically the entire buffer and thus the
4196 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4200 * vfs_page_set_validclean:
4202 * Set the valid bits and clear the dirty bits in a page based on the
4203 * supplied offset. The range is restricted to the buffer's size.
4206 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4208 vm_ooffset_t soff, eoff;
4211 * Start and end offsets in buffer. eoff - soff may not cross a
4212 * page boundary or cross the end of the buffer. The end of the
4213 * buffer, in this case, is our file EOF, not the allocation size
4217 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4218 if (eoff > bp->b_offset + bp->b_bcount)
4219 eoff = bp->b_offset + bp->b_bcount;
4222 * Set valid range. This is typically the entire buffer and thus the
4226 vm_page_set_validclean(
4228 (vm_offset_t) (soff & PAGE_MASK),
4229 (vm_offset_t) (eoff - soff)
4235 * Ensure that all buffer pages are not exclusive busied. If any page is
4236 * exclusive busy, drain it.
4239 vfs_drain_busy_pages(struct buf *bp)
4244 VM_OBJECT_ASSERT_WLOCKED(bp->b_bufobj->bo_object);
4246 for (i = 0; i < bp->b_npages; i++) {
4248 if (vm_page_xbusied(m)) {
4249 for (; last_busied < i; last_busied++)
4250 vm_page_sbusy(bp->b_pages[last_busied]);
4251 while (vm_page_xbusied(m)) {
4253 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4254 vm_page_busy_sleep(m, "vbpage", true);
4255 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4259 for (i = 0; i < last_busied; i++)
4260 vm_page_sunbusy(bp->b_pages[i]);
4264 * This routine is called before a device strategy routine.
4265 * It is used to tell the VM system that paging I/O is in
4266 * progress, and treat the pages associated with the buffer
4267 * almost as being exclusive busy. Also the object paging_in_progress
4268 * flag is handled to make sure that the object doesn't become
4271 * Since I/O has not been initiated yet, certain buffer flags
4272 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4273 * and should be ignored.
4276 vfs_busy_pages(struct buf *bp, int clear_modify)
4284 if (!(bp->b_flags & B_VMIO))
4287 obj = bp->b_bufobj->bo_object;
4288 foff = bp->b_offset;
4289 KASSERT(bp->b_offset != NOOFFSET,
4290 ("vfs_busy_pages: no buffer offset"));
4291 VM_OBJECT_WLOCK(obj);
4292 vfs_drain_busy_pages(bp);
4293 if (bp->b_bufsize != 0)
4294 vfs_setdirty_locked_object(bp);
4296 for (i = 0; i < bp->b_npages; i++) {
4299 if ((bp->b_flags & B_CLUSTER) == 0) {
4300 vm_object_pip_add(obj, 1);
4304 * When readying a buffer for a read ( i.e
4305 * clear_modify == 0 ), it is important to do
4306 * bogus_page replacement for valid pages in
4307 * partially instantiated buffers. Partially
4308 * instantiated buffers can, in turn, occur when
4309 * reconstituting a buffer from its VM backing store
4310 * base. We only have to do this if B_CACHE is
4311 * clear ( which causes the I/O to occur in the
4312 * first place ). The replacement prevents the read
4313 * I/O from overwriting potentially dirty VM-backed
4314 * pages. XXX bogus page replacement is, uh, bogus.
4315 * It may not work properly with small-block devices.
4316 * We need to find a better way.
4319 pmap_remove_write(m);
4320 vfs_page_set_validclean(bp, foff, m);
4321 } else if (m->valid == VM_PAGE_BITS_ALL &&
4322 (bp->b_flags & B_CACHE) == 0) {
4323 bp->b_pages[i] = bogus_page;
4326 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4328 VM_OBJECT_WUNLOCK(obj);
4329 if (bogus && buf_mapped(bp)) {
4330 BUF_CHECK_MAPPED(bp);
4331 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4332 bp->b_pages, bp->b_npages);
4337 * vfs_bio_set_valid:
4339 * Set the range within the buffer to valid. The range is
4340 * relative to the beginning of the buffer, b_offset. Note that
4341 * b_offset itself may be offset from the beginning of the first
4345 vfs_bio_set_valid(struct buf *bp, int base, int size)
4350 if (!(bp->b_flags & B_VMIO))
4354 * Fixup base to be relative to beginning of first page.
4355 * Set initial n to be the maximum number of bytes in the
4356 * first page that can be validated.
4358 base += (bp->b_offset & PAGE_MASK);
4359 n = PAGE_SIZE - (base & PAGE_MASK);
4361 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4362 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4366 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4371 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4377 * If the specified buffer is a non-VMIO buffer, clear the entire
4378 * buffer. If the specified buffer is a VMIO buffer, clear and
4379 * validate only the previously invalid portions of the buffer.
4380 * This routine essentially fakes an I/O, so we need to clear
4381 * BIO_ERROR and B_INVAL.
4383 * Note that while we only theoretically need to clear through b_bcount,
4384 * we go ahead and clear through b_bufsize.
4387 vfs_bio_clrbuf(struct buf *bp)
4389 int i, j, mask, sa, ea, slide;
4391 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4395 bp->b_flags &= ~B_INVAL;
4396 bp->b_ioflags &= ~BIO_ERROR;
4397 VM_OBJECT_WLOCK(bp->b_bufobj->bo_object);
4398 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4399 (bp->b_offset & PAGE_MASK) == 0) {
4400 if (bp->b_pages[0] == bogus_page)
4402 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4403 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[0]->object);
4404 if ((bp->b_pages[0]->valid & mask) == mask)
4406 if ((bp->b_pages[0]->valid & mask) == 0) {
4407 pmap_zero_page_area(bp->b_pages[0], 0, bp->b_bufsize);
4408 bp->b_pages[0]->valid |= mask;
4412 sa = bp->b_offset & PAGE_MASK;
4414 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4415 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4416 ea = slide & PAGE_MASK;
4419 if (bp->b_pages[i] == bogus_page)
4422 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4423 VM_OBJECT_ASSERT_WLOCKED(bp->b_pages[i]->object);
4424 if ((bp->b_pages[i]->valid & mask) == mask)
4426 if ((bp->b_pages[i]->valid & mask) == 0)
4427 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4429 for (; sa < ea; sa += DEV_BSIZE, j++) {
4430 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4431 pmap_zero_page_area(bp->b_pages[i],
4436 bp->b_pages[i]->valid |= mask;
4439 VM_OBJECT_WUNLOCK(bp->b_bufobj->bo_object);
4444 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4449 if (buf_mapped(bp)) {
4450 BUF_CHECK_MAPPED(bp);
4451 bzero(bp->b_data + base, size);
4453 BUF_CHECK_UNMAPPED(bp);
4454 n = PAGE_SIZE - (base & PAGE_MASK);
4455 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4459 pmap_zero_page_area(m, base & PAGE_MASK, n);
4468 * Update buffer flags based on I/O request parameters, optionally releasing the
4469 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM,
4470 * where they may be placed on a page queue (VMIO) or freed immediately (direct
4471 * I/O). Otherwise the buffer is released to the cache.
4474 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4477 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4478 ("buf %p non-VMIO noreuse", bp));
4480 if ((ioflag & IO_DIRECT) != 0)
4481 bp->b_flags |= B_DIRECT;
4482 if ((ioflag & IO_EXT) != 0)
4483 bp->b_xflags |= BX_ALTDATA;
4484 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4485 bp->b_flags |= B_RELBUF;
4486 if ((ioflag & IO_NOREUSE) != 0)
4487 bp->b_flags |= B_NOREUSE;
4495 vfs_bio_brelse(struct buf *bp, int ioflag)
4498 b_io_dismiss(bp, ioflag, true);
4502 vfs_bio_set_flags(struct buf *bp, int ioflag)
4505 b_io_dismiss(bp, ioflag, false);
4509 * vm_hold_load_pages and vm_hold_free_pages get pages into
4510 * a buffers address space. The pages are anonymous and are
4511 * not associated with a file object.
4514 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4520 BUF_CHECK_MAPPED(bp);
4522 to = round_page(to);
4523 from = round_page(from);
4524 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4526 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4528 * note: must allocate system pages since blocking here
4529 * could interfere with paging I/O, no matter which
4532 p = vm_page_alloc(NULL, 0, VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
4533 VM_ALLOC_WIRED | VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) |
4535 pmap_qenter(pg, &p, 1);
4536 bp->b_pages[index] = p;
4538 bp->b_npages = index;
4541 /* Return pages associated with this buf to the vm system */
4543 vm_hold_free_pages(struct buf *bp, int newbsize)
4547 int index, newnpages;
4549 BUF_CHECK_MAPPED(bp);
4551 from = round_page((vm_offset_t)bp->b_data + newbsize);
4552 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4553 if (bp->b_npages > newnpages)
4554 pmap_qremove(from, bp->b_npages - newnpages);
4555 for (index = newnpages; index < bp->b_npages; index++) {
4556 p = bp->b_pages[index];
4557 bp->b_pages[index] = NULL;
4561 atomic_subtract_int(&vm_cnt.v_wire_count, bp->b_npages - newnpages);
4562 bp->b_npages = newnpages;
4566 * Map an IO request into kernel virtual address space.
4568 * All requests are (re)mapped into kernel VA space.
4569 * Notice that we use b_bufsize for the size of the buffer
4570 * to be mapped. b_bcount might be modified by the driver.
4572 * Note that even if the caller determines that the address space should
4573 * be valid, a race or a smaller-file mapped into a larger space may
4574 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
4575 * check the return value.
4577 * This function only works with pager buffers.
4580 vmapbuf(struct buf *bp, int mapbuf)
4585 if (bp->b_bufsize < 0)
4587 prot = VM_PROT_READ;
4588 if (bp->b_iocmd == BIO_READ)
4589 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
4590 if ((pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
4591 (vm_offset_t)bp->b_data, bp->b_bufsize, prot, bp->b_pages,
4592 btoc(MAXPHYS))) < 0)
4594 bp->b_npages = pidx;
4595 bp->b_offset = ((vm_offset_t)bp->b_data) & PAGE_MASK;
4596 if (mapbuf || !unmapped_buf_allowed) {
4597 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
4598 bp->b_data = bp->b_kvabase + bp->b_offset;
4600 bp->b_data = unmapped_buf;
4605 * Free the io map PTEs associated with this IO operation.
4606 * We also invalidate the TLB entries and restore the original b_addr.
4608 * This function only works with pager buffers.
4611 vunmapbuf(struct buf *bp)
4615 npages = bp->b_npages;
4617 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4618 vm_page_unhold_pages(bp->b_pages, npages);
4620 bp->b_data = unmapped_buf;
4624 bdone(struct buf *bp)
4628 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4630 bp->b_flags |= B_DONE;
4636 bwait(struct buf *bp, u_char pri, const char *wchan)
4640 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4642 while ((bp->b_flags & B_DONE) == 0)
4643 msleep(bp, mtxp, pri, wchan, 0);
4648 bufsync(struct bufobj *bo, int waitfor)
4651 return (VOP_FSYNC(bo->__bo_vnode, waitfor, curthread));
4655 bufstrategy(struct bufobj *bo, struct buf *bp)
4661 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
4662 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
4663 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
4664 i = VOP_STRATEGY(vp, bp);
4665 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
4669 bufobj_wrefl(struct bufobj *bo)
4672 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4673 ASSERT_BO_WLOCKED(bo);
4678 bufobj_wref(struct bufobj *bo)
4681 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
4688 bufobj_wdrop(struct bufobj *bo)
4691 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
4693 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
4694 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
4695 bo->bo_flag &= ~BO_WWAIT;
4696 wakeup(&bo->bo_numoutput);
4702 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
4706 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
4707 ASSERT_BO_WLOCKED(bo);
4709 while (bo->bo_numoutput) {
4710 bo->bo_flag |= BO_WWAIT;
4711 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
4712 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
4720 bpin(struct buf *bp)
4724 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4731 bunpin(struct buf *bp)
4735 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4737 if (--bp->b_pin_count == 0)
4743 bunpin_wait(struct buf *bp)
4747 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4749 while (bp->b_pin_count > 0)
4750 msleep(bp, mtxp, PRIBIO, "bwunpin", 0);
4755 * Set bio_data or bio_ma for struct bio from the struct buf.
4758 bdata2bio(struct buf *bp, struct bio *bip)
4761 if (!buf_mapped(bp)) {
4762 KASSERT(unmapped_buf_allowed, ("unmapped"));
4763 bip->bio_ma = bp->b_pages;
4764 bip->bio_ma_n = bp->b_npages;
4765 bip->bio_data = unmapped_buf;
4766 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
4767 bip->bio_flags |= BIO_UNMAPPED;
4768 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
4769 PAGE_SIZE == bp->b_npages,
4770 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
4771 (long long)bip->bio_length, bip->bio_ma_n));
4773 bip->bio_data = bp->b_data;
4778 static int buf_pager_relbuf;
4779 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
4780 &buf_pager_relbuf, 0,
4781 "Make buffer pager release buffers after reading");
4784 * The buffer pager. It uses buffer reads to validate pages.
4786 * In contrast to the generic local pager from vm/vnode_pager.c, this
4787 * pager correctly and easily handles volumes where the underlying
4788 * device block size is greater than the machine page size. The
4789 * buffer cache transparently extends the requested page run to be
4790 * aligned at the block boundary, and does the necessary bogus page
4791 * replacements in the addends to avoid obliterating already valid
4794 * The only non-trivial issue is that the exclusive busy state for
4795 * pages, which is assumed by the vm_pager_getpages() interface, is
4796 * incompatible with the VMIO buffer cache's desire to share-busy the
4797 * pages. This function performs a trivial downgrade of the pages'
4798 * state before reading buffers, and a less trivial upgrade from the
4799 * shared-busy to excl-busy state after the read.
4802 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
4803 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
4804 vbg_get_blksize_t get_blksize)
4811 vm_ooffset_t la, lb, poff, poffe;
4813 int bo_bs, br_flags, error, i, pgsin, pgsin_a, pgsin_b;
4816 object = vp->v_object;
4818 la = IDX_TO_OFF(ma[count - 1]->pindex);
4819 if (la >= object->un_pager.vnp.vnp_size)
4820 return (VM_PAGER_BAD);
4823 * Change the meaning of la from where the last requested page starts
4824 * to where it ends, because that's the end of the requested region
4825 * and the start of the potential read-ahead region.
4828 lpart = la > object->un_pager.vnp.vnp_size;
4829 bo_bs = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)));
4832 * Calculate read-ahead, behind and total pages.
4835 lb = IDX_TO_OFF(ma[0]->pindex);
4836 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
4838 if (rbehind != NULL)
4840 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
4841 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
4842 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
4847 PCPU_INC(cnt.v_vnodein);
4848 PCPU_ADD(cnt.v_vnodepgsin, pgsin);
4850 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
4851 != 0) ? GB_UNMAPPED : 0;
4852 VM_OBJECT_WLOCK(object);
4854 for (i = 0; i < count; i++)
4855 vm_page_busy_downgrade(ma[i]);
4856 VM_OBJECT_WUNLOCK(object);
4859 for (i = 0; i < count; i++) {
4863 * Pages are shared busy and the object lock is not
4864 * owned, which together allow for the pages'
4865 * invalidation. The racy test for validity avoids
4866 * useless creation of the buffer for the most typical
4867 * case when invalidation is not used in redo or for
4868 * parallel read. The shared->excl upgrade loop at
4869 * the end of the function catches the race in a
4870 * reliable way (protected by the object lock).
4872 if (m->valid == VM_PAGE_BITS_ALL)
4875 poff = IDX_TO_OFF(m->pindex);
4876 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
4877 for (; poff < poffe; poff += bsize) {
4878 lbn = get_lblkno(vp, poff);
4883 bsize = get_blksize(vp, lbn);
4884 error = bread_gb(vp, lbn, bsize, curthread->td_ucred,
4888 if (LIST_EMPTY(&bp->b_dep)) {
4890 * Invalidation clears m->valid, but
4891 * may leave B_CACHE flag if the
4892 * buffer existed at the invalidation
4893 * time. In this case, recycle the
4894 * buffer to do real read on next
4895 * bread() after redo.
4897 * Otherwise B_RELBUF is not strictly
4898 * necessary, enable to reduce buf
4901 if (buf_pager_relbuf ||
4902 m->valid != VM_PAGE_BITS_ALL)
4903 bp->b_flags |= B_RELBUF;
4905 bp->b_flags &= ~B_NOCACHE;
4911 KASSERT(1 /* racy, enable for debugging */ ||
4912 m->valid == VM_PAGE_BITS_ALL || i == count - 1,
4913 ("buf %d %p invalid", i, m));
4914 if (i == count - 1 && lpart) {
4915 VM_OBJECT_WLOCK(object);
4916 if (m->valid != 0 &&
4917 m->valid != VM_PAGE_BITS_ALL)
4918 vm_page_zero_invalid(m, TRUE);
4919 VM_OBJECT_WUNLOCK(object);
4925 VM_OBJECT_WLOCK(object);
4927 for (i = 0; i < count; i++) {
4928 vm_page_sunbusy(ma[i]);
4929 ma[i] = vm_page_grab(object, ma[i]->pindex, VM_ALLOC_NORMAL);
4932 * Since the pages were only sbusy while neither the
4933 * buffer nor the object lock was held by us, or
4934 * reallocated while vm_page_grab() slept for busy
4935 * relinguish, they could have been invalidated.
4936 * Recheck the valid bits and re-read as needed.
4938 * Note that the last page is made fully valid in the
4939 * read loop, and partial validity for the page at
4940 * index count - 1 could mean that the page was
4941 * invalidated or removed, so we must restart for
4944 if (ma[i]->valid != VM_PAGE_BITS_ALL)
4947 if (redo && error == 0)
4949 VM_OBJECT_WUNLOCK(object);
4950 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
4953 #include "opt_ddb.h"
4955 #include <ddb/ddb.h>
4957 /* DDB command to show buffer data */
4958 DB_SHOW_COMMAND(buffer, db_show_buffer)
4961 struct buf *bp = (struct buf *)addr;
4964 db_printf("usage: show buffer <addr>\n");
4968 db_printf("buf at %p\n", bp);
4969 db_printf("b_flags = 0x%b, b_xflags=0x%b, b_vflags=0x%b\n",
4970 (u_int)bp->b_flags, PRINT_BUF_FLAGS, (u_int)bp->b_xflags,
4971 PRINT_BUF_XFLAGS, (u_int)bp->b_vflags, PRINT_BUF_VFLAGS);
4973 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
4974 "b_bufobj = (%p), b_data = %p, b_blkno = %jd, b_lblkno = %jd, "
4976 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4977 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
4978 (intmax_t)bp->b_lblkno, bp->b_dep.lh_first);
4979 db_printf("b_kvabase = %p, b_kvasize = %d\n",
4980 bp->b_kvabase, bp->b_kvasize);
4983 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
4984 for (i = 0; i < bp->b_npages; i++) {
4987 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4988 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4989 if ((i + 1) < bp->b_npages)
4995 BUF_LOCKPRINTINFO(bp);
4998 DB_SHOW_COMMAND(lockedbufs, lockedbufs)
5003 for (i = 0; i < nbuf; i++) {
5005 if (BUF_ISLOCKED(bp)) {
5006 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5014 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
5020 db_printf("usage: show vnodebufs <addr>\n");
5023 vp = (struct vnode *)addr;
5024 db_printf("Clean buffers:\n");
5025 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
5026 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5029 db_printf("Dirty buffers:\n");
5030 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5031 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5036 DB_COMMAND(countfreebufs, db_coundfreebufs)
5039 int i, used = 0, nfree = 0;
5042 db_printf("usage: countfreebufs\n");
5046 for (i = 0; i < nbuf; i++) {
5048 if (bp->b_qindex == QUEUE_EMPTY)
5054 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5056 db_printf("numfreebuffers is %d\n", numfreebuffers);