2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2004 Poul-Henning Kamp
5 * Copyright (c) 1994,1997 John S. Dyson
6 * Copyright (c) 2013 The FreeBSD Foundation
9 * Portions of this software were developed by Konstantin Belousov
10 * under sponsorship from the FreeBSD Foundation.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * this file contains a new buffer I/O scheme implementing a coherent
36 * VM object and buffer cache scheme. Pains have been taken to make
37 * sure that the performance degradation associated with schemes such
38 * as this is not realized.
40 * Author: John S. Dyson
41 * Significant help during the development and debugging phases
42 * had been provided by David Greenman, also of the FreeBSD core team.
44 * see man buf(9) for more info.
47 #include <sys/param.h>
48 #include <sys/systm.h>
51 #include <sys/bitset.h>
52 #include <sys/boottrace.h>
55 #include <sys/counter.h>
56 #include <sys/devicestat.h>
57 #include <sys/eventhandler.h>
60 #include <sys/limits.h>
62 #include <sys/malloc.h>
63 #include <sys/memdesc.h>
64 #include <sys/mount.h>
65 #include <sys/mutex.h>
66 #include <sys/kernel.h>
67 #include <sys/kthread.h>
68 #include <sys/pctrie.h>
70 #include <sys/racct.h>
71 #include <sys/refcount.h>
72 #include <sys/resourcevar.h>
73 #include <sys/rwlock.h>
74 #include <sys/sched.h>
76 #include <sys/sysctl.h>
77 #include <sys/syscallsubr.h>
79 #include <sys/vmmeter.h>
80 #include <sys/vnode.h>
81 #include <sys/watchdog.h>
82 #include <geom/geom.h>
84 #include <vm/vm_param.h>
85 #include <vm/vm_kern.h>
86 #include <vm/vm_object.h>
87 #include <vm/vm_page.h>
88 #include <vm/vm_pageout.h>
89 #include <vm/vm_pager.h>
90 #include <vm/vm_extern.h>
91 #include <vm/vm_map.h>
92 #include <vm/swap_pager.h>
94 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
96 struct bio_ops bioops; /* I/O operation notification */
98 struct buf_ops buf_ops_bio = {
99 .bop_name = "buf_ops_bio",
100 .bop_write = bufwrite,
101 .bop_strategy = bufstrategy,
103 .bop_bdflush = bufbdflush,
107 struct mtx_padalign bq_lock;
108 TAILQ_HEAD(, buf) bq_queue;
110 uint16_t bq_subqueue;
112 } __aligned(CACHE_LINE_SIZE);
114 #define BQ_LOCKPTR(bq) (&(bq)->bq_lock)
115 #define BQ_LOCK(bq) mtx_lock(BQ_LOCKPTR((bq)))
116 #define BQ_UNLOCK(bq) mtx_unlock(BQ_LOCKPTR((bq)))
117 #define BQ_ASSERT_LOCKED(bq) mtx_assert(BQ_LOCKPTR((bq)), MA_OWNED)
120 struct bufqueue *bd_subq;
121 struct bufqueue bd_dirtyq;
122 struct bufqueue *bd_cleanq;
123 struct mtx_padalign bd_run_lock;
128 long bd_bufspacethresh;
129 int bd_hifreebuffers;
130 int bd_lofreebuffers;
131 int bd_hidirtybuffers;
132 int bd_lodirtybuffers;
133 int bd_dirtybufthresh;
138 int __aligned(CACHE_LINE_SIZE) bd_numdirtybuffers;
139 int __aligned(CACHE_LINE_SIZE) bd_running;
140 long __aligned(CACHE_LINE_SIZE) bd_bufspace;
141 int __aligned(CACHE_LINE_SIZE) bd_freebuffers;
142 } __aligned(CACHE_LINE_SIZE);
144 #define BD_LOCKPTR(bd) (&(bd)->bd_cleanq->bq_lock)
145 #define BD_LOCK(bd) mtx_lock(BD_LOCKPTR((bd)))
146 #define BD_UNLOCK(bd) mtx_unlock(BD_LOCKPTR((bd)))
147 #define BD_ASSERT_LOCKED(bd) mtx_assert(BD_LOCKPTR((bd)), MA_OWNED)
148 #define BD_RUN_LOCKPTR(bd) (&(bd)->bd_run_lock)
149 #define BD_RUN_LOCK(bd) mtx_lock(BD_RUN_LOCKPTR((bd)))
150 #define BD_RUN_UNLOCK(bd) mtx_unlock(BD_RUN_LOCKPTR((bd)))
151 #define BD_DOMAIN(bd) (bd - bdomain)
153 static char *buf; /* buffer header pool */
157 return ((struct buf *)(buf + (sizeof(struct buf) +
158 sizeof(vm_page_t) * atop(maxbcachebuf)) * i));
161 caddr_t __read_mostly unmapped_buf;
163 caddr_t poisoned_buf = (void *)-1;
166 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
167 struct proc *bufdaemonproc;
169 static void vm_hold_free_pages(struct buf *bp, int newbsize);
170 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
172 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
173 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
175 static void vfs_clean_pages_dirty_buf(struct buf *bp);
176 static void vfs_setdirty_range(struct buf *bp);
177 static void vfs_vmio_invalidate(struct buf *bp);
178 static void vfs_vmio_truncate(struct buf *bp, int npages);
179 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
180 static int vfs_bio_clcheck(struct vnode *vp, int size,
181 daddr_t lblkno, daddr_t blkno);
182 static void breada(struct vnode *, daddr_t *, int *, int, struct ucred *, int,
183 void (*)(struct buf *));
184 static int buf_flush(struct vnode *vp, struct bufdomain *, int);
185 static int flushbufqueues(struct vnode *, struct bufdomain *, int, int);
186 static void buf_daemon(void);
187 static __inline void bd_wakeup(void);
188 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
189 static void bufkva_reclaim(vmem_t *, int);
190 static void bufkva_free(struct buf *);
191 static int buf_import(void *, void **, int, int, int);
192 static void buf_release(void *, void **, int);
193 static void maxbcachebuf_adjust(void);
194 static inline struct bufdomain *bufdomain(struct buf *);
195 static void bq_remove(struct bufqueue *bq, struct buf *bp);
196 static void bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock);
197 static int buf_recycle(struct bufdomain *, bool kva);
198 static void bq_init(struct bufqueue *bq, int qindex, int cpu,
199 const char *lockname);
200 static void bd_init(struct bufdomain *bd);
201 static int bd_flushall(struct bufdomain *bd);
202 static int sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS);
203 static int sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS);
205 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
206 int vmiodirenable = TRUE;
207 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
208 "Use the VM system for directory writes");
209 long runningbufspace;
210 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
211 "Amount of presently outstanding async buffer io");
212 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
213 NULL, 0, sysctl_bufspace, "L", "Physical memory used for buffers");
214 static counter_u64_t bufkvaspace;
215 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace,
216 "Kernel virtual memory used for buffers");
217 static long maxbufspace;
218 SYSCTL_PROC(_vfs, OID_AUTO, maxbufspace,
219 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &maxbufspace,
220 __offsetof(struct bufdomain, bd_maxbufspace), sysctl_bufdomain_long, "L",
221 "Maximum allowed value of bufspace (including metadata)");
222 static long bufmallocspace;
223 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
224 "Amount of malloced memory for buffers");
225 static long maxbufmallocspace;
226 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
227 0, "Maximum amount of malloced memory for buffers");
228 static long lobufspace;
229 SYSCTL_PROC(_vfs, OID_AUTO, lobufspace,
230 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &lobufspace,
231 __offsetof(struct bufdomain, bd_lobufspace), sysctl_bufdomain_long, "L",
232 "Minimum amount of buffers we want to have");
234 SYSCTL_PROC(_vfs, OID_AUTO, hibufspace,
235 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &hibufspace,
236 __offsetof(struct bufdomain, bd_hibufspace), sysctl_bufdomain_long, "L",
237 "Maximum allowed value of bufspace (excluding metadata)");
239 SYSCTL_PROC(_vfs, OID_AUTO, bufspacethresh,
240 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &bufspacethresh,
241 __offsetof(struct bufdomain, bd_bufspacethresh), sysctl_bufdomain_long, "L",
242 "Bufspace consumed before waking the daemon to free some");
243 static counter_u64_t buffreekvacnt;
244 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt,
245 "Number of times we have freed the KVA space from some buffer");
246 static counter_u64_t bufdefragcnt;
247 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt,
248 "Number of times we have had to repeat buffer allocation to defragment");
249 static long lorunningspace;
250 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
251 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
252 "Minimum preferred space used for in-progress I/O");
253 static long hirunningspace;
254 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
255 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
256 "Maximum amount of space to use for in-progress I/O");
257 int dirtybufferflushes;
258 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
259 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
261 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
262 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
263 int altbufferflushes;
264 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW | CTLFLAG_STATS,
265 &altbufferflushes, 0, "Number of fsync flushes to limit dirty buffers");
266 static int recursiveflushes;
267 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW | CTLFLAG_STATS,
268 &recursiveflushes, 0, "Number of flushes skipped due to being recursive");
269 static int sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS);
270 SYSCTL_PROC(_vfs, OID_AUTO, numdirtybuffers,
271 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RD, NULL, 0, sysctl_numdirtybuffers, "I",
272 "Number of buffers that are dirty (has unwritten changes) at the moment");
273 static int lodirtybuffers;
274 SYSCTL_PROC(_vfs, OID_AUTO, lodirtybuffers,
275 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lodirtybuffers,
276 __offsetof(struct bufdomain, bd_lodirtybuffers), sysctl_bufdomain_int, "I",
277 "How many buffers we want to have free before bufdaemon can sleep");
278 static int hidirtybuffers;
279 SYSCTL_PROC(_vfs, OID_AUTO, hidirtybuffers,
280 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hidirtybuffers,
281 __offsetof(struct bufdomain, bd_hidirtybuffers), sysctl_bufdomain_int, "I",
282 "When the number of dirty buffers is considered severe");
284 SYSCTL_PROC(_vfs, OID_AUTO, dirtybufthresh,
285 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &dirtybufthresh,
286 __offsetof(struct bufdomain, bd_dirtybufthresh), sysctl_bufdomain_int, "I",
287 "Number of bdwrite to bawrite conversions to clear dirty buffers");
288 static int numfreebuffers;
289 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
290 "Number of free buffers");
291 static int lofreebuffers;
292 SYSCTL_PROC(_vfs, OID_AUTO, lofreebuffers,
293 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lofreebuffers,
294 __offsetof(struct bufdomain, bd_lofreebuffers), sysctl_bufdomain_int, "I",
295 "Target number of free buffers");
296 static int hifreebuffers;
297 SYSCTL_PROC(_vfs, OID_AUTO, hifreebuffers,
298 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hifreebuffers,
299 __offsetof(struct bufdomain, bd_hifreebuffers), sysctl_bufdomain_int, "I",
300 "Threshold for clean buffer recycling");
301 static counter_u64_t getnewbufcalls;
302 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD,
303 &getnewbufcalls, "Number of calls to getnewbuf");
304 static counter_u64_t getnewbufrestarts;
305 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD,
307 "Number of times getnewbuf has had to restart a buffer acquisition");
308 static counter_u64_t mappingrestarts;
309 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RD,
311 "Number of times getblk has had to restart a buffer mapping for "
313 static counter_u64_t numbufallocfails;
314 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW,
315 &numbufallocfails, "Number of times buffer allocations failed");
316 static int flushbufqtarget = 100;
317 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
318 "Amount of work to do in flushbufqueues when helping bufdaemon");
319 static counter_u64_t notbufdflushes;
320 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes,
321 "Number of dirty buffer flushes done by the bufdaemon helpers");
322 static long barrierwrites;
323 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW | CTLFLAG_STATS,
324 &barrierwrites, 0, "Number of barrier writes");
325 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed,
326 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
327 &unmapped_buf_allowed, 0,
328 "Permit the use of the unmapped i/o");
329 int maxbcachebuf = MAXBCACHEBUF;
330 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0,
331 "Maximum size of a buffer cache block");
334 * This lock synchronizes access to bd_request.
336 static struct mtx_padalign __exclusive_cache_line bdlock;
339 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
340 * waitrunningbufspace().
342 static struct mtx_padalign __exclusive_cache_line rbreqlock;
345 * Lock that protects bdirtywait.
347 static struct mtx_padalign __exclusive_cache_line bdirtylock;
350 * bufdaemon shutdown request and sleep channel.
352 static bool bd_shutdown;
355 * Wakeup point for bufdaemon, as well as indicator of whether it is already
356 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
359 static int bd_request;
362 * Request for the buf daemon to write more buffers than is indicated by
363 * lodirtybuf. This may be necessary to push out excess dependencies or
364 * defragment the address space where a simple count of the number of dirty
365 * buffers is insufficient to characterize the demand for flushing them.
367 static int bd_speedupreq;
370 * Synchronization (sleep/wakeup) variable for active buffer space requests.
371 * Set when wait starts, cleared prior to wakeup().
372 * Used in runningbufwakeup() and waitrunningbufspace().
374 static int runningbufreq;
377 * Synchronization for bwillwrite() waiters.
379 static int bdirtywait;
382 * Definitions for the buffer free lists.
384 #define QUEUE_NONE 0 /* on no queue */
385 #define QUEUE_EMPTY 1 /* empty buffer headers */
386 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
387 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
388 #define QUEUE_SENTINEL 4 /* not an queue index, but mark for sentinel */
390 /* Maximum number of buffer domains. */
391 #define BUF_DOMAINS 8
393 struct bufdomainset bdlodirty; /* Domains > lodirty */
394 struct bufdomainset bdhidirty; /* Domains > hidirty */
396 /* Configured number of clean queues. */
397 static int __read_mostly buf_domains;
399 BITSET_DEFINE(bufdomainset, BUF_DOMAINS);
400 struct bufdomain __exclusive_cache_line bdomain[BUF_DOMAINS];
401 struct bufqueue __exclusive_cache_line bqempty;
404 * per-cpu empty buffer cache.
409 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
414 value = *(long *)arg1;
415 error = sysctl_handle_long(oidp, &value, 0, req);
416 if (error != 0 || req->newptr == NULL)
418 mtx_lock(&rbreqlock);
419 if (arg1 == &hirunningspace) {
420 if (value < lorunningspace)
423 hirunningspace = value;
425 KASSERT(arg1 == &lorunningspace,
426 ("%s: unknown arg1", __func__));
427 if (value > hirunningspace)
430 lorunningspace = value;
432 mtx_unlock(&rbreqlock);
437 sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS)
443 value = *(int *)arg1;
444 error = sysctl_handle_int(oidp, &value, 0, req);
445 if (error != 0 || req->newptr == NULL)
447 *(int *)arg1 = value;
448 for (i = 0; i < buf_domains; i++)
449 *(int *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
456 sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS)
462 value = *(long *)arg1;
463 error = sysctl_handle_long(oidp, &value, 0, req);
464 if (error != 0 || req->newptr == NULL)
466 *(long *)arg1 = value;
467 for (i = 0; i < buf_domains; i++)
468 *(long *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
474 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
475 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
477 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
484 for (i = 0; i < buf_domains; i++)
485 lvalue += bdomain[i].bd_bufspace;
486 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
487 return (sysctl_handle_long(oidp, &lvalue, 0, req));
488 if (lvalue > INT_MAX)
489 /* On overflow, still write out a long to trigger ENOMEM. */
490 return (sysctl_handle_long(oidp, &lvalue, 0, req));
492 return (sysctl_handle_int(oidp, &ivalue, 0, req));
496 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
502 for (i = 0; i < buf_domains; i++)
503 lvalue += bdomain[i].bd_bufspace;
504 return (sysctl_handle_long(oidp, &lvalue, 0, req));
509 sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS)
515 for (i = 0; i < buf_domains; i++)
516 value += bdomain[i].bd_numdirtybuffers;
517 return (sysctl_handle_int(oidp, &value, 0, req));
523 * Wakeup any bwillwrite() waiters.
528 mtx_lock(&bdirtylock);
533 mtx_unlock(&bdirtylock);
539 * Clear a domain from the appropriate bitsets when dirtybuffers
543 bd_clear(struct bufdomain *bd)
546 mtx_lock(&bdirtylock);
547 if (bd->bd_numdirtybuffers <= bd->bd_lodirtybuffers)
548 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
549 if (bd->bd_numdirtybuffers <= bd->bd_hidirtybuffers)
550 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
551 mtx_unlock(&bdirtylock);
557 * Set a domain in the appropriate bitsets when dirtybuffers
561 bd_set(struct bufdomain *bd)
564 mtx_lock(&bdirtylock);
565 if (bd->bd_numdirtybuffers > bd->bd_lodirtybuffers)
566 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
567 if (bd->bd_numdirtybuffers > bd->bd_hidirtybuffers)
568 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
569 mtx_unlock(&bdirtylock);
575 * Decrement the numdirtybuffers count by one and wakeup any
576 * threads blocked in bwillwrite().
579 bdirtysub(struct buf *bp)
581 struct bufdomain *bd;
585 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, -1);
586 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
588 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
595 * Increment the numdirtybuffers count by one and wakeup the buf
599 bdirtyadd(struct buf *bp)
601 struct bufdomain *bd;
605 * Only do the wakeup once as we cross the boundary. The
606 * buf daemon will keep running until the condition clears.
609 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, 1);
610 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
612 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
617 * bufspace_daemon_wakeup:
619 * Wakeup the daemons responsible for freeing clean bufs.
622 bufspace_daemon_wakeup(struct bufdomain *bd)
626 * avoid the lock if the daemon is running.
628 if (atomic_fetchadd_int(&bd->bd_running, 1) == 0) {
630 atomic_store_int(&bd->bd_running, 1);
631 wakeup(&bd->bd_running);
639 * Adjust the reported bufspace for a KVA managed buffer, possibly
640 * waking any waiters.
643 bufspace_adjust(struct buf *bp, int bufsize)
645 struct bufdomain *bd;
649 KASSERT((bp->b_flags & B_MALLOC) == 0,
650 ("bufspace_adjust: malloc buf %p", bp));
652 diff = bufsize - bp->b_bufsize;
654 atomic_subtract_long(&bd->bd_bufspace, -diff);
655 } else if (diff > 0) {
656 space = atomic_fetchadd_long(&bd->bd_bufspace, diff);
657 /* Wake up the daemon on the transition. */
658 if (space < bd->bd_bufspacethresh &&
659 space + diff >= bd->bd_bufspacethresh)
660 bufspace_daemon_wakeup(bd);
662 bp->b_bufsize = bufsize;
668 * Reserve bufspace before calling allocbuf(). metadata has a
669 * different space limit than data.
672 bufspace_reserve(struct bufdomain *bd, int size, bool metadata)
678 limit = bd->bd_maxbufspace;
680 limit = bd->bd_hibufspace;
681 space = atomic_fetchadd_long(&bd->bd_bufspace, size);
684 atomic_subtract_long(&bd->bd_bufspace, size);
688 /* Wake up the daemon on the transition. */
689 if (space < bd->bd_bufspacethresh && new >= bd->bd_bufspacethresh)
690 bufspace_daemon_wakeup(bd);
698 * Release reserved bufspace after bufspace_adjust() has consumed it.
701 bufspace_release(struct bufdomain *bd, int size)
704 atomic_subtract_long(&bd->bd_bufspace, size);
710 * Wait for bufspace, acting as the buf daemon if a locked vnode is
711 * supplied. bd_wanted must be set prior to polling for space. The
712 * operation must be re-tried on return.
715 bufspace_wait(struct bufdomain *bd, struct vnode *vp, int gbflags,
716 int slpflag, int slptimeo)
719 int error, fl, norunbuf;
721 if ((gbflags & GB_NOWAIT_BD) != 0)
726 while (bd->bd_wanted) {
727 if (vp != NULL && vp->v_type != VCHR &&
728 (td->td_pflags & TDP_BUFNEED) == 0) {
731 * getblk() is called with a vnode locked, and
732 * some majority of the dirty buffers may as
733 * well belong to the vnode. Flushing the
734 * buffers there would make a progress that
735 * cannot be achieved by the buf_daemon, that
736 * cannot lock the vnode.
738 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
739 (td->td_pflags & TDP_NORUNNINGBUF);
742 * Play bufdaemon. The getnewbuf() function
743 * may be called while the thread owns lock
744 * for another dirty buffer for the same
745 * vnode, which makes it impossible to use
746 * VOP_FSYNC() there, due to the buffer lock
749 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
750 fl = buf_flush(vp, bd, flushbufqtarget);
751 td->td_pflags &= norunbuf;
755 if (bd->bd_wanted == 0)
758 error = msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
759 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
767 bufspace_daemon_shutdown(void *arg, int howto __unused)
769 struct bufdomain *bd = arg;
772 if (KERNEL_PANICKED())
776 bd->bd_shutdown = true;
777 wakeup(&bd->bd_running);
778 error = msleep(&bd->bd_shutdown, BD_RUN_LOCKPTR(bd), 0,
779 "bufspace_shutdown", 60 * hz);
782 printf("bufspacedaemon wait error: %d\n", error);
788 * buffer space management daemon. Tries to maintain some marginal
789 * amount of free buffer space so that requesting processes neither
790 * block nor work to reclaim buffers.
793 bufspace_daemon(void *arg)
795 struct bufdomain *bd = arg;
797 EVENTHANDLER_REGISTER(shutdown_pre_sync, bufspace_daemon_shutdown, bd,
798 SHUTDOWN_PRI_LAST + 100);
801 while (!bd->bd_shutdown) {
805 * Free buffers from the clean queue until we meet our
808 * Theory of operation: The buffer cache is most efficient
809 * when some free buffer headers and space are always
810 * available to getnewbuf(). This daemon attempts to prevent
811 * the excessive blocking and synchronization associated
812 * with shortfall. It goes through three phases according
815 * 1) The daemon wakes up voluntarily once per-second
816 * during idle periods when the counters are below
817 * the wakeup thresholds (bufspacethresh, lofreebuffers).
819 * 2) The daemon wakes up as we cross the thresholds
820 * ahead of any potential blocking. This may bounce
821 * slightly according to the rate of consumption and
824 * 3) The daemon and consumers are starved for working
825 * clean buffers. This is the 'bufspace' sleep below
826 * which will inefficiently trade bufs with bqrelse
827 * until we return to condition 2.
829 while (bd->bd_bufspace > bd->bd_lobufspace ||
830 bd->bd_freebuffers < bd->bd_hifreebuffers) {
831 if (buf_recycle(bd, false) != 0) {
835 * Speedup dirty if we've run out of clean
836 * buffers. This is possible in particular
837 * because softdep may held many bufs locked
838 * pending writes to other bufs which are
839 * marked for delayed write, exhausting
840 * clean space until they are written.
845 msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
846 PRIBIO|PDROP, "bufspace", hz/10);
854 * Re-check our limits and sleep. bd_running must be
855 * cleared prior to checking the limits to avoid missed
856 * wakeups. The waker will adjust one of bufspace or
857 * freebuffers prior to checking bd_running.
862 atomic_store_int(&bd->bd_running, 0);
863 if (bd->bd_bufspace < bd->bd_bufspacethresh &&
864 bd->bd_freebuffers > bd->bd_lofreebuffers) {
865 msleep(&bd->bd_running, BD_RUN_LOCKPTR(bd),
868 /* Avoid spurious wakeups while running. */
869 atomic_store_int(&bd->bd_running, 1);
872 wakeup(&bd->bd_shutdown);
880 * Adjust the reported bufspace for a malloc managed buffer, possibly
881 * waking any waiters.
884 bufmallocadjust(struct buf *bp, int bufsize)
888 KASSERT((bp->b_flags & B_MALLOC) != 0,
889 ("bufmallocadjust: non-malloc buf %p", bp));
890 diff = bufsize - bp->b_bufsize;
892 atomic_subtract_long(&bufmallocspace, -diff);
894 atomic_add_long(&bufmallocspace, diff);
895 bp->b_bufsize = bufsize;
901 * Wake up processes that are waiting on asynchronous writes to fall
902 * below lorunningspace.
908 mtx_lock(&rbreqlock);
911 wakeup(&runningbufreq);
913 mtx_unlock(&rbreqlock);
919 * Decrement the outstanding write count according.
922 runningbufwakeup(struct buf *bp)
926 bspace = bp->b_runningbufspace;
929 space = atomic_fetchadd_long(&runningbufspace, -bspace);
930 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
932 bp->b_runningbufspace = 0;
934 * Only acquire the lock and wakeup on the transition from exceeding
935 * the threshold to falling below it.
937 if (space < lorunningspace)
939 if (space - bspace > lorunningspace)
945 * waitrunningbufspace()
947 * runningbufspace is a measure of the amount of I/O currently
948 * running. This routine is used in async-write situations to
949 * prevent creating huge backups of pending writes to a device.
950 * Only asynchronous writes are governed by this function.
952 * This does NOT turn an async write into a sync write. It waits
953 * for earlier writes to complete and generally returns before the
954 * caller's write has reached the device.
957 waitrunningbufspace(void)
960 mtx_lock(&rbreqlock);
961 while (runningbufspace > hirunningspace) {
963 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
965 mtx_unlock(&rbreqlock);
969 * vfs_buf_test_cache:
971 * Called when a buffer is extended. This function clears the B_CACHE
972 * bit if the newly extended portion of the buffer does not contain
976 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
977 vm_offset_t size, vm_page_t m)
981 * This function and its results are protected by higher level
982 * synchronization requiring vnode and buf locks to page in and
985 if (bp->b_flags & B_CACHE) {
986 int base = (foff + off) & PAGE_MASK;
987 if (vm_page_is_valid(m, base, size) == 0)
988 bp->b_flags &= ~B_CACHE;
992 /* Wake up the buffer daemon if necessary */
998 if (bd_request == 0) {
1000 wakeup(&bd_request);
1002 mtx_unlock(&bdlock);
1006 * Adjust the maxbcachbuf tunable.
1009 maxbcachebuf_adjust(void)
1014 * maxbcachebuf must be a power of 2 >= MAXBSIZE.
1017 while (i * 2 <= maxbcachebuf)
1020 if (maxbcachebuf < MAXBSIZE)
1021 maxbcachebuf = MAXBSIZE;
1022 if (maxbcachebuf > maxphys)
1023 maxbcachebuf = maxphys;
1024 if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF)
1025 printf("maxbcachebuf=%d\n", maxbcachebuf);
1029 * bd_speedup - speedup the buffer cache flushing code
1038 if (bd_speedupreq == 0 || bd_request == 0)
1043 wakeup(&bd_request);
1044 mtx_unlock(&bdlock);
1048 #define TRANSIENT_DENOM 5
1050 #define TRANSIENT_DENOM 10
1054 * Calculating buffer cache scaling values and reserve space for buffer
1055 * headers. This is called during low level kernel initialization and
1056 * may be called more then once. We CANNOT write to the memory area
1057 * being reserved at this time.
1060 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
1063 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
1066 * With KASAN or KMSAN enabled, the kernel map is shadowed. Account for
1067 * this when sizing maps based on the amount of physical memory
1071 physmem_est = (physmem_est * KASAN_SHADOW_SCALE) /
1072 (KASAN_SHADOW_SCALE + 1);
1073 #elif defined(KMSAN)
1077 * KMSAN cannot reliably determine whether buffer data is initialized
1078 * unless it is updated through a KVA mapping.
1080 unmapped_buf_allowed = 0;
1084 * physmem_est is in pages. Convert it to kilobytes (assumes
1085 * PAGE_SIZE is >= 1K)
1087 physmem_est = physmem_est * (PAGE_SIZE / 1024);
1089 maxbcachebuf_adjust();
1091 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
1092 * For the first 64MB of ram nominally allocate sufficient buffers to
1093 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
1094 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
1095 * the buffer cache we limit the eventual kva reservation to
1098 * factor represents the 1/4 x ram conversion.
1101 int factor = 4 * BKVASIZE / 1024;
1104 if (physmem_est > 4096)
1105 nbuf += min((physmem_est - 4096) / factor,
1107 if (physmem_est > 65536)
1108 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
1109 32 * 1024 * 1024 / (factor * 5));
1111 if (maxbcache && nbuf > maxbcache / BKVASIZE)
1112 nbuf = maxbcache / BKVASIZE;
1117 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
1118 maxbuf = (LONG_MAX / 3) / BKVASIZE;
1119 if (nbuf > maxbuf) {
1121 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
1127 * Ideal allocation size for the transient bio submap is 10%
1128 * of the maximal space buffer map. This roughly corresponds
1129 * to the amount of the buffer mapped for typical UFS load.
1131 * Clip the buffer map to reserve space for the transient
1132 * BIOs, if its extent is bigger than 90% (80% on i386) of the
1133 * maximum buffer map extent on the platform.
1135 * The fall-back to the maxbuf in case of maxbcache unset,
1136 * allows to not trim the buffer KVA for the architectures
1137 * with ample KVA space.
1139 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
1140 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
1141 buf_sz = (long)nbuf * BKVASIZE;
1142 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
1143 (TRANSIENT_DENOM - 1)) {
1145 * There is more KVA than memory. Do not
1146 * adjust buffer map size, and assign the rest
1147 * of maxbuf to transient map.
1149 biotmap_sz = maxbuf_sz - buf_sz;
1152 * Buffer map spans all KVA we could afford on
1153 * this platform. Give 10% (20% on i386) of
1154 * the buffer map to the transient bio map.
1156 biotmap_sz = buf_sz / TRANSIENT_DENOM;
1157 buf_sz -= biotmap_sz;
1159 if (biotmap_sz / INT_MAX > maxphys)
1160 bio_transient_maxcnt = INT_MAX;
1162 bio_transient_maxcnt = biotmap_sz / maxphys;
1164 * Artificially limit to 1024 simultaneous in-flight I/Os
1165 * using the transient mapping.
1167 if (bio_transient_maxcnt > 1024)
1168 bio_transient_maxcnt = 1024;
1170 nbuf = buf_sz / BKVASIZE;
1175 * Pager buffers are allocated for short periods, so scale the
1176 * number of reserved buffers based on the number of CPUs rather
1177 * than amount of memory.
1179 nswbuf = min(nbuf / 4, 32 * mp_ncpus);
1180 if (nswbuf < NSWBUF_MIN)
1181 nswbuf = NSWBUF_MIN;
1185 * Reserve space for the buffer cache buffers
1188 v = (caddr_t)buf + (sizeof(struct buf) + sizeof(vm_page_t) *
1189 atop(maxbcachebuf)) * nbuf;
1195 * Single global constant for BUF_WMESG, to avoid getting multiple
1198 static const char buf_wmesg[] = "bufwait";
1200 /* Initialize the buffer subsystem. Called before use of any buffers. */
1208 KASSERT(maxbcachebuf >= MAXBSIZE,
1209 ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf,
1211 bq_init(&bqempty, QUEUE_EMPTY, -1, "bufq empty lock");
1212 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1213 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1214 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1216 unmapped_buf = (caddr_t)kva_alloc(maxphys);
1218 poisoned_buf = unmapped_buf;
1221 /* finally, initialize each buffer header and stick on empty q */
1222 for (i = 0; i < nbuf; i++) {
1224 bzero(bp, sizeof(*bp) + sizeof(vm_page_t) * atop(maxbcachebuf));
1225 bp->b_flags = B_INVAL;
1226 bp->b_rcred = NOCRED;
1227 bp->b_wcred = NOCRED;
1228 bp->b_qindex = QUEUE_NONE;
1230 bp->b_subqueue = mp_maxid + 1;
1232 bp->b_data = bp->b_kvabase = unmapped_buf;
1233 LIST_INIT(&bp->b_dep);
1234 BUF_LOCKINIT(bp, buf_wmesg);
1235 bq_insert(&bqempty, bp, false);
1239 * maxbufspace is the absolute maximum amount of buffer space we are
1240 * allowed to reserve in KVM and in real terms. The absolute maximum
1241 * is nominally used by metadata. hibufspace is the nominal maximum
1242 * used by most other requests. The differential is required to
1243 * ensure that metadata deadlocks don't occur.
1245 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1246 * this may result in KVM fragmentation which is not handled optimally
1247 * by the system. XXX This is less true with vmem. We could use
1250 maxbufspace = (long)nbuf * BKVASIZE;
1251 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10);
1252 lobufspace = (hibufspace / 20) * 19; /* 95% */
1253 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1256 * Note: The 16 MiB upper limit for hirunningspace was chosen
1257 * arbitrarily and may need further tuning. It corresponds to
1258 * 128 outstanding write IO requests (if IO size is 128 KiB),
1259 * which fits with many RAID controllers' tagged queuing limits.
1260 * The lower 1 MiB limit is the historical upper limit for
1263 hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf),
1264 16 * 1024 * 1024), 1024 * 1024);
1265 lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf);
1268 * Limit the amount of malloc memory since it is wired permanently into
1269 * the kernel space. Even though this is accounted for in the buffer
1270 * allocation, we don't want the malloced region to grow uncontrolled.
1271 * The malloc scheme improves memory utilization significantly on
1272 * average (small) directories.
1274 maxbufmallocspace = hibufspace / 20;
1277 * Reduce the chance of a deadlock occurring by limiting the number
1278 * of delayed-write dirty buffers we allow to stack up.
1280 hidirtybuffers = nbuf / 4 + 20;
1281 dirtybufthresh = hidirtybuffers * 9 / 10;
1283 * To support extreme low-memory systems, make sure hidirtybuffers
1284 * cannot eat up all available buffer space. This occurs when our
1285 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1286 * buffer space assuming BKVASIZE'd buffers.
1288 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1289 hidirtybuffers >>= 1;
1291 lodirtybuffers = hidirtybuffers / 2;
1294 * lofreebuffers should be sufficient to avoid stalling waiting on
1295 * buf headers under heavy utilization. The bufs in per-cpu caches
1296 * are counted as free but will be unavailable to threads executing
1299 * hifreebuffers is the free target for the bufspace daemon. This
1300 * should be set appropriately to limit work per-iteration.
1302 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1303 hifreebuffers = (3 * lofreebuffers) / 2;
1304 numfreebuffers = nbuf;
1306 /* Setup the kva and free list allocators. */
1307 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1308 buf_zone = uma_zcache_create("buf free cache",
1309 sizeof(struct buf) + sizeof(vm_page_t) * atop(maxbcachebuf),
1310 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1313 * Size the clean queue according to the amount of buffer space.
1314 * One queue per-256mb up to the max. More queues gives better
1315 * concurrency but less accurate LRU.
1317 buf_domains = MIN(howmany(maxbufspace, 256*1024*1024), BUF_DOMAINS);
1318 for (i = 0 ; i < buf_domains; i++) {
1319 struct bufdomain *bd;
1323 bd->bd_freebuffers = nbuf / buf_domains;
1324 bd->bd_hifreebuffers = hifreebuffers / buf_domains;
1325 bd->bd_lofreebuffers = lofreebuffers / buf_domains;
1326 bd->bd_bufspace = 0;
1327 bd->bd_maxbufspace = maxbufspace / buf_domains;
1328 bd->bd_hibufspace = hibufspace / buf_domains;
1329 bd->bd_lobufspace = lobufspace / buf_domains;
1330 bd->bd_bufspacethresh = bufspacethresh / buf_domains;
1331 bd->bd_numdirtybuffers = 0;
1332 bd->bd_hidirtybuffers = hidirtybuffers / buf_domains;
1333 bd->bd_lodirtybuffers = lodirtybuffers / buf_domains;
1334 bd->bd_dirtybufthresh = dirtybufthresh / buf_domains;
1335 /* Don't allow more than 2% of bufs in the per-cpu caches. */
1336 bd->bd_lim = nbuf / buf_domains / 50 / mp_ncpus;
1338 getnewbufcalls = counter_u64_alloc(M_WAITOK);
1339 getnewbufrestarts = counter_u64_alloc(M_WAITOK);
1340 mappingrestarts = counter_u64_alloc(M_WAITOK);
1341 numbufallocfails = counter_u64_alloc(M_WAITOK);
1342 notbufdflushes = counter_u64_alloc(M_WAITOK);
1343 buffreekvacnt = counter_u64_alloc(M_WAITOK);
1344 bufdefragcnt = counter_u64_alloc(M_WAITOK);
1345 bufkvaspace = counter_u64_alloc(M_WAITOK);
1351 vfs_buf_check_mapped(struct buf *bp)
1354 KASSERT(bp->b_kvabase != unmapped_buf,
1355 ("mapped buf: b_kvabase was not updated %p", bp));
1356 KASSERT(bp->b_data != unmapped_buf,
1357 ("mapped buf: b_data was not updated %p", bp));
1358 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1359 maxphys, ("b_data + b_offset unmapped %p", bp));
1363 vfs_buf_check_unmapped(struct buf *bp)
1366 KASSERT(bp->b_data == unmapped_buf,
1367 ("unmapped buf: corrupted b_data %p", bp));
1370 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1371 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1373 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1374 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1378 isbufbusy(struct buf *bp)
1380 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1381 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1387 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1390 bufshutdown(int show_busybufs)
1392 static int first_buf_printf = 1;
1394 int i, iter, nbusy, pbusy;
1400 * Sync filesystems for shutdown
1402 wdog_kern_pat(WD_LASTVAL);
1403 kern_sync(curthread);
1406 * With soft updates, some buffers that are
1407 * written will be remarked as dirty until other
1408 * buffers are written.
1410 for (iter = pbusy = 0; iter < 20; iter++) {
1412 for (i = nbuf - 1; i >= 0; i--) {
1418 if (first_buf_printf)
1419 printf("All buffers synced.");
1422 if (first_buf_printf) {
1423 printf("Syncing disks, buffers remaining... ");
1424 first_buf_printf = 0;
1426 printf("%d ", nbusy);
1431 wdog_kern_pat(WD_LASTVAL);
1432 kern_sync(curthread);
1436 * Spin for a while to allow interrupt threads to run.
1438 DELAY(50000 * iter);
1441 * Context switch several times to allow interrupt
1444 for (subiter = 0; subiter < 50 * iter; subiter++) {
1445 sched_relinquish(curthread);
1452 * Count only busy local buffers to prevent forcing
1453 * a fsck if we're just a client of a wedged NFS server
1456 for (i = nbuf - 1; i >= 0; i--) {
1458 if (isbufbusy(bp)) {
1460 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1461 if (bp->b_dev == NULL) {
1462 TAILQ_REMOVE(&mountlist,
1463 bp->b_vp->v_mount, mnt_list);
1468 if (show_busybufs > 0) {
1470 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1471 nbusy, bp, bp->b_vp, bp->b_flags,
1472 (intmax_t)bp->b_blkno,
1473 (intmax_t)bp->b_lblkno);
1474 BUF_LOCKPRINTINFO(bp);
1475 if (show_busybufs > 1)
1483 * Failed to sync all blocks. Indicate this and don't
1484 * unmount filesystems (thus forcing an fsck on reboot).
1486 BOOTTRACE("shutdown failed to sync buffers");
1487 printf("Giving up on %d buffers\n", nbusy);
1488 DELAY(5000000); /* 5 seconds */
1491 BOOTTRACE("shutdown sync complete");
1492 if (!first_buf_printf)
1493 printf("Final sync complete\n");
1496 * Unmount filesystems and perform swapoff, to quiesce
1497 * the system as much as possible. In particular, no
1498 * I/O should be initiated from top levels since it
1499 * might be abruptly terminated by reset, or otherwise
1500 * erronously handled because other parts of the
1501 * system are disabled.
1503 * Swapoff before unmount, because file-backed swap is
1504 * non-operational after unmount of the underlying
1507 if (!KERNEL_PANICKED()) {
1511 BOOTTRACE("shutdown unmounted all filesystems");
1513 DELAY(100000); /* wait for console output to finish */
1517 bpmap_qenter(struct buf *bp)
1520 BUF_CHECK_MAPPED(bp);
1523 * bp->b_data is relative to bp->b_offset, but
1524 * bp->b_offset may be offset into the first page.
1526 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1527 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1528 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1529 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1532 static inline struct bufdomain *
1533 bufdomain(struct buf *bp)
1536 return (&bdomain[bp->b_domain]);
1539 static struct bufqueue *
1540 bufqueue(struct buf *bp)
1543 switch (bp->b_qindex) {
1546 case QUEUE_SENTINEL:
1551 return (&bufdomain(bp)->bd_dirtyq);
1553 return (&bufdomain(bp)->bd_subq[bp->b_subqueue]);
1557 panic("bufqueue(%p): Unhandled type %d\n", bp, bp->b_qindex);
1561 * Return the locked bufqueue that bp is a member of.
1563 static struct bufqueue *
1564 bufqueue_acquire(struct buf *bp)
1566 struct bufqueue *bq, *nbq;
1569 * bp can be pushed from a per-cpu queue to the
1570 * cleanq while we're waiting on the lock. Retry
1571 * if the queues don't match.
1589 * Insert the buffer into the appropriate free list. Requires a
1590 * locked buffer on entry and buffer is unlocked before return.
1593 binsfree(struct buf *bp, int qindex)
1595 struct bufdomain *bd;
1596 struct bufqueue *bq;
1598 KASSERT(qindex == QUEUE_CLEAN || qindex == QUEUE_DIRTY,
1599 ("binsfree: Invalid qindex %d", qindex));
1600 BUF_ASSERT_XLOCKED(bp);
1603 * Handle delayed bremfree() processing.
1605 if (bp->b_flags & B_REMFREE) {
1606 if (bp->b_qindex == qindex) {
1607 bp->b_flags |= B_REUSE;
1608 bp->b_flags &= ~B_REMFREE;
1612 bq = bufqueue_acquire(bp);
1617 if (qindex == QUEUE_CLEAN) {
1618 if (bd->bd_lim != 0)
1619 bq = &bd->bd_subq[PCPU_GET(cpuid)];
1623 bq = &bd->bd_dirtyq;
1624 bq_insert(bq, bp, true);
1630 * Free a buffer to the buf zone once it no longer has valid contents.
1633 buf_free(struct buf *bp)
1636 if (bp->b_flags & B_REMFREE)
1638 if (bp->b_vflags & BV_BKGRDINPROG)
1639 panic("losing buffer 1");
1640 if (bp->b_rcred != NOCRED) {
1641 crfree(bp->b_rcred);
1642 bp->b_rcred = NOCRED;
1644 if (bp->b_wcred != NOCRED) {
1645 crfree(bp->b_wcred);
1646 bp->b_wcred = NOCRED;
1648 if (!LIST_EMPTY(&bp->b_dep))
1651 atomic_add_int(&bufdomain(bp)->bd_freebuffers, 1);
1652 MPASS((bp->b_flags & B_MAXPHYS) == 0);
1654 uma_zfree(buf_zone, bp);
1660 * Import bufs into the uma cache from the buf list. The system still
1661 * expects a static array of bufs and much of the synchronization
1662 * around bufs assumes type stable storage. As a result, UMA is used
1663 * only as a per-cpu cache of bufs still maintained on a global list.
1666 buf_import(void *arg, void **store, int cnt, int domain, int flags)
1672 for (i = 0; i < cnt; i++) {
1673 bp = TAILQ_FIRST(&bqempty.bq_queue);
1676 bq_remove(&bqempty, bp);
1679 BQ_UNLOCK(&bqempty);
1687 * Release bufs from the uma cache back to the buffer queues.
1690 buf_release(void *arg, void **store, int cnt)
1692 struct bufqueue *bq;
1698 for (i = 0; i < cnt; i++) {
1700 /* Inline bq_insert() to batch locking. */
1701 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1702 bp->b_flags &= ~(B_AGE | B_REUSE);
1704 bp->b_qindex = bq->bq_index;
1712 * Allocate an empty buffer header.
1715 buf_alloc(struct bufdomain *bd)
1718 int freebufs, error;
1721 * We can only run out of bufs in the buf zone if the average buf
1722 * is less than BKVASIZE. In this case the actual wait/block will
1723 * come from buf_reycle() failing to flush one of these small bufs.
1726 freebufs = atomic_fetchadd_int(&bd->bd_freebuffers, -1);
1728 bp = uma_zalloc(buf_zone, M_NOWAIT);
1730 atomic_add_int(&bd->bd_freebuffers, 1);
1731 bufspace_daemon_wakeup(bd);
1732 counter_u64_add(numbufallocfails, 1);
1736 * Wake-up the bufspace daemon on transition below threshold.
1738 if (freebufs == bd->bd_lofreebuffers)
1739 bufspace_daemon_wakeup(bd);
1741 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
1742 KASSERT(error == 0, ("%s: BUF_LOCK on free buf %p: %d.", __func__, bp,
1746 KASSERT(bp->b_vp == NULL,
1747 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1748 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1749 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1750 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1751 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1752 KASSERT(bp->b_npages == 0,
1753 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1754 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1755 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1756 MPASS((bp->b_flags & B_MAXPHYS) == 0);
1758 bp->b_domain = BD_DOMAIN(bd);
1764 bp->b_blkno = bp->b_lblkno = 0;
1765 bp->b_offset = NOOFFSET;
1771 bp->b_dirtyoff = bp->b_dirtyend = 0;
1772 bp->b_bufobj = NULL;
1773 bp->b_data = bp->b_kvabase = unmapped_buf;
1774 bp->b_fsprivate1 = NULL;
1775 bp->b_fsprivate2 = NULL;
1776 bp->b_fsprivate3 = NULL;
1777 LIST_INIT(&bp->b_dep);
1785 * Free a buffer from the given bufqueue. kva controls whether the
1786 * freed buf must own some kva resources. This is used for
1790 buf_recycle(struct bufdomain *bd, bool kva)
1792 struct bufqueue *bq;
1793 struct buf *bp, *nbp;
1796 counter_u64_add(bufdefragcnt, 1);
1800 KASSERT(BQ_LOCKPTR(bq) == BD_LOCKPTR(bd),
1801 ("buf_recycle: Locks don't match"));
1802 nbp = TAILQ_FIRST(&bq->bq_queue);
1805 * Run scan, possibly freeing data and/or kva mappings on the fly
1808 while ((bp = nbp) != NULL) {
1810 * Calculate next bp (we can only use it if we do not
1811 * release the bqlock).
1813 nbp = TAILQ_NEXT(bp, b_freelist);
1816 * If we are defragging then we need a buffer with
1817 * some kva to reclaim.
1819 if (kva && bp->b_kvasize == 0)
1822 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1826 * Implement a second chance algorithm for frequently
1829 if ((bp->b_flags & B_REUSE) != 0) {
1830 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1831 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1832 bp->b_flags &= ~B_REUSE;
1838 * Skip buffers with background writes in progress.
1840 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1845 KASSERT(bp->b_qindex == QUEUE_CLEAN,
1846 ("buf_recycle: inconsistent queue %d bp %p",
1848 KASSERT(bp->b_domain == BD_DOMAIN(bd),
1849 ("getnewbuf: queue domain %d doesn't match request %d",
1850 bp->b_domain, (int)BD_DOMAIN(bd)));
1852 * NOTE: nbp is now entirely invalid. We can only restart
1853 * the scan from this point on.
1859 * Requeue the background write buffer with error and
1862 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1865 nbp = TAILQ_FIRST(&bq->bq_queue);
1868 bp->b_flags |= B_INVAL;
1881 * Mark the buffer for removal from the appropriate free list.
1885 bremfree(struct buf *bp)
1888 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1889 KASSERT((bp->b_flags & B_REMFREE) == 0,
1890 ("bremfree: buffer %p already marked for delayed removal.", bp));
1891 KASSERT(bp->b_qindex != QUEUE_NONE,
1892 ("bremfree: buffer %p not on a queue.", bp));
1893 BUF_ASSERT_XLOCKED(bp);
1895 bp->b_flags |= B_REMFREE;
1901 * Force an immediate removal from a free list. Used only in nfs when
1902 * it abuses the b_freelist pointer.
1905 bremfreef(struct buf *bp)
1907 struct bufqueue *bq;
1909 bq = bufqueue_acquire(bp);
1915 bq_init(struct bufqueue *bq, int qindex, int subqueue, const char *lockname)
1918 mtx_init(&bq->bq_lock, lockname, NULL, MTX_DEF);
1919 TAILQ_INIT(&bq->bq_queue);
1921 bq->bq_index = qindex;
1922 bq->bq_subqueue = subqueue;
1926 bd_init(struct bufdomain *bd)
1930 /* Per-CPU clean buf queues, plus one global queue. */
1931 bd->bd_subq = mallocarray(mp_maxid + 2, sizeof(struct bufqueue),
1932 M_BIOBUF, M_WAITOK | M_ZERO);
1933 bd->bd_cleanq = &bd->bd_subq[mp_maxid + 1];
1934 bq_init(bd->bd_cleanq, QUEUE_CLEAN, mp_maxid + 1, "bufq clean lock");
1935 bq_init(&bd->bd_dirtyq, QUEUE_DIRTY, -1, "bufq dirty lock");
1936 for (i = 0; i <= mp_maxid; i++)
1937 bq_init(&bd->bd_subq[i], QUEUE_CLEAN, i,
1938 "bufq clean subqueue lock");
1939 mtx_init(&bd->bd_run_lock, "bufspace daemon run lock", NULL, MTX_DEF);
1945 * Removes a buffer from the free list, must be called with the
1946 * correct qlock held.
1949 bq_remove(struct bufqueue *bq, struct buf *bp)
1952 CTR3(KTR_BUF, "bq_remove(%p) vp %p flags %X",
1953 bp, bp->b_vp, bp->b_flags);
1954 KASSERT(bp->b_qindex != QUEUE_NONE,
1955 ("bq_remove: buffer %p not on a queue.", bp));
1956 KASSERT(bufqueue(bp) == bq,
1957 ("bq_remove: Remove buffer %p from wrong queue.", bp));
1959 BQ_ASSERT_LOCKED(bq);
1960 if (bp->b_qindex != QUEUE_EMPTY) {
1961 BUF_ASSERT_XLOCKED(bp);
1963 KASSERT(bq->bq_len >= 1,
1964 ("queue %d underflow", bp->b_qindex));
1965 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1967 bp->b_qindex = QUEUE_NONE;
1968 bp->b_flags &= ~(B_REMFREE | B_REUSE);
1972 bd_flush(struct bufdomain *bd, struct bufqueue *bq)
1976 BQ_ASSERT_LOCKED(bq);
1977 if (bq != bd->bd_cleanq) {
1979 while ((bp = TAILQ_FIRST(&bq->bq_queue)) != NULL) {
1980 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1981 TAILQ_INSERT_TAIL(&bd->bd_cleanq->bq_queue, bp,
1983 bp->b_subqueue = bd->bd_cleanq->bq_subqueue;
1985 bd->bd_cleanq->bq_len += bq->bq_len;
1988 if (bd->bd_wanted) {
1990 wakeup(&bd->bd_wanted);
1992 if (bq != bd->bd_cleanq)
1997 bd_flushall(struct bufdomain *bd)
1999 struct bufqueue *bq;
2003 if (bd->bd_lim == 0)
2006 for (i = 0; i <= mp_maxid; i++) {
2007 bq = &bd->bd_subq[i];
2008 if (bq->bq_len == 0)
2020 bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock)
2022 struct bufdomain *bd;
2024 if (bp->b_qindex != QUEUE_NONE)
2025 panic("bq_insert: free buffer %p onto another queue?", bp);
2028 if (bp->b_flags & B_AGE) {
2029 /* Place this buf directly on the real queue. */
2030 if (bq->bq_index == QUEUE_CLEAN)
2033 TAILQ_INSERT_HEAD(&bq->bq_queue, bp, b_freelist);
2036 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
2038 bp->b_flags &= ~(B_AGE | B_REUSE);
2040 bp->b_qindex = bq->bq_index;
2041 bp->b_subqueue = bq->bq_subqueue;
2044 * Unlock before we notify so that we don't wakeup a waiter that
2045 * fails a trylock on the buf and sleeps again.
2050 if (bp->b_qindex == QUEUE_CLEAN) {
2052 * Flush the per-cpu queue and notify any waiters.
2054 if (bd->bd_wanted || (bq != bd->bd_cleanq &&
2055 bq->bq_len >= bd->bd_lim))
2064 * Free the kva allocation for a buffer.
2068 bufkva_free(struct buf *bp)
2072 if (bp->b_kvasize == 0) {
2073 KASSERT(bp->b_kvabase == unmapped_buf &&
2074 bp->b_data == unmapped_buf,
2075 ("Leaked KVA space on %p", bp));
2076 } else if (buf_mapped(bp))
2077 BUF_CHECK_MAPPED(bp);
2079 BUF_CHECK_UNMAPPED(bp);
2081 if (bp->b_kvasize == 0)
2084 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
2085 counter_u64_add(bufkvaspace, -bp->b_kvasize);
2086 counter_u64_add(buffreekvacnt, 1);
2087 bp->b_data = bp->b_kvabase = unmapped_buf;
2094 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
2097 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
2102 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
2103 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
2104 MPASS((bp->b_flags & B_MAXPHYS) == 0);
2105 KASSERT(maxsize <= maxbcachebuf,
2106 ("bufkva_alloc kva too large %d %u", maxsize, maxbcachebuf));
2111 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
2114 * Buffer map is too fragmented. Request the caller
2115 * to defragment the map.
2119 bp->b_kvabase = (caddr_t)addr;
2120 bp->b_kvasize = maxsize;
2121 counter_u64_add(bufkvaspace, bp->b_kvasize);
2122 if ((gbflags & GB_UNMAPPED) != 0) {
2123 bp->b_data = unmapped_buf;
2124 BUF_CHECK_UNMAPPED(bp);
2126 bp->b_data = bp->b_kvabase;
2127 BUF_CHECK_MAPPED(bp);
2135 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
2136 * callback that fires to avoid returning failure.
2139 bufkva_reclaim(vmem_t *vmem, int flags)
2146 for (i = 0; i < 5; i++) {
2147 for (q = 0; q < buf_domains; q++)
2148 if (buf_recycle(&bdomain[q], true) != 0)
2157 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
2158 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
2159 * the buffer is valid and we do not have to do anything.
2162 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize, int cnt,
2163 struct ucred * cred, int flags, void (*ckhashfunc)(struct buf *))
2171 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
2172 if (inmem(vp, *rablkno))
2174 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
2175 if ((rabp->b_flags & B_CACHE) != 0) {
2182 racct_add_buf(curproc, rabp, 0);
2183 PROC_UNLOCK(curproc);
2186 td->td_ru.ru_inblock++;
2187 rabp->b_flags |= B_ASYNC;
2188 rabp->b_flags &= ~B_INVAL;
2189 if ((flags & GB_CKHASH) != 0) {
2190 rabp->b_flags |= B_CKHASH;
2191 rabp->b_ckhashcalc = ckhashfunc;
2193 rabp->b_ioflags &= ~BIO_ERROR;
2194 rabp->b_iocmd = BIO_READ;
2195 if (rabp->b_rcred == NOCRED && cred != NOCRED)
2196 rabp->b_rcred = crhold(cred);
2197 vfs_busy_pages(rabp, 0);
2199 rabp->b_iooffset = dbtob(rabp->b_blkno);
2205 * Entry point for bread() and breadn() via #defines in sys/buf.h.
2207 * Get a buffer with the specified data. Look in the cache first. We
2208 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
2209 * is set, the buffer is valid and we do not have to do anything, see
2210 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
2212 * Always return a NULL buffer pointer (in bpp) when returning an error.
2214 * The blkno parameter is the logical block being requested. Normally
2215 * the mapping of logical block number to disk block address is done
2216 * by calling VOP_BMAP(). However, if the mapping is already known, the
2217 * disk block address can be passed using the dblkno parameter. If the
2218 * disk block address is not known, then the same value should be passed
2219 * for blkno and dblkno.
2222 breadn_flags(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size,
2223 daddr_t *rablkno, int *rabsize, int cnt, struct ucred *cred, int flags,
2224 void (*ckhashfunc)(struct buf *), struct buf **bpp)
2228 int error, readwait, rv;
2230 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
2233 * Can only return NULL if GB_LOCK_NOWAIT or GB_SPARSE flags
2236 error = getblkx(vp, blkno, dblkno, size, 0, 0, flags, &bp);
2241 KASSERT(blkno == bp->b_lblkno,
2242 ("getblkx returned buffer for blkno %jd instead of blkno %jd",
2243 (intmax_t)bp->b_lblkno, (intmax_t)blkno));
2244 flags &= ~GB_NOSPARSE;
2248 * If not found in cache, do some I/O
2251 if ((bp->b_flags & B_CACHE) == 0) {
2254 PROC_LOCK(td->td_proc);
2255 racct_add_buf(td->td_proc, bp, 0);
2256 PROC_UNLOCK(td->td_proc);
2259 td->td_ru.ru_inblock++;
2260 bp->b_iocmd = BIO_READ;
2261 bp->b_flags &= ~B_INVAL;
2262 if ((flags & GB_CKHASH) != 0) {
2263 bp->b_flags |= B_CKHASH;
2264 bp->b_ckhashcalc = ckhashfunc;
2266 if ((flags & GB_CVTENXIO) != 0)
2267 bp->b_xflags |= BX_CVTENXIO;
2268 bp->b_ioflags &= ~BIO_ERROR;
2269 if (bp->b_rcred == NOCRED && cred != NOCRED)
2270 bp->b_rcred = crhold(cred);
2271 vfs_busy_pages(bp, 0);
2272 bp->b_iooffset = dbtob(bp->b_blkno);
2278 * Attempt to initiate asynchronous I/O on read-ahead blocks.
2280 breada(vp, rablkno, rabsize, cnt, cred, flags, ckhashfunc);
2294 * Write, release buffer on completion. (Done by iodone
2295 * if async). Do not bother writing anything if the buffer
2298 * Note that we set B_CACHE here, indicating that buffer is
2299 * fully valid and thus cacheable. This is true even of NFS
2300 * now so we set it generally. This could be set either here
2301 * or in biodone() since the I/O is synchronous. We put it
2305 bufwrite(struct buf *bp)
2312 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2313 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
2314 bp->b_flags |= B_INVAL | B_RELBUF;
2315 bp->b_flags &= ~B_CACHE;
2319 if (bp->b_flags & B_INVAL) {
2324 if (bp->b_flags & B_BARRIER)
2325 atomic_add_long(&barrierwrites, 1);
2327 oldflags = bp->b_flags;
2329 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
2330 ("FFS background buffer should not get here %p", bp));
2334 vp_md = vp->v_vflag & VV_MD;
2339 * Mark the buffer clean. Increment the bufobj write count
2340 * before bundirty() call, to prevent other thread from seeing
2341 * empty dirty list and zero counter for writes in progress,
2342 * falsely indicating that the bufobj is clean.
2344 bufobj_wref(bp->b_bufobj);
2347 bp->b_flags &= ~B_DONE;
2348 bp->b_ioflags &= ~BIO_ERROR;
2349 bp->b_flags |= B_CACHE;
2350 bp->b_iocmd = BIO_WRITE;
2352 vfs_busy_pages(bp, 1);
2355 * Normal bwrites pipeline writes
2357 bp->b_runningbufspace = bp->b_bufsize;
2358 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
2363 racct_add_buf(curproc, bp, 1);
2364 PROC_UNLOCK(curproc);
2367 curthread->td_ru.ru_oublock++;
2368 if (oldflags & B_ASYNC)
2370 bp->b_iooffset = dbtob(bp->b_blkno);
2371 buf_track(bp, __func__);
2374 if ((oldflags & B_ASYNC) == 0) {
2375 int rtval = bufwait(bp);
2378 } else if (space > hirunningspace) {
2380 * don't allow the async write to saturate the I/O
2381 * system. We will not deadlock here because
2382 * we are blocking waiting for I/O that is already in-progress
2383 * to complete. We do not block here if it is the update
2384 * or syncer daemon trying to clean up as that can lead
2387 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
2388 waitrunningbufspace();
2395 bufbdflush(struct bufobj *bo, struct buf *bp)
2398 struct bufdomain *bd;
2400 bd = &bdomain[bo->bo_domain];
2401 if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh + 10) {
2402 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
2404 } else if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh) {
2407 * Try to find a buffer to flush.
2409 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2410 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2412 LK_EXCLUSIVE | LK_NOWAIT, NULL))
2415 panic("bdwrite: found ourselves");
2417 /* Don't countdeps with the bo lock held. */
2418 if (buf_countdeps(nbp, 0)) {
2423 if (nbp->b_flags & B_CLUSTEROK) {
2424 vfs_bio_awrite(nbp);
2429 dirtybufferflushes++;
2438 * Delayed write. (Buffer is marked dirty). Do not bother writing
2439 * anything if the buffer is marked invalid.
2441 * Note that since the buffer must be completely valid, we can safely
2442 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2443 * biodone() in order to prevent getblk from writing the buffer
2444 * out synchronously.
2447 bdwrite(struct buf *bp)
2449 struct thread *td = curthread;
2453 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2454 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2455 KASSERT((bp->b_flags & B_BARRIER) == 0,
2456 ("Barrier request in delayed write %p", bp));
2458 if (bp->b_flags & B_INVAL) {
2464 * If we have too many dirty buffers, don't create any more.
2465 * If we are wildly over our limit, then force a complete
2466 * cleanup. Otherwise, just keep the situation from getting
2467 * out of control. Note that we have to avoid a recursive
2468 * disaster and not try to clean up after our own cleanup!
2472 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2473 td->td_pflags |= TDP_INBDFLUSH;
2475 td->td_pflags &= ~TDP_INBDFLUSH;
2481 * Set B_CACHE, indicating that the buffer is fully valid. This is
2482 * true even of NFS now.
2484 bp->b_flags |= B_CACHE;
2487 * This bmap keeps the system from needing to do the bmap later,
2488 * perhaps when the system is attempting to do a sync. Since it
2489 * is likely that the indirect block -- or whatever other datastructure
2490 * that the filesystem needs is still in memory now, it is a good
2491 * thing to do this. Note also, that if the pageout daemon is
2492 * requesting a sync -- there might not be enough memory to do
2493 * the bmap then... So, this is important to do.
2495 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2496 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2499 buf_track(bp, __func__);
2502 * Set the *dirty* buffer range based upon the VM system dirty
2505 * Mark the buffer pages as clean. We need to do this here to
2506 * satisfy the vnode_pager and the pageout daemon, so that it
2507 * thinks that the pages have been "cleaned". Note that since
2508 * the pages are in a delayed write buffer -- the VFS layer
2509 * "will" see that the pages get written out on the next sync,
2510 * or perhaps the cluster will be completed.
2512 vfs_clean_pages_dirty_buf(bp);
2516 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2517 * due to the softdep code.
2524 * Turn buffer into delayed write request. We must clear BIO_READ and
2525 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2526 * itself to properly update it in the dirty/clean lists. We mark it
2527 * B_DONE to ensure that any asynchronization of the buffer properly
2528 * clears B_DONE ( else a panic will occur later ).
2530 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2531 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2532 * should only be called if the buffer is known-good.
2534 * Since the buffer is not on a queue, we do not update the numfreebuffers
2537 * The buffer must be on QUEUE_NONE.
2540 bdirty(struct buf *bp)
2543 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2544 bp, bp->b_vp, bp->b_flags);
2545 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2546 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2547 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2548 bp->b_flags &= ~(B_RELBUF);
2549 bp->b_iocmd = BIO_WRITE;
2551 if ((bp->b_flags & B_DELWRI) == 0) {
2552 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2561 * Clear B_DELWRI for buffer.
2563 * Since the buffer is not on a queue, we do not update the numfreebuffers
2566 * The buffer must be on QUEUE_NONE.
2570 bundirty(struct buf *bp)
2573 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2574 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2575 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2576 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2578 if (bp->b_flags & B_DELWRI) {
2579 bp->b_flags &= ~B_DELWRI;
2584 * Since it is now being written, we can clear its deferred write flag.
2586 bp->b_flags &= ~B_DEFERRED;
2592 * Asynchronous write. Start output on a buffer, but do not wait for
2593 * it to complete. The buffer is released when the output completes.
2595 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2596 * B_INVAL buffers. Not us.
2599 bawrite(struct buf *bp)
2602 bp->b_flags |= B_ASYNC;
2609 * Asynchronous barrier write. Start output on a buffer, but do not
2610 * wait for it to complete. Place a write barrier after this write so
2611 * that this buffer and all buffers written before it are committed to
2612 * the disk before any buffers written after this write are committed
2613 * to the disk. The buffer is released when the output completes.
2616 babarrierwrite(struct buf *bp)
2619 bp->b_flags |= B_ASYNC | B_BARRIER;
2626 * Synchronous barrier write. Start output on a buffer and wait for
2627 * it to complete. Place a write barrier after this write so that
2628 * this buffer and all buffers written before it are committed to
2629 * the disk before any buffers written after this write are committed
2630 * to the disk. The buffer is released when the output completes.
2633 bbarrierwrite(struct buf *bp)
2636 bp->b_flags |= B_BARRIER;
2637 return (bwrite(bp));
2643 * Called prior to the locking of any vnodes when we are expecting to
2644 * write. We do not want to starve the buffer cache with too many
2645 * dirty buffers so we block here. By blocking prior to the locking
2646 * of any vnodes we attempt to avoid the situation where a locked vnode
2647 * prevents the various system daemons from flushing related buffers.
2653 if (buf_dirty_count_severe()) {
2654 mtx_lock(&bdirtylock);
2655 while (buf_dirty_count_severe()) {
2657 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2660 mtx_unlock(&bdirtylock);
2665 * Return true if we have too many dirty buffers.
2668 buf_dirty_count_severe(void)
2671 return (!BIT_EMPTY(BUF_DOMAINS, &bdhidirty));
2677 * Release a busy buffer and, if requested, free its resources. The
2678 * buffer will be stashed in the appropriate bufqueue[] allowing it
2679 * to be accessed later as a cache entity or reused for other purposes.
2682 brelse(struct buf *bp)
2684 struct mount *v_mnt;
2688 * Many functions erroneously call brelse with a NULL bp under rare
2689 * error conditions. Simply return when called with a NULL bp.
2693 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2694 bp, bp->b_vp, bp->b_flags);
2695 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2696 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2697 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2698 ("brelse: non-VMIO buffer marked NOREUSE"));
2700 if (BUF_LOCKRECURSED(bp)) {
2702 * Do not process, in particular, do not handle the
2703 * B_INVAL/B_RELBUF and do not release to free list.
2709 if (bp->b_flags & B_MANAGED) {
2714 if (LIST_EMPTY(&bp->b_dep)) {
2715 bp->b_flags &= ~B_IOSTARTED;
2717 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2718 ("brelse: SU io not finished bp %p", bp));
2721 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2722 BO_LOCK(bp->b_bufobj);
2723 bp->b_vflags &= ~BV_BKGRDERR;
2724 BO_UNLOCK(bp->b_bufobj);
2728 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2729 (bp->b_flags & B_INVALONERR)) {
2731 * Forced invalidation of dirty buffer contents, to be used
2732 * after a failed write in the rare case that the loss of the
2733 * contents is acceptable. The buffer is invalidated and
2736 bp->b_flags |= B_INVAL | B_RELBUF | B_NOCACHE;
2737 bp->b_flags &= ~(B_ASYNC | B_CACHE);
2740 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2741 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2742 !(bp->b_flags & B_INVAL)) {
2744 * Failed write, redirty. All errors except ENXIO (which
2745 * means the device is gone) are treated as being
2748 * XXX Treating EIO as transient is not correct; the
2749 * contract with the local storage device drivers is that
2750 * they will only return EIO once the I/O is no longer
2751 * retriable. Network I/O also respects this through the
2752 * guarantees of TCP and/or the internal retries of NFS.
2753 * ENOMEM might be transient, but we also have no way of
2754 * knowing when its ok to retry/reschedule. In general,
2755 * this entire case should be made obsolete through better
2756 * error handling/recovery and resource scheduling.
2758 * Do this also for buffers that failed with ENXIO, but have
2759 * non-empty dependencies - the soft updates code might need
2760 * to access the buffer to untangle them.
2762 * Must clear BIO_ERROR to prevent pages from being scrapped.
2764 bp->b_ioflags &= ~BIO_ERROR;
2766 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2767 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2769 * Either a failed read I/O, or we were asked to free or not
2770 * cache the buffer, or we failed to write to a device that's
2771 * no longer present.
2773 bp->b_flags |= B_INVAL;
2774 if (!LIST_EMPTY(&bp->b_dep))
2776 if (bp->b_flags & B_DELWRI)
2778 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2779 if ((bp->b_flags & B_VMIO) == 0) {
2787 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2788 * is called with B_DELWRI set, the underlying pages may wind up
2789 * getting freed causing a previous write (bdwrite()) to get 'lost'
2790 * because pages associated with a B_DELWRI bp are marked clean.
2792 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2793 * if B_DELWRI is set.
2795 if (bp->b_flags & B_DELWRI)
2796 bp->b_flags &= ~B_RELBUF;
2799 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2800 * constituted, not even NFS buffers now. Two flags effect this. If
2801 * B_INVAL, the struct buf is invalidated but the VM object is kept
2802 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2804 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2805 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2806 * buffer is also B_INVAL because it hits the re-dirtying code above.
2808 * Normally we can do this whether a buffer is B_DELWRI or not. If
2809 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2810 * the commit state and we cannot afford to lose the buffer. If the
2811 * buffer has a background write in progress, we need to keep it
2812 * around to prevent it from being reconstituted and starting a second
2816 v_mnt = bp->b_vp != NULL ? bp->b_vp->v_mount : NULL;
2818 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2819 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2820 (v_mnt == NULL || (v_mnt->mnt_vfc->vfc_flags & VFCF_NETWORK) == 0 ||
2821 vn_isdisk(bp->b_vp) || (bp->b_flags & B_DELWRI) == 0)) {
2822 vfs_vmio_invalidate(bp);
2826 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2827 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2829 bp->b_flags &= ~B_NOREUSE;
2830 if (bp->b_vp != NULL)
2835 * If the buffer has junk contents signal it and eventually
2836 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2839 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2840 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2841 bp->b_flags |= B_INVAL;
2842 if (bp->b_flags & B_INVAL) {
2843 if (bp->b_flags & B_DELWRI)
2849 buf_track(bp, __func__);
2851 /* buffers with no memory */
2852 if (bp->b_bufsize == 0) {
2856 /* buffers with junk contents */
2857 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2858 (bp->b_ioflags & BIO_ERROR)) {
2859 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2860 if (bp->b_vflags & BV_BKGRDINPROG)
2861 panic("losing buffer 2");
2862 qindex = QUEUE_CLEAN;
2863 bp->b_flags |= B_AGE;
2864 /* remaining buffers */
2865 } else if (bp->b_flags & B_DELWRI)
2866 qindex = QUEUE_DIRTY;
2868 qindex = QUEUE_CLEAN;
2870 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2871 panic("brelse: not dirty");
2873 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
2874 bp->b_xflags &= ~(BX_CVTENXIO);
2875 /* binsfree unlocks bp. */
2876 binsfree(bp, qindex);
2880 * Release a buffer back to the appropriate queue but do not try to free
2881 * it. The buffer is expected to be used again soon.
2883 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2884 * biodone() to requeue an async I/O on completion. It is also used when
2885 * known good buffers need to be requeued but we think we may need the data
2888 * XXX we should be able to leave the B_RELBUF hint set on completion.
2891 bqrelse(struct buf *bp)
2895 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2896 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2897 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2899 qindex = QUEUE_NONE;
2900 if (BUF_LOCKRECURSED(bp)) {
2901 /* do not release to free list */
2905 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2906 bp->b_xflags &= ~(BX_CVTENXIO);
2908 if (LIST_EMPTY(&bp->b_dep)) {
2909 bp->b_flags &= ~B_IOSTARTED;
2911 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2912 ("bqrelse: SU io not finished bp %p", bp));
2915 if (bp->b_flags & B_MANAGED) {
2916 if (bp->b_flags & B_REMFREE)
2921 /* buffers with stale but valid contents */
2922 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2923 BV_BKGRDERR)) == BV_BKGRDERR) {
2924 BO_LOCK(bp->b_bufobj);
2925 bp->b_vflags &= ~BV_BKGRDERR;
2926 BO_UNLOCK(bp->b_bufobj);
2927 qindex = QUEUE_DIRTY;
2929 if ((bp->b_flags & B_DELWRI) == 0 &&
2930 (bp->b_xflags & BX_VNDIRTY))
2931 panic("bqrelse: not dirty");
2932 if ((bp->b_flags & B_NOREUSE) != 0) {
2936 qindex = QUEUE_CLEAN;
2938 buf_track(bp, __func__);
2939 /* binsfree unlocks bp. */
2940 binsfree(bp, qindex);
2944 buf_track(bp, __func__);
2950 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2951 * restore bogus pages.
2954 vfs_vmio_iodone(struct buf *bp)
2959 struct vnode *vp __unused;
2960 int i, iosize, resid;
2963 obj = bp->b_bufobj->bo_object;
2964 KASSERT(blockcount_read(&obj->paging_in_progress) >= bp->b_npages,
2965 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2966 blockcount_read(&obj->paging_in_progress), bp->b_npages));
2969 VNPASS(vp->v_holdcnt > 0, vp);
2970 VNPASS(vp->v_object != NULL, vp);
2972 foff = bp->b_offset;
2973 KASSERT(bp->b_offset != NOOFFSET,
2974 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2977 iosize = bp->b_bcount - bp->b_resid;
2978 for (i = 0; i < bp->b_npages; i++) {
2979 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2984 * cleanup bogus pages, restoring the originals
2987 if (m == bogus_page) {
2989 m = vm_page_relookup(obj, OFF_TO_IDX(foff));
2991 panic("biodone: page disappeared!");
2993 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2995 * In the write case, the valid and clean bits are
2996 * already changed correctly ( see bdwrite() ), so we
2997 * only need to do this here in the read case.
2999 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
3000 resid)) == 0, ("vfs_vmio_iodone: page %p "
3001 "has unexpected dirty bits", m));
3002 vfs_page_set_valid(bp, foff, m);
3004 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3005 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
3006 (intmax_t)foff, (uintmax_t)m->pindex));
3009 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3012 vm_object_pip_wakeupn(obj, bp->b_npages);
3013 if (bogus && buf_mapped(bp)) {
3014 BUF_CHECK_MAPPED(bp);
3015 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3016 bp->b_pages, bp->b_npages);
3021 * Perform page invalidation when a buffer is released. The fully invalid
3022 * pages will be reclaimed later in vfs_vmio_truncate().
3025 vfs_vmio_invalidate(struct buf *bp)
3029 int flags, i, resid, poffset, presid;
3031 if (buf_mapped(bp)) {
3032 BUF_CHECK_MAPPED(bp);
3033 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
3035 BUF_CHECK_UNMAPPED(bp);
3037 * Get the base offset and length of the buffer. Note that
3038 * in the VMIO case if the buffer block size is not
3039 * page-aligned then b_data pointer may not be page-aligned.
3040 * But our b_pages[] array *IS* page aligned.
3042 * block sizes less then DEV_BSIZE (usually 512) are not
3043 * supported due to the page granularity bits (m->valid,
3044 * m->dirty, etc...).
3046 * See man buf(9) for more information
3048 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3049 obj = bp->b_bufobj->bo_object;
3050 resid = bp->b_bufsize;
3051 poffset = bp->b_offset & PAGE_MASK;
3052 VM_OBJECT_WLOCK(obj);
3053 for (i = 0; i < bp->b_npages; i++) {
3055 if (m == bogus_page)
3056 panic("vfs_vmio_invalidate: Unexpected bogus page.");
3057 bp->b_pages[i] = NULL;
3059 presid = resid > (PAGE_SIZE - poffset) ?
3060 (PAGE_SIZE - poffset) : resid;
3061 KASSERT(presid >= 0, ("brelse: extra page"));
3062 vm_page_busy_acquire(m, VM_ALLOC_SBUSY);
3063 if (pmap_page_wired_mappings(m) == 0)
3064 vm_page_set_invalid(m, poffset, presid);
3066 vm_page_release_locked(m, flags);
3070 VM_OBJECT_WUNLOCK(obj);
3075 * Page-granular truncation of an existing VMIO buffer.
3078 vfs_vmio_truncate(struct buf *bp, int desiredpages)
3084 if (bp->b_npages == desiredpages)
3087 if (buf_mapped(bp)) {
3088 BUF_CHECK_MAPPED(bp);
3089 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
3090 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
3092 BUF_CHECK_UNMAPPED(bp);
3095 * The object lock is needed only if we will attempt to free pages.
3097 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3098 if ((bp->b_flags & B_DIRECT) != 0) {
3099 flags |= VPR_TRYFREE;
3100 obj = bp->b_bufobj->bo_object;
3101 VM_OBJECT_WLOCK(obj);
3105 for (i = desiredpages; i < bp->b_npages; i++) {
3107 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
3108 bp->b_pages[i] = NULL;
3110 vm_page_release_locked(m, flags);
3112 vm_page_release(m, flags);
3115 VM_OBJECT_WUNLOCK(obj);
3116 bp->b_npages = desiredpages;
3120 * Byte granular extension of VMIO buffers.
3123 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
3126 * We are growing the buffer, possibly in a
3127 * byte-granular fashion.
3135 * Step 1, bring in the VM pages from the object, allocating
3136 * them if necessary. We must clear B_CACHE if these pages
3137 * are not valid for the range covered by the buffer.
3139 obj = bp->b_bufobj->bo_object;
3140 if (bp->b_npages < desiredpages) {
3141 KASSERT(desiredpages <= atop(maxbcachebuf),
3142 ("vfs_vmio_extend past maxbcachebuf %p %d %u",
3143 bp, desiredpages, maxbcachebuf));
3146 * We must allocate system pages since blocking
3147 * here could interfere with paging I/O, no
3148 * matter which process we are.
3150 * Only exclusive busy can be tested here.
3151 * Blocking on shared busy might lead to
3152 * deadlocks once allocbuf() is called after
3153 * pages are vfs_busy_pages().
3155 (void)vm_page_grab_pages_unlocked(obj,
3156 OFF_TO_IDX(bp->b_offset) + bp->b_npages,
3157 VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
3158 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
3159 &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
3160 bp->b_npages = desiredpages;
3164 * Step 2. We've loaded the pages into the buffer,
3165 * we have to figure out if we can still have B_CACHE
3166 * set. Note that B_CACHE is set according to the
3167 * byte-granular range ( bcount and size ), not the
3168 * aligned range ( newbsize ).
3170 * The VM test is against m->valid, which is DEV_BSIZE
3171 * aligned. Needless to say, the validity of the data
3172 * needs to also be DEV_BSIZE aligned. Note that this
3173 * fails with NFS if the server or some other client
3174 * extends the file's EOF. If our buffer is resized,
3175 * B_CACHE may remain set! XXX
3177 toff = bp->b_bcount;
3178 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3179 while ((bp->b_flags & B_CACHE) && toff < size) {
3182 if (tinc > (size - toff))
3184 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
3185 m = bp->b_pages[pi];
3186 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
3192 * Step 3, fixup the KVA pmap.
3197 BUF_CHECK_UNMAPPED(bp);
3201 * Check to see if a block at a particular lbn is available for a clustered
3205 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
3212 /* If the buf isn't in core skip it */
3213 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
3216 /* If the buf is busy we don't want to wait for it */
3217 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
3220 /* Only cluster with valid clusterable delayed write buffers */
3221 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
3222 (B_DELWRI | B_CLUSTEROK))
3225 if (bpa->b_bufsize != size)
3229 * Check to see if it is in the expected place on disk and that the
3230 * block has been mapped.
3232 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
3242 * Implement clustered async writes for clearing out B_DELWRI buffers.
3243 * This is much better then the old way of writing only one buffer at
3244 * a time. Note that we may not be presented with the buffers in the
3245 * correct order, so we search for the cluster in both directions.
3248 vfs_bio_awrite(struct buf *bp)
3253 daddr_t lblkno = bp->b_lblkno;
3254 struct vnode *vp = bp->b_vp;
3262 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
3264 * right now we support clustered writing only to regular files. If
3265 * we find a clusterable block we could be in the middle of a cluster
3266 * rather then at the beginning.
3268 if ((vp->v_type == VREG) &&
3269 (vp->v_mount != 0) && /* Only on nodes that have the size info */
3270 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
3271 size = vp->v_mount->mnt_stat.f_iosize;
3272 maxcl = maxphys / size;
3275 for (i = 1; i < maxcl; i++)
3276 if (vfs_bio_clcheck(vp, size, lblkno + i,
3277 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
3280 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
3281 if (vfs_bio_clcheck(vp, size, lblkno - j,
3282 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
3288 * this is a possible cluster write
3292 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
3298 bp->b_flags |= B_ASYNC;
3300 * default (old) behavior, writing out only one block
3302 * XXX returns b_bufsize instead of b_bcount for nwritten?
3304 nwritten = bp->b_bufsize;
3313 * Allocate KVA for an empty buf header according to gbflags.
3316 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
3319 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
3321 * In order to keep fragmentation sane we only allocate kva
3322 * in BKVASIZE chunks. XXX with vmem we can do page size.
3324 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
3326 if (maxsize != bp->b_kvasize &&
3327 bufkva_alloc(bp, maxsize, gbflags))
3336 * Find and initialize a new buffer header, freeing up existing buffers
3337 * in the bufqueues as necessary. The new buffer is returned locked.
3340 * We have insufficient buffer headers
3341 * We have insufficient buffer space
3342 * buffer_arena is too fragmented ( space reservation fails )
3343 * If we have to flush dirty buffers ( but we try to avoid this )
3345 * The caller is responsible for releasing the reserved bufspace after
3346 * allocbuf() is called.
3349 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
3351 struct bufdomain *bd;
3353 bool metadata, reserved;
3356 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3357 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3358 if (!unmapped_buf_allowed)
3359 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3361 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
3369 bd = &bdomain[vp->v_bufobj.bo_domain];
3371 counter_u64_add(getnewbufcalls, 1);
3374 if (reserved == false &&
3375 bufspace_reserve(bd, maxsize, metadata) != 0) {
3376 counter_u64_add(getnewbufrestarts, 1);
3380 if ((bp = buf_alloc(bd)) == NULL) {
3381 counter_u64_add(getnewbufrestarts, 1);
3384 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
3387 } while (buf_recycle(bd, false) == 0);
3390 bufspace_release(bd, maxsize);
3392 bp->b_flags |= B_INVAL;
3395 bufspace_wait(bd, vp, gbflags, slpflag, slptimeo);
3403 * buffer flushing daemon. Buffers are normally flushed by the
3404 * update daemon but if it cannot keep up this process starts to
3405 * take the load in an attempt to prevent getnewbuf() from blocking.
3407 static struct kproc_desc buf_kp = {
3412 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3415 buf_flush(struct vnode *vp, struct bufdomain *bd, int target)
3419 flushed = flushbufqueues(vp, bd, target, 0);
3422 * Could not find any buffers without rollback
3423 * dependencies, so just write the first one
3424 * in the hopes of eventually making progress.
3426 if (vp != NULL && target > 2)
3428 flushbufqueues(vp, bd, target, 1);
3434 buf_daemon_shutdown(void *arg __unused, int howto __unused)
3438 if (KERNEL_PANICKED())
3443 wakeup(&bd_request);
3444 error = msleep(&bd_shutdown, &bdlock, 0, "buf_daemon_shutdown",
3446 mtx_unlock(&bdlock);
3448 printf("bufdaemon wait error: %d\n", error);
3454 struct bufdomain *bd;
3460 * This process needs to be suspended prior to shutdown sync.
3462 EVENTHANDLER_REGISTER(shutdown_pre_sync, buf_daemon_shutdown, NULL,
3463 SHUTDOWN_PRI_LAST + 100);
3466 * Start the buf clean daemons as children threads.
3468 for (i = 0 ; i < buf_domains; i++) {
3471 error = kthread_add((void (*)(void *))bufspace_daemon,
3472 &bdomain[i], curproc, NULL, 0, 0, "bufspacedaemon-%d", i);
3474 panic("error %d spawning bufspace daemon", error);
3478 * This process is allowed to take the buffer cache to the limit
3480 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3482 while (!bd_shutdown) {
3484 mtx_unlock(&bdlock);
3487 * Save speedupreq for this pass and reset to capture new
3490 speedupreq = bd_speedupreq;
3494 * Flush each domain sequentially according to its level and
3495 * the speedup request.
3497 for (i = 0; i < buf_domains; i++) {
3500 lodirty = bd->bd_numdirtybuffers / 2;
3502 lodirty = bd->bd_lodirtybuffers;
3503 while (bd->bd_numdirtybuffers > lodirty) {
3504 if (buf_flush(NULL, bd,
3505 bd->bd_numdirtybuffers - lodirty) == 0)
3507 kern_yield(PRI_USER);
3512 * Only clear bd_request if we have reached our low water
3513 * mark. The buf_daemon normally waits 1 second and
3514 * then incrementally flushes any dirty buffers that have
3515 * built up, within reason.
3517 * If we were unable to hit our low water mark and couldn't
3518 * find any flushable buffers, we sleep for a short period
3519 * to avoid endless loops on unlockable buffers.
3524 if (BIT_EMPTY(BUF_DOMAINS, &bdlodirty)) {
3526 * We reached our low water mark, reset the
3527 * request and sleep until we are needed again.
3528 * The sleep is just so the suspend code works.
3532 * Do an extra wakeup in case dirty threshold
3533 * changed via sysctl and the explicit transition
3534 * out of shortfall was missed.
3537 if (runningbufspace <= lorunningspace)
3539 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3542 * We couldn't find any flushable dirty buffers but
3543 * still have too many dirty buffers, we
3544 * have to sleep and try again. (rare)
3546 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3549 wakeup(&bd_shutdown);
3550 mtx_unlock(&bdlock);
3557 * Try to flush a buffer in the dirty queue. We must be careful to
3558 * free up B_INVAL buffers instead of write them, which NFS is
3559 * particularly sensitive to.
3561 static int flushwithdeps = 0;
3562 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW | CTLFLAG_STATS,
3564 "Number of buffers flushed with dependencies that require rollbacks");
3567 flushbufqueues(struct vnode *lvp, struct bufdomain *bd, int target,
3570 struct bufqueue *bq;
3571 struct buf *sentinel;
3581 bq = &bd->bd_dirtyq;
3583 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3584 sentinel->b_qindex = QUEUE_SENTINEL;
3586 TAILQ_INSERT_HEAD(&bq->bq_queue, sentinel, b_freelist);
3588 while (flushed != target) {
3591 bp = TAILQ_NEXT(sentinel, b_freelist);
3593 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3594 TAILQ_INSERT_AFTER(&bq->bq_queue, bp, sentinel,
3601 * Skip sentinels inserted by other invocations of the
3602 * flushbufqueues(), taking care to not reorder them.
3604 * Only flush the buffers that belong to the
3605 * vnode locked by the curthread.
3607 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3612 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3618 * BKGRDINPROG can only be set with the buf and bufobj
3619 * locks both held. We tolerate a race to clear it here.
3621 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3622 (bp->b_flags & B_DELWRI) == 0) {
3626 if (bp->b_flags & B_INVAL) {
3633 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3634 if (flushdeps == 0) {
3642 * We must hold the lock on a vnode before writing
3643 * one of its buffers. Otherwise we may confuse, or
3644 * in the case of a snapshot vnode, deadlock the
3647 * The lock order here is the reverse of the normal
3648 * of vnode followed by buf lock. This is ok because
3649 * the NOWAIT will prevent deadlock.
3652 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3658 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3660 ASSERT_VOP_LOCKED(vp, "getbuf");
3662 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3663 vn_lock(vp, LK_TRYUPGRADE);
3666 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3667 bp, bp->b_vp, bp->b_flags);
3668 if (curproc == bufdaemonproc) {
3673 counter_u64_add(notbufdflushes, 1);
3675 vn_finished_write(mp);
3678 flushwithdeps += hasdeps;
3682 * Sleeping on runningbufspace while holding
3683 * vnode lock leads to deadlock.
3685 if (curproc == bufdaemonproc &&
3686 runningbufspace > hirunningspace)
3687 waitrunningbufspace();
3690 vn_finished_write(mp);
3694 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3696 free(sentinel, M_TEMP);
3701 * Check to see if a block is currently memory resident.
3704 incore(struct bufobj *bo, daddr_t blkno)
3706 return (gbincore_unlocked(bo, blkno));
3710 * Returns true if no I/O is needed to access the
3711 * associated VM object. This is like incore except
3712 * it also hunts around in the VM system for the data.
3715 inmem(struct vnode * vp, daddr_t blkno)
3718 vm_offset_t toff, tinc, size;
3723 ASSERT_VOP_LOCKED(vp, "inmem");
3725 if (incore(&vp->v_bufobj, blkno))
3727 if (vp->v_mount == NULL)
3734 if (size > vp->v_mount->mnt_stat.f_iosize)
3735 size = vp->v_mount->mnt_stat.f_iosize;
3736 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3738 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3739 m = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3745 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3746 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3748 * Consider page validity only if page mapping didn't change
3751 valid = vm_page_is_valid(m,
3752 (vm_offset_t)((toff + off) & PAGE_MASK), tinc);
3753 n = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3765 * Set the dirty range for a buffer based on the status of the dirty
3766 * bits in the pages comprising the buffer. The range is limited
3767 * to the size of the buffer.
3769 * Tell the VM system that the pages associated with this buffer
3770 * are clean. This is used for delayed writes where the data is
3771 * going to go to disk eventually without additional VM intevention.
3773 * Note that while we only really need to clean through to b_bcount, we
3774 * just go ahead and clean through to b_bufsize.
3777 vfs_clean_pages_dirty_buf(struct buf *bp)
3779 vm_ooffset_t foff, noff, eoff;
3783 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3786 foff = bp->b_offset;
3787 KASSERT(bp->b_offset != NOOFFSET,
3788 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3790 vfs_busy_pages_acquire(bp);
3791 vfs_setdirty_range(bp);
3792 for (i = 0; i < bp->b_npages; i++) {
3793 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3795 if (eoff > bp->b_offset + bp->b_bufsize)
3796 eoff = bp->b_offset + bp->b_bufsize;
3798 vfs_page_set_validclean(bp, foff, m);
3799 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3802 vfs_busy_pages_release(bp);
3806 vfs_setdirty_range(struct buf *bp)
3808 vm_offset_t boffset;
3809 vm_offset_t eoffset;
3813 * test the pages to see if they have been modified directly
3814 * by users through the VM system.
3816 for (i = 0; i < bp->b_npages; i++)
3817 vm_page_test_dirty(bp->b_pages[i]);
3820 * Calculate the encompassing dirty range, boffset and eoffset,
3821 * (eoffset - boffset) bytes.
3824 for (i = 0; i < bp->b_npages; i++) {
3825 if (bp->b_pages[i]->dirty)
3828 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3830 for (i = bp->b_npages - 1; i >= 0; --i) {
3831 if (bp->b_pages[i]->dirty) {
3835 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3838 * Fit it to the buffer.
3841 if (eoffset > bp->b_bcount)
3842 eoffset = bp->b_bcount;
3845 * If we have a good dirty range, merge with the existing
3849 if (boffset < eoffset) {
3850 if (bp->b_dirtyoff > boffset)
3851 bp->b_dirtyoff = boffset;
3852 if (bp->b_dirtyend < eoffset)
3853 bp->b_dirtyend = eoffset;
3858 * Allocate the KVA mapping for an existing buffer.
3859 * If an unmapped buffer is provided but a mapped buffer is requested, take
3860 * also care to properly setup mappings between pages and KVA.
3863 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3865 int bsize, maxsize, need_mapping, need_kva;
3868 need_mapping = bp->b_data == unmapped_buf &&
3869 (gbflags & GB_UNMAPPED) == 0;
3870 need_kva = bp->b_kvabase == unmapped_buf &&
3871 bp->b_data == unmapped_buf &&
3872 (gbflags & GB_KVAALLOC) != 0;
3873 if (!need_mapping && !need_kva)
3876 BUF_CHECK_UNMAPPED(bp);
3878 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3880 * Buffer is not mapped, but the KVA was already
3881 * reserved at the time of the instantiation. Use the
3888 * Calculate the amount of the address space we would reserve
3889 * if the buffer was mapped.
3891 bsize = vn_isdisk(bp->b_vp) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3892 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3893 offset = blkno * bsize;
3894 maxsize = size + (offset & PAGE_MASK);
3895 maxsize = imax(maxsize, bsize);
3897 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3898 if ((gbflags & GB_NOWAIT_BD) != 0) {
3900 * XXXKIB: defragmentation cannot
3901 * succeed, not sure what else to do.
3903 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3905 counter_u64_add(mappingrestarts, 1);
3906 bufspace_wait(bufdomain(bp), bp->b_vp, gbflags, 0, 0);
3910 /* b_offset is handled by bpmap_qenter. */
3911 bp->b_data = bp->b_kvabase;
3912 BUF_CHECK_MAPPED(bp);
3918 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3924 error = getblkx(vp, blkno, blkno, size, slpflag, slptimeo, flags, &bp);
3933 * Get a block given a specified block and offset into a file/device.
3934 * The buffers B_DONE bit will be cleared on return, making it almost
3935 * ready for an I/O initiation. B_INVAL may or may not be set on
3936 * return. The caller should clear B_INVAL prior to initiating a
3939 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3940 * an existing buffer.
3942 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3943 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3944 * and then cleared based on the backing VM. If the previous buffer is
3945 * non-0-sized but invalid, B_CACHE will be cleared.
3947 * If getblk() must create a new buffer, the new buffer is returned with
3948 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3949 * case it is returned with B_INVAL clear and B_CACHE set based on the
3952 * getblk() also forces a bwrite() for any B_DELWRI buffer whose
3953 * B_CACHE bit is clear.
3955 * What this means, basically, is that the caller should use B_CACHE to
3956 * determine whether the buffer is fully valid or not and should clear
3957 * B_INVAL prior to issuing a read. If the caller intends to validate
3958 * the buffer by loading its data area with something, the caller needs
3959 * to clear B_INVAL. If the caller does this without issuing an I/O,
3960 * the caller should set B_CACHE ( as an optimization ), else the caller
3961 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3962 * a write attempt or if it was a successful read. If the caller
3963 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3964 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3966 * The blkno parameter is the logical block being requested. Normally
3967 * the mapping of logical block number to disk block address is done
3968 * by calling VOP_BMAP(). However, if the mapping is already known, the
3969 * disk block address can be passed using the dblkno parameter. If the
3970 * disk block address is not known, then the same value should be passed
3971 * for blkno and dblkno.
3974 getblkx(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size, int slpflag,
3975 int slptimeo, int flags, struct buf **bpp)
3980 int bsize, error, maxsize, vmio;
3983 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3984 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3985 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3986 if (vp->v_type != VCHR)
3987 ASSERT_VOP_LOCKED(vp, "getblk");
3988 if (size > maxbcachebuf) {
3989 printf("getblkx: size(%d) > maxbcachebuf(%d)\n", size,
3993 if (!unmapped_buf_allowed)
3994 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3999 /* Attempt lockless lookup first. */
4000 bp = gbincore_unlocked(bo, blkno);
4003 * With GB_NOCREAT we must be sure about not finding the buffer
4004 * as it may have been reassigned during unlocked lookup.
4006 if ((flags & GB_NOCREAT) != 0)
4008 goto newbuf_unlocked;
4011 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL, "getblku", 0,
4016 /* Verify buf identify has not changed since lookup. */
4017 if (bp->b_bufobj == bo && bp->b_lblkno == blkno)
4018 goto foundbuf_fastpath;
4020 /* It changed, fallback to locked lookup. */
4025 bp = gbincore(bo, blkno);
4030 * Buffer is in-core. If the buffer is not busy nor managed,
4031 * it must be on a queue.
4033 lockflags = LK_EXCLUSIVE | LK_INTERLOCK |
4034 ((flags & GB_LOCK_NOWAIT) != 0 ? LK_NOWAIT : LK_SLEEPFAIL);
4036 lockflags |= (flags & GB_NOWITNESS) != 0 ? LK_NOWITNESS : 0;
4039 error = BUF_TIMELOCK(bp, lockflags,
4040 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
4043 * If we slept and got the lock we have to restart in case
4044 * the buffer changed identities.
4046 if (error == ENOLCK)
4048 /* We timed out or were interrupted. */
4049 else if (error != 0)
4053 /* If recursed, assume caller knows the rules. */
4054 if (BUF_LOCKRECURSED(bp))
4058 * The buffer is locked. B_CACHE is cleared if the buffer is
4059 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
4060 * and for a VMIO buffer B_CACHE is adjusted according to the
4063 if (bp->b_flags & B_INVAL)
4064 bp->b_flags &= ~B_CACHE;
4065 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
4066 bp->b_flags |= B_CACHE;
4067 if (bp->b_flags & B_MANAGED)
4068 MPASS(bp->b_qindex == QUEUE_NONE);
4073 * check for size inconsistencies for non-VMIO case.
4075 if (bp->b_bcount != size) {
4076 if ((bp->b_flags & B_VMIO) == 0 ||
4077 (size > bp->b_kvasize)) {
4078 if (bp->b_flags & B_DELWRI) {
4079 bp->b_flags |= B_NOCACHE;
4082 if (LIST_EMPTY(&bp->b_dep)) {
4083 bp->b_flags |= B_RELBUF;
4086 bp->b_flags |= B_NOCACHE;
4095 * Handle the case of unmapped buffer which should
4096 * become mapped, or the buffer for which KVA
4097 * reservation is requested.
4099 bp_unmapped_get_kva(bp, blkno, size, flags);
4102 * If the size is inconsistent in the VMIO case, we can resize
4103 * the buffer. This might lead to B_CACHE getting set or
4104 * cleared. If the size has not changed, B_CACHE remains
4105 * unchanged from its previous state.
4109 KASSERT(bp->b_offset != NOOFFSET,
4110 ("getblk: no buffer offset"));
4113 * A buffer with B_DELWRI set and B_CACHE clear must
4114 * be committed before we can return the buffer in
4115 * order to prevent the caller from issuing a read
4116 * ( due to B_CACHE not being set ) and overwriting
4119 * Most callers, including NFS and FFS, need this to
4120 * operate properly either because they assume they
4121 * can issue a read if B_CACHE is not set, or because
4122 * ( for example ) an uncached B_DELWRI might loop due
4123 * to softupdates re-dirtying the buffer. In the latter
4124 * case, B_CACHE is set after the first write completes,
4125 * preventing further loops.
4126 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
4127 * above while extending the buffer, we cannot allow the
4128 * buffer to remain with B_CACHE set after the write
4129 * completes or it will represent a corrupt state. To
4130 * deal with this we set B_NOCACHE to scrap the buffer
4133 * We might be able to do something fancy, like setting
4134 * B_CACHE in bwrite() except if B_DELWRI is already set,
4135 * so the below call doesn't set B_CACHE, but that gets real
4136 * confusing. This is much easier.
4139 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
4140 bp->b_flags |= B_NOCACHE;
4144 bp->b_flags &= ~B_DONE;
4147 * Buffer is not in-core, create new buffer. The buffer
4148 * returned by getnewbuf() is locked. Note that the returned
4149 * buffer is also considered valid (not marked B_INVAL).
4154 * If the user does not want us to create the buffer, bail out
4157 if (flags & GB_NOCREAT)
4160 bsize = vn_isdisk(vp) ? DEV_BSIZE : bo->bo_bsize;
4161 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
4162 offset = blkno * bsize;
4163 vmio = vp->v_object != NULL;
4165 maxsize = size + (offset & PAGE_MASK);
4166 if (maxsize > maxbcachebuf) {
4168 "getblkx: maxsize(%d) > maxbcachebuf(%d)\n",
4169 maxsize, maxbcachebuf);
4174 /* Do not allow non-VMIO notmapped buffers. */
4175 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
4177 maxsize = imax(maxsize, bsize);
4178 if ((flags & GB_NOSPARSE) != 0 && vmio &&
4180 error = VOP_BMAP(vp, blkno, NULL, &d_blkno, 0, 0);
4181 KASSERT(error != EOPNOTSUPP,
4182 ("GB_NOSPARSE from fs not supporting bmap, vp %p",
4187 return (EJUSTRETURN);
4190 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
4192 if (slpflag || slptimeo)
4195 * XXX This is here until the sleep path is diagnosed
4196 * enough to work under very low memory conditions.
4198 * There's an issue on low memory, 4BSD+non-preempt
4199 * systems (eg MIPS routers with 32MB RAM) where buffer
4200 * exhaustion occurs without sleeping for buffer
4201 * reclaimation. This just sticks in a loop and
4202 * constantly attempts to allocate a buffer, which
4203 * hits exhaustion and tries to wakeup bufdaemon.
4204 * This never happens because we never yield.
4206 * The real solution is to identify and fix these cases
4207 * so we aren't effectively busy-waiting in a loop
4208 * until the reclaimation path has cycles to run.
4210 kern_yield(PRI_USER);
4215 * This code is used to make sure that a buffer is not
4216 * created while the getnewbuf routine is blocked.
4217 * This can be a problem whether the vnode is locked or not.
4218 * If the buffer is created out from under us, we have to
4219 * throw away the one we just created.
4221 * Note: this must occur before we associate the buffer
4222 * with the vp especially considering limitations in
4223 * the splay tree implementation when dealing with duplicate
4227 if (gbincore(bo, blkno)) {
4229 bp->b_flags |= B_INVAL;
4230 bufspace_release(bufdomain(bp), maxsize);
4236 * Insert the buffer into the hash, so that it can
4237 * be found by incore.
4239 bp->b_lblkno = blkno;
4240 bp->b_blkno = d_blkno;
4241 bp->b_offset = offset;
4246 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
4247 * buffer size starts out as 0, B_CACHE will be set by
4248 * allocbuf() for the VMIO case prior to it testing the
4249 * backing store for validity.
4253 bp->b_flags |= B_VMIO;
4254 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
4255 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
4256 bp, vp->v_object, bp->b_bufobj->bo_object));
4258 bp->b_flags &= ~B_VMIO;
4259 KASSERT(bp->b_bufobj->bo_object == NULL,
4260 ("ARGH! has b_bufobj->bo_object %p %p\n",
4261 bp, bp->b_bufobj->bo_object));
4262 BUF_CHECK_MAPPED(bp);
4266 bufspace_release(bufdomain(bp), maxsize);
4267 bp->b_flags &= ~B_DONE;
4269 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
4271 buf_track(bp, __func__);
4272 KASSERT(bp->b_bufobj == bo,
4273 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
4279 * Get an empty, disassociated buffer of given size. The buffer is initially
4283 geteblk(int size, int flags)
4288 maxsize = (size + BKVAMASK) & ~BKVAMASK;
4289 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
4290 if ((flags & GB_NOWAIT_BD) &&
4291 (curthread->td_pflags & TDP_BUFNEED) != 0)
4295 bufspace_release(bufdomain(bp), maxsize);
4296 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
4301 * Truncate the backing store for a non-vmio buffer.
4304 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
4307 if (bp->b_flags & B_MALLOC) {
4309 * malloced buffers are not shrunk
4311 if (newbsize == 0) {
4312 bufmallocadjust(bp, 0);
4313 free(bp->b_data, M_BIOBUF);
4314 bp->b_data = bp->b_kvabase;
4315 bp->b_flags &= ~B_MALLOC;
4319 vm_hold_free_pages(bp, newbsize);
4320 bufspace_adjust(bp, newbsize);
4324 * Extend the backing for a non-VMIO buffer.
4327 vfs_nonvmio_extend(struct buf *bp, int newbsize)
4333 * We only use malloced memory on the first allocation.
4334 * and revert to page-allocated memory when the buffer
4337 * There is a potential smp race here that could lead
4338 * to bufmallocspace slightly passing the max. It
4339 * is probably extremely rare and not worth worrying
4342 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
4343 bufmallocspace < maxbufmallocspace) {
4344 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
4345 bp->b_flags |= B_MALLOC;
4346 bufmallocadjust(bp, newbsize);
4351 * If the buffer is growing on its other-than-first
4352 * allocation then we revert to the page-allocation
4357 if (bp->b_flags & B_MALLOC) {
4358 origbuf = bp->b_data;
4359 origbufsize = bp->b_bufsize;
4360 bp->b_data = bp->b_kvabase;
4361 bufmallocadjust(bp, 0);
4362 bp->b_flags &= ~B_MALLOC;
4363 newbsize = round_page(newbsize);
4365 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
4366 (vm_offset_t) bp->b_data + newbsize);
4367 if (origbuf != NULL) {
4368 bcopy(origbuf, bp->b_data, origbufsize);
4369 free(origbuf, M_BIOBUF);
4371 bufspace_adjust(bp, newbsize);
4375 * This code constitutes the buffer memory from either anonymous system
4376 * memory (in the case of non-VMIO operations) or from an associated
4377 * VM object (in the case of VMIO operations). This code is able to
4378 * resize a buffer up or down.
4380 * Note that this code is tricky, and has many complications to resolve
4381 * deadlock or inconsistent data situations. Tread lightly!!!
4382 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
4383 * the caller. Calling this code willy nilly can result in the loss of data.
4385 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
4386 * B_CACHE for the non-VMIO case.
4389 allocbuf(struct buf *bp, int size)
4393 if (bp->b_bcount == size)
4396 KASSERT(bp->b_kvasize == 0 || bp->b_kvasize >= size,
4397 ("allocbuf: buffer too small %p %#x %#x",
4398 bp, bp->b_kvasize, size));
4400 newbsize = roundup2(size, DEV_BSIZE);
4401 if ((bp->b_flags & B_VMIO) == 0) {
4402 if ((bp->b_flags & B_MALLOC) == 0)
4403 newbsize = round_page(newbsize);
4405 * Just get anonymous memory from the kernel. Don't
4406 * mess with B_CACHE.
4408 if (newbsize < bp->b_bufsize)
4409 vfs_nonvmio_truncate(bp, newbsize);
4410 else if (newbsize > bp->b_bufsize)
4411 vfs_nonvmio_extend(bp, newbsize);
4415 desiredpages = size == 0 ? 0 :
4416 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
4418 KASSERT((bp->b_flags & B_MALLOC) == 0,
4419 ("allocbuf: VMIO buffer can't be malloced %p", bp));
4422 * Set B_CACHE initially if buffer is 0 length or will become
4425 if (size == 0 || bp->b_bufsize == 0)
4426 bp->b_flags |= B_CACHE;
4428 if (newbsize < bp->b_bufsize)
4429 vfs_vmio_truncate(bp, desiredpages);
4430 /* XXX This looks as if it should be newbsize > b_bufsize */
4431 else if (size > bp->b_bcount)
4432 vfs_vmio_extend(bp, desiredpages, size);
4433 bufspace_adjust(bp, newbsize);
4435 bp->b_bcount = size; /* requested buffer size. */
4439 extern int inflight_transient_maps;
4441 static struct bio_queue nondump_bios;
4444 biodone(struct bio *bp)
4447 void (*done)(struct bio *);
4448 vm_offset_t start, end;
4450 biotrack(bp, __func__);
4453 * Avoid completing I/O when dumping after a panic since that may
4454 * result in a deadlock in the filesystem or pager code. Note that
4455 * this doesn't affect dumps that were started manually since we aim
4456 * to keep the system usable after it has been resumed.
4458 if (__predict_false(dumping && SCHEDULER_STOPPED())) {
4459 TAILQ_INSERT_HEAD(&nondump_bios, bp, bio_queue);
4462 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
4463 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
4464 bp->bio_flags |= BIO_UNMAPPED;
4465 start = trunc_page((vm_offset_t)bp->bio_data);
4466 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
4467 bp->bio_data = unmapped_buf;
4468 pmap_qremove(start, atop(end - start));
4469 vmem_free(transient_arena, start, end - start);
4470 atomic_add_int(&inflight_transient_maps, -1);
4472 done = bp->bio_done;
4474 * The check for done == biodone is to allow biodone to be
4475 * used as a bio_done routine.
4477 if (done == NULL || done == biodone) {
4478 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4480 bp->bio_flags |= BIO_DONE;
4488 * Wait for a BIO to finish.
4491 biowait(struct bio *bp, const char *wmesg)
4495 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4497 while ((bp->bio_flags & BIO_DONE) == 0)
4498 msleep(bp, mtxp, PRIBIO, wmesg, 0);
4500 if (bp->bio_error != 0)
4501 return (bp->bio_error);
4502 if (!(bp->bio_flags & BIO_ERROR))
4508 biofinish(struct bio *bp, struct devstat *stat, int error)
4512 bp->bio_error = error;
4513 bp->bio_flags |= BIO_ERROR;
4516 devstat_end_transaction_bio(stat, bp);
4520 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4522 biotrack_buf(struct bio *bp, const char *location)
4525 buf_track(bp->bio_track_bp, location);
4532 * Wait for buffer I/O completion, returning error status. The buffer
4533 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
4534 * error and cleared.
4537 bufwait(struct buf *bp)
4539 if (bp->b_iocmd == BIO_READ)
4540 bwait(bp, PRIBIO, "biord");
4542 bwait(bp, PRIBIO, "biowr");
4543 if (bp->b_flags & B_EINTR) {
4544 bp->b_flags &= ~B_EINTR;
4547 if (bp->b_ioflags & BIO_ERROR) {
4548 return (bp->b_error ? bp->b_error : EIO);
4557 * Finish I/O on a buffer, optionally calling a completion function.
4558 * This is usually called from an interrupt so process blocking is
4561 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4562 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
4563 * assuming B_INVAL is clear.
4565 * For the VMIO case, we set B_CACHE if the op was a read and no
4566 * read error occurred, or if the op was a write. B_CACHE is never
4567 * set if the buffer is invalid or otherwise uncacheable.
4569 * bufdone does not mess with B_INVAL, allowing the I/O routine or the
4570 * initiator to leave B_INVAL set to brelse the buffer out of existence
4571 * in the biodone routine.
4574 bufdone(struct buf *bp)
4576 struct bufobj *dropobj;
4577 void (*biodone)(struct buf *);
4579 buf_track(bp, __func__);
4580 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4583 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4585 runningbufwakeup(bp);
4586 if (bp->b_iocmd == BIO_WRITE)
4587 dropobj = bp->b_bufobj;
4588 /* call optional completion function if requested */
4589 if (bp->b_iodone != NULL) {
4590 biodone = bp->b_iodone;
4591 bp->b_iodone = NULL;
4594 bufobj_wdrop(dropobj);
4597 if (bp->b_flags & B_VMIO) {
4599 * Set B_CACHE if the op was a normal read and no error
4600 * occurred. B_CACHE is set for writes in the b*write()
4603 if (bp->b_iocmd == BIO_READ &&
4604 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4605 !(bp->b_ioflags & BIO_ERROR))
4606 bp->b_flags |= B_CACHE;
4607 vfs_vmio_iodone(bp);
4609 if (!LIST_EMPTY(&bp->b_dep))
4611 if ((bp->b_flags & B_CKHASH) != 0) {
4612 KASSERT(bp->b_iocmd == BIO_READ,
4613 ("bufdone: b_iocmd %d not BIO_READ", bp->b_iocmd));
4614 KASSERT(buf_mapped(bp), ("bufdone: bp %p not mapped", bp));
4615 (*bp->b_ckhashcalc)(bp);
4618 * For asynchronous completions, release the buffer now. The brelse
4619 * will do a wakeup there if necessary - so no need to do a wakeup
4620 * here in the async case. The sync case always needs to do a wakeup.
4622 if (bp->b_flags & B_ASYNC) {
4623 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4624 (bp->b_ioflags & BIO_ERROR))
4631 bufobj_wdrop(dropobj);
4635 * This routine is called in lieu of iodone in the case of
4636 * incomplete I/O. This keeps the busy status for pages
4640 vfs_unbusy_pages(struct buf *bp)
4646 runningbufwakeup(bp);
4647 if (!(bp->b_flags & B_VMIO))
4650 obj = bp->b_bufobj->bo_object;
4651 for (i = 0; i < bp->b_npages; i++) {
4653 if (m == bogus_page) {
4654 m = vm_page_relookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4656 panic("vfs_unbusy_pages: page missing\n");
4658 if (buf_mapped(bp)) {
4659 BUF_CHECK_MAPPED(bp);
4660 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4661 bp->b_pages, bp->b_npages);
4663 BUF_CHECK_UNMAPPED(bp);
4667 vm_object_pip_wakeupn(obj, bp->b_npages);
4671 * vfs_page_set_valid:
4673 * Set the valid bits in a page based on the supplied offset. The
4674 * range is restricted to the buffer's size.
4676 * This routine is typically called after a read completes.
4679 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4684 * Compute the end offset, eoff, such that [off, eoff) does not span a
4685 * page boundary and eoff is not greater than the end of the buffer.
4686 * The end of the buffer, in this case, is our file EOF, not the
4687 * allocation size of the buffer.
4689 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4690 if (eoff > bp->b_offset + bp->b_bcount)
4691 eoff = bp->b_offset + bp->b_bcount;
4694 * Set valid range. This is typically the entire buffer and thus the
4698 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4702 * vfs_page_set_validclean:
4704 * Set the valid bits and clear the dirty bits in a page based on the
4705 * supplied offset. The range is restricted to the buffer's size.
4708 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4710 vm_ooffset_t soff, eoff;
4713 * Start and end offsets in buffer. eoff - soff may not cross a
4714 * page boundary or cross the end of the buffer. The end of the
4715 * buffer, in this case, is our file EOF, not the allocation size
4719 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4720 if (eoff > bp->b_offset + bp->b_bcount)
4721 eoff = bp->b_offset + bp->b_bcount;
4724 * Set valid range. This is typically the entire buffer and thus the
4728 vm_page_set_validclean(
4730 (vm_offset_t) (soff & PAGE_MASK),
4731 (vm_offset_t) (eoff - soff)
4737 * Acquire a shared busy on all pages in the buf.
4740 vfs_busy_pages_acquire(struct buf *bp)
4744 for (i = 0; i < bp->b_npages; i++)
4745 vm_page_busy_acquire(bp->b_pages[i], VM_ALLOC_SBUSY);
4749 vfs_busy_pages_release(struct buf *bp)
4753 for (i = 0; i < bp->b_npages; i++)
4754 vm_page_sunbusy(bp->b_pages[i]);
4758 * This routine is called before a device strategy routine.
4759 * It is used to tell the VM system that paging I/O is in
4760 * progress, and treat the pages associated with the buffer
4761 * almost as being exclusive busy. Also the object paging_in_progress
4762 * flag is handled to make sure that the object doesn't become
4765 * Since I/O has not been initiated yet, certain buffer flags
4766 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4767 * and should be ignored.
4770 vfs_busy_pages(struct buf *bp, int clear_modify)
4778 if (!(bp->b_flags & B_VMIO))
4781 obj = bp->b_bufobj->bo_object;
4782 foff = bp->b_offset;
4783 KASSERT(bp->b_offset != NOOFFSET,
4784 ("vfs_busy_pages: no buffer offset"));
4785 if ((bp->b_flags & B_CLUSTER) == 0) {
4786 vm_object_pip_add(obj, bp->b_npages);
4787 vfs_busy_pages_acquire(bp);
4789 if (bp->b_bufsize != 0)
4790 vfs_setdirty_range(bp);
4792 for (i = 0; i < bp->b_npages; i++) {
4794 vm_page_assert_sbusied(m);
4797 * When readying a buffer for a read ( i.e
4798 * clear_modify == 0 ), it is important to do
4799 * bogus_page replacement for valid pages in
4800 * partially instantiated buffers. Partially
4801 * instantiated buffers can, in turn, occur when
4802 * reconstituting a buffer from its VM backing store
4803 * base. We only have to do this if B_CACHE is
4804 * clear ( which causes the I/O to occur in the
4805 * first place ). The replacement prevents the read
4806 * I/O from overwriting potentially dirty VM-backed
4807 * pages. XXX bogus page replacement is, uh, bogus.
4808 * It may not work properly with small-block devices.
4809 * We need to find a better way.
4812 pmap_remove_write(m);
4813 vfs_page_set_validclean(bp, foff, m);
4814 } else if (vm_page_all_valid(m) &&
4815 (bp->b_flags & B_CACHE) == 0) {
4816 bp->b_pages[i] = bogus_page;
4819 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4821 if (bogus && buf_mapped(bp)) {
4822 BUF_CHECK_MAPPED(bp);
4823 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4824 bp->b_pages, bp->b_npages);
4829 * vfs_bio_set_valid:
4831 * Set the range within the buffer to valid. The range is
4832 * relative to the beginning of the buffer, b_offset. Note that
4833 * b_offset itself may be offset from the beginning of the first
4837 vfs_bio_set_valid(struct buf *bp, int base, int size)
4842 if (!(bp->b_flags & B_VMIO))
4846 * Fixup base to be relative to beginning of first page.
4847 * Set initial n to be the maximum number of bytes in the
4848 * first page that can be validated.
4850 base += (bp->b_offset & PAGE_MASK);
4851 n = PAGE_SIZE - (base & PAGE_MASK);
4854 * Busy may not be strictly necessary here because the pages are
4855 * unlikely to be fully valid and the vnode lock will synchronize
4856 * their access via getpages. It is grabbed for consistency with
4857 * other page validation.
4859 vfs_busy_pages_acquire(bp);
4860 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4864 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4869 vfs_busy_pages_release(bp);
4875 * If the specified buffer is a non-VMIO buffer, clear the entire
4876 * buffer. If the specified buffer is a VMIO buffer, clear and
4877 * validate only the previously invalid portions of the buffer.
4878 * This routine essentially fakes an I/O, so we need to clear
4879 * BIO_ERROR and B_INVAL.
4881 * Note that while we only theoretically need to clear through b_bcount,
4882 * we go ahead and clear through b_bufsize.
4885 vfs_bio_clrbuf(struct buf *bp)
4887 int i, j, sa, ea, slide, zbits;
4888 vm_page_bits_t mask;
4890 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4894 bp->b_flags &= ~B_INVAL;
4895 bp->b_ioflags &= ~BIO_ERROR;
4896 vfs_busy_pages_acquire(bp);
4897 sa = bp->b_offset & PAGE_MASK;
4899 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4900 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4901 ea = slide & PAGE_MASK;
4904 if (bp->b_pages[i] == bogus_page)
4907 zbits = (sizeof(vm_page_bits_t) * NBBY) -
4908 (ea - sa) / DEV_BSIZE;
4909 mask = (VM_PAGE_BITS_ALL >> zbits) << j;
4910 if ((bp->b_pages[i]->valid & mask) == mask)
4912 if ((bp->b_pages[i]->valid & mask) == 0)
4913 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4915 for (; sa < ea; sa += DEV_BSIZE, j++) {
4916 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4917 pmap_zero_page_area(bp->b_pages[i],
4922 vm_page_set_valid_range(bp->b_pages[i], j * DEV_BSIZE,
4923 roundup2(ea - sa, DEV_BSIZE));
4925 vfs_busy_pages_release(bp);
4930 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4935 if (buf_mapped(bp)) {
4936 BUF_CHECK_MAPPED(bp);
4937 bzero(bp->b_data + base, size);
4939 BUF_CHECK_UNMAPPED(bp);
4940 n = PAGE_SIZE - (base & PAGE_MASK);
4941 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4945 pmap_zero_page_area(m, base & PAGE_MASK, n);
4954 * Update buffer flags based on I/O request parameters, optionally releasing the
4955 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM,
4956 * where they may be placed on a page queue (VMIO) or freed immediately (direct
4957 * I/O). Otherwise the buffer is released to the cache.
4960 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4963 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4964 ("buf %p non-VMIO noreuse", bp));
4966 if ((ioflag & IO_DIRECT) != 0)
4967 bp->b_flags |= B_DIRECT;
4968 if ((ioflag & IO_EXT) != 0)
4969 bp->b_xflags |= BX_ALTDATA;
4970 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4971 bp->b_flags |= B_RELBUF;
4972 if ((ioflag & IO_NOREUSE) != 0)
4973 bp->b_flags |= B_NOREUSE;
4981 vfs_bio_brelse(struct buf *bp, int ioflag)
4984 b_io_dismiss(bp, ioflag, true);
4988 vfs_bio_set_flags(struct buf *bp, int ioflag)
4991 b_io_dismiss(bp, ioflag, false);
4995 * vm_hold_load_pages and vm_hold_free_pages get pages into
4996 * a buffers address space. The pages are anonymous and are
4997 * not associated with a file object.
5000 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
5006 BUF_CHECK_MAPPED(bp);
5008 to = round_page(to);
5009 from = round_page(from);
5010 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
5011 MPASS((bp->b_flags & B_MAXPHYS) == 0);
5012 KASSERT(to - from <= maxbcachebuf,
5013 ("vm_hold_load_pages too large %p %#jx %#jx %u",
5014 bp, (uintmax_t)from, (uintmax_t)to, maxbcachebuf));
5016 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
5018 * note: must allocate system pages since blocking here
5019 * could interfere with paging I/O, no matter which
5022 p = vm_page_alloc_noobj(VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
5023 VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) | VM_ALLOC_WAITOK);
5024 pmap_qenter(pg, &p, 1);
5025 bp->b_pages[index] = p;
5027 bp->b_npages = index;
5030 /* Return pages associated with this buf to the vm system */
5032 vm_hold_free_pages(struct buf *bp, int newbsize)
5036 int index, newnpages;
5038 BUF_CHECK_MAPPED(bp);
5040 from = round_page((vm_offset_t)bp->b_data + newbsize);
5041 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
5042 if (bp->b_npages > newnpages)
5043 pmap_qremove(from, bp->b_npages - newnpages);
5044 for (index = newnpages; index < bp->b_npages; index++) {
5045 p = bp->b_pages[index];
5046 bp->b_pages[index] = NULL;
5047 vm_page_unwire_noq(p);
5050 bp->b_npages = newnpages;
5054 * Map an IO request into kernel virtual address space.
5056 * All requests are (re)mapped into kernel VA space.
5057 * Notice that we use b_bufsize for the size of the buffer
5058 * to be mapped. b_bcount might be modified by the driver.
5060 * Note that even if the caller determines that the address space should
5061 * be valid, a race or a smaller-file mapped into a larger space may
5062 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
5063 * check the return value.
5065 * This function only works with pager buffers.
5068 vmapbuf(struct buf *bp, void *uaddr, size_t len, int mapbuf)
5073 MPASS((bp->b_flags & B_MAXPHYS) != 0);
5074 prot = VM_PROT_READ;
5075 if (bp->b_iocmd == BIO_READ)
5076 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
5077 pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
5078 (vm_offset_t)uaddr, len, prot, bp->b_pages, PBUF_PAGES);
5081 bp->b_bufsize = len;
5082 bp->b_npages = pidx;
5083 bp->b_offset = ((vm_offset_t)uaddr) & PAGE_MASK;
5084 if (mapbuf || !unmapped_buf_allowed) {
5085 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
5086 bp->b_data = bp->b_kvabase + bp->b_offset;
5088 bp->b_data = unmapped_buf;
5093 * Free the io map PTEs associated with this IO operation.
5094 * We also invalidate the TLB entries and restore the original b_addr.
5096 * This function only works with pager buffers.
5099 vunmapbuf(struct buf *bp)
5103 npages = bp->b_npages;
5105 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
5106 vm_page_unhold_pages(bp->b_pages, npages);
5108 bp->b_data = unmapped_buf;
5112 bdone(struct buf *bp)
5116 mtxp = mtx_pool_find(mtxpool_sleep, bp);
5118 bp->b_flags |= B_DONE;
5124 bwait(struct buf *bp, u_char pri, const char *wchan)
5128 mtxp = mtx_pool_find(mtxpool_sleep, bp);
5130 while ((bp->b_flags & B_DONE) == 0)
5131 msleep(bp, mtxp, pri, wchan, 0);
5136 bufsync(struct bufobj *bo, int waitfor)
5139 return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
5143 bufstrategy(struct bufobj *bo, struct buf *bp)
5149 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
5150 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
5151 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
5152 i = VOP_STRATEGY(vp, bp);
5153 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
5157 * Initialize a struct bufobj before use. Memory is assumed zero filled.
5160 bufobj_init(struct bufobj *bo, void *private)
5162 static volatile int bufobj_cleanq;
5165 atomic_fetchadd_int(&bufobj_cleanq, 1) % buf_domains;
5166 rw_init(BO_LOCKPTR(bo), "bufobj interlock");
5167 bo->bo_private = private;
5168 TAILQ_INIT(&bo->bo_clean.bv_hd);
5169 pctrie_init(&bo->bo_clean.bv_root);
5170 TAILQ_INIT(&bo->bo_dirty.bv_hd);
5171 pctrie_init(&bo->bo_dirty.bv_root);
5175 bufobj_wrefl(struct bufobj *bo)
5178 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5179 ASSERT_BO_WLOCKED(bo);
5184 bufobj_wref(struct bufobj *bo)
5187 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5194 bufobj_wdrop(struct bufobj *bo)
5197 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
5199 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
5200 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
5201 bo->bo_flag &= ~BO_WWAIT;
5202 wakeup(&bo->bo_numoutput);
5208 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
5212 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
5213 ASSERT_BO_WLOCKED(bo);
5215 while (bo->bo_numoutput) {
5216 bo->bo_flag |= BO_WWAIT;
5217 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
5218 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
5226 * Set bio_data or bio_ma for struct bio from the struct buf.
5229 bdata2bio(struct buf *bp, struct bio *bip)
5232 if (!buf_mapped(bp)) {
5233 KASSERT(unmapped_buf_allowed, ("unmapped"));
5234 bip->bio_ma = bp->b_pages;
5235 bip->bio_ma_n = bp->b_npages;
5236 bip->bio_data = unmapped_buf;
5237 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
5238 bip->bio_flags |= BIO_UNMAPPED;
5239 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
5240 PAGE_SIZE == bp->b_npages,
5241 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
5242 (long long)bip->bio_length, bip->bio_ma_n));
5244 bip->bio_data = bp->b_data;
5250 memdesc_bio(struct bio *bio)
5252 if ((bio->bio_flags & BIO_VLIST) != 0)
5253 return (memdesc_vlist((struct bus_dma_segment *)bio->bio_data,
5256 if ((bio->bio_flags & BIO_UNMAPPED) != 0)
5257 return (memdesc_vmpages(bio->bio_ma, bio->bio_bcount,
5258 bio->bio_ma_offset));
5260 return (memdesc_vaddr(bio->bio_data, bio->bio_bcount));
5263 static int buf_pager_relbuf;
5264 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
5265 &buf_pager_relbuf, 0,
5266 "Make buffer pager release buffers after reading");
5269 * The buffer pager. It uses buffer reads to validate pages.
5271 * In contrast to the generic local pager from vm/vnode_pager.c, this
5272 * pager correctly and easily handles volumes where the underlying
5273 * device block size is greater than the machine page size. The
5274 * buffer cache transparently extends the requested page run to be
5275 * aligned at the block boundary, and does the necessary bogus page
5276 * replacements in the addends to avoid obliterating already valid
5279 * The only non-trivial issue is that the exclusive busy state for
5280 * pages, which is assumed by the vm_pager_getpages() interface, is
5281 * incompatible with the VMIO buffer cache's desire to share-busy the
5282 * pages. This function performs a trivial downgrade of the pages'
5283 * state before reading buffers, and a less trivial upgrade from the
5284 * shared-busy to excl-busy state after the read.
5287 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
5288 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
5289 vbg_get_blksize_t get_blksize)
5296 vm_ooffset_t la, lb, poff, poffe;
5298 int br_flags, error, i, pgsin, pgsin_a, pgsin_b;
5301 object = vp->v_object;
5304 la = IDX_TO_OFF(ma[count - 1]->pindex);
5305 if (la >= object->un_pager.vnp.vnp_size)
5306 return (VM_PAGER_BAD);
5309 * Change the meaning of la from where the last requested page starts
5310 * to where it ends, because that's the end of the requested region
5311 * and the start of the potential read-ahead region.
5314 lpart = la > object->un_pager.vnp.vnp_size;
5315 error = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)),
5318 return (VM_PAGER_ERROR);
5321 * Calculate read-ahead, behind and total pages.
5324 lb = IDX_TO_OFF(ma[0]->pindex);
5325 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
5327 if (rbehind != NULL)
5329 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
5330 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
5331 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
5336 VM_CNT_INC(v_vnodein);
5337 VM_CNT_ADD(v_vnodepgsin, pgsin);
5339 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
5340 != 0) ? GB_UNMAPPED : 0;
5342 for (i = 0; i < count; i++) {
5343 if (ma[i] != bogus_page)
5344 vm_page_busy_downgrade(ma[i]);
5348 for (i = 0; i < count; i++) {
5350 if (m == bogus_page)
5354 * Pages are shared busy and the object lock is not
5355 * owned, which together allow for the pages'
5356 * invalidation. The racy test for validity avoids
5357 * useless creation of the buffer for the most typical
5358 * case when invalidation is not used in redo or for
5359 * parallel read. The shared->excl upgrade loop at
5360 * the end of the function catches the race in a
5361 * reliable way (protected by the object lock).
5363 if (vm_page_all_valid(m))
5366 poff = IDX_TO_OFF(m->pindex);
5367 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
5368 for (; poff < poffe; poff += bsize) {
5369 lbn = get_lblkno(vp, poff);
5374 error = get_blksize(vp, lbn, &bsize);
5376 error = bread_gb(vp, lbn, bsize,
5377 curthread->td_ucred, br_flags, &bp);
5380 if (bp->b_rcred == curthread->td_ucred) {
5381 crfree(bp->b_rcred);
5382 bp->b_rcred = NOCRED;
5384 if (LIST_EMPTY(&bp->b_dep)) {
5386 * Invalidation clears m->valid, but
5387 * may leave B_CACHE flag if the
5388 * buffer existed at the invalidation
5389 * time. In this case, recycle the
5390 * buffer to do real read on next
5391 * bread() after redo.
5393 * Otherwise B_RELBUF is not strictly
5394 * necessary, enable to reduce buf
5397 if (buf_pager_relbuf ||
5398 !vm_page_all_valid(m))
5399 bp->b_flags |= B_RELBUF;
5401 bp->b_flags &= ~B_NOCACHE;
5407 KASSERT(1 /* racy, enable for debugging */ ||
5408 vm_page_all_valid(m) || i == count - 1,
5409 ("buf %d %p invalid", i, m));
5410 if (i == count - 1 && lpart) {
5411 if (!vm_page_none_valid(m) &&
5412 !vm_page_all_valid(m))
5413 vm_page_zero_invalid(m, TRUE);
5420 for (i = 0; i < count; i++) {
5421 if (ma[i] == bogus_page)
5423 if (vm_page_busy_tryupgrade(ma[i]) == 0) {
5424 vm_page_sunbusy(ma[i]);
5425 ma[i] = vm_page_grab_unlocked(object, ma[i]->pindex,
5430 * Since the pages were only sbusy while neither the
5431 * buffer nor the object lock was held by us, or
5432 * reallocated while vm_page_grab() slept for busy
5433 * relinguish, they could have been invalidated.
5434 * Recheck the valid bits and re-read as needed.
5436 * Note that the last page is made fully valid in the
5437 * read loop, and partial validity for the page at
5438 * index count - 1 could mean that the page was
5439 * invalidated or removed, so we must restart for
5442 if (!vm_page_all_valid(ma[i]))
5445 if (redo && error == 0)
5447 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
5450 #include "opt_ddb.h"
5452 #include <ddb/ddb.h>
5454 /* DDB command to show buffer data */
5455 DB_SHOW_COMMAND(buffer, db_show_buffer)
5458 struct buf *bp = (struct buf *)addr;
5459 #ifdef FULL_BUF_TRACKING
5464 db_printf("usage: show buffer <addr>\n");
5468 db_printf("buf at %p\n", bp);
5469 db_printf("b_flags = 0x%b, b_xflags=0x%b\n",
5470 (u_int)bp->b_flags, PRINT_BUF_FLAGS,
5471 (u_int)bp->b_xflags, PRINT_BUF_XFLAGS);
5472 db_printf("b_vflags=0x%b b_ioflags0x%b\n",
5473 (u_int)bp->b_vflags, PRINT_BUF_VFLAGS,
5474 (u_int)bp->b_ioflags, PRINT_BIO_FLAGS);
5476 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
5477 "b_bufobj = (%p), b_data = %p\n, b_blkno = %jd, b_lblkno = %jd, "
5478 "b_vp = %p, b_dep = %p\n",
5479 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
5480 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
5481 (intmax_t)bp->b_lblkno, bp->b_vp, bp->b_dep.lh_first);
5482 db_printf("b_kvabase = %p, b_kvasize = %d\n",
5483 bp->b_kvabase, bp->b_kvasize);
5486 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
5487 for (i = 0; i < bp->b_npages; i++) {
5491 db_printf("(%p, 0x%lx, 0x%lx)", m->object,
5493 (u_long)VM_PAGE_TO_PHYS(m));
5495 db_printf("( ??? )");
5496 if ((i + 1) < bp->b_npages)
5501 BUF_LOCKPRINTINFO(bp);
5502 #if defined(FULL_BUF_TRACKING)
5503 db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
5505 i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
5506 for (j = 1; j <= BUF_TRACKING_SIZE; j++) {
5507 if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL)
5509 db_printf(" %2u: %s\n", j,
5510 bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
5512 #elif defined(BUF_TRACKING)
5513 db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
5518 DB_SHOW_COMMAND_FLAGS(bufqueues, bufqueues, DB_CMD_MEMSAFE)
5520 struct bufdomain *bd;
5525 db_printf("bqempty: %d\n", bqempty.bq_len);
5527 for (i = 0; i < buf_domains; i++) {
5529 db_printf("Buf domain %d\n", i);
5530 db_printf("\tfreebufs\t%d\n", bd->bd_freebuffers);
5531 db_printf("\tlofreebufs\t%d\n", bd->bd_lofreebuffers);
5532 db_printf("\thifreebufs\t%d\n", bd->bd_hifreebuffers);
5534 db_printf("\tbufspace\t%ld\n", bd->bd_bufspace);
5535 db_printf("\tmaxbufspace\t%ld\n", bd->bd_maxbufspace);
5536 db_printf("\thibufspace\t%ld\n", bd->bd_hibufspace);
5537 db_printf("\tlobufspace\t%ld\n", bd->bd_lobufspace);
5538 db_printf("\tbufspacethresh\t%ld\n", bd->bd_bufspacethresh);
5540 db_printf("\tnumdirtybuffers\t%d\n", bd->bd_numdirtybuffers);
5541 db_printf("\tlodirtybuffers\t%d\n", bd->bd_lodirtybuffers);
5542 db_printf("\thidirtybuffers\t%d\n", bd->bd_hidirtybuffers);
5543 db_printf("\tdirtybufthresh\t%d\n", bd->bd_dirtybufthresh);
5546 TAILQ_FOREACH(bp, &bd->bd_cleanq->bq_queue, b_freelist)
5547 total += bp->b_bufsize;
5548 db_printf("\tcleanq count\t%d (%ld)\n",
5549 bd->bd_cleanq->bq_len, total);
5551 TAILQ_FOREACH(bp, &bd->bd_dirtyq.bq_queue, b_freelist)
5552 total += bp->b_bufsize;
5553 db_printf("\tdirtyq count\t%d (%ld)\n",
5554 bd->bd_dirtyq.bq_len, total);
5555 db_printf("\twakeup\t\t%d\n", bd->bd_wanted);
5556 db_printf("\tlim\t\t%d\n", bd->bd_lim);
5557 db_printf("\tCPU ");
5558 for (j = 0; j <= mp_maxid; j++)
5559 db_printf("%d, ", bd->bd_subq[j].bq_len);
5563 for (j = 0; j < nbuf; j++) {
5565 if (bp->b_domain == i && BUF_ISLOCKED(bp)) {
5567 total += bp->b_bufsize;
5570 db_printf("\tLocked buffers: %d space %ld\n", cnt, total);
5573 for (j = 0; j < nbuf; j++) {
5575 if (bp->b_domain == i) {
5577 total += bp->b_bufsize;
5580 db_printf("\tTotal buffers: %d space %ld\n", cnt, total);
5584 DB_SHOW_COMMAND_FLAGS(lockedbufs, lockedbufs, DB_CMD_MEMSAFE)
5589 for (i = 0; i < nbuf; i++) {
5591 if (BUF_ISLOCKED(bp)) {
5592 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5600 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
5606 db_printf("usage: show vnodebufs <addr>\n");
5609 vp = (struct vnode *)addr;
5610 db_printf("Clean buffers:\n");
5611 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
5612 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5615 db_printf("Dirty buffers:\n");
5616 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5617 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5622 DB_COMMAND_FLAGS(countfreebufs, db_coundfreebufs, DB_CMD_MEMSAFE)
5625 int i, used = 0, nfree = 0;
5628 db_printf("usage: countfreebufs\n");
5632 for (i = 0; i < nbuf; i++) {
5634 if (bp->b_qindex == QUEUE_EMPTY)
5640 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5642 db_printf("numfreebuffers is %d\n", numfreebuffers);