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/cdefs.h>
48 __FBSDID("$FreeBSD$");
50 #include <sys/param.h>
51 #include <sys/systm.h>
54 #include <sys/bitset.h>
55 #include <sys/boottrace.h>
58 #include <sys/counter.h>
59 #include <sys/devicestat.h>
60 #include <sys/eventhandler.h>
63 #include <sys/limits.h>
65 #include <sys/malloc.h>
66 #include <sys/memdesc.h>
67 #include <sys/mount.h>
68 #include <sys/mutex.h>
69 #include <sys/kernel.h>
70 #include <sys/kthread.h>
71 #include <sys/pctrie.h>
73 #include <sys/racct.h>
74 #include <sys/refcount.h>
75 #include <sys/resourcevar.h>
76 #include <sys/rwlock.h>
77 #include <sys/sched.h>
79 #include <sys/sysctl.h>
80 #include <sys/syscallsubr.h>
82 #include <sys/vmmeter.h>
83 #include <sys/vnode.h>
84 #include <sys/watchdog.h>
85 #include <geom/geom.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_kern.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_page.h>
91 #include <vm/vm_pageout.h>
92 #include <vm/vm_pager.h>
93 #include <vm/vm_extern.h>
94 #include <vm/vm_map.h>
95 #include <vm/swap_pager.h>
97 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
99 struct bio_ops bioops; /* I/O operation notification */
101 struct buf_ops buf_ops_bio = {
102 .bop_name = "buf_ops_bio",
103 .bop_write = bufwrite,
104 .bop_strategy = bufstrategy,
106 .bop_bdflush = bufbdflush,
110 struct mtx_padalign bq_lock;
111 TAILQ_HEAD(, buf) bq_queue;
113 uint16_t bq_subqueue;
115 } __aligned(CACHE_LINE_SIZE);
117 #define BQ_LOCKPTR(bq) (&(bq)->bq_lock)
118 #define BQ_LOCK(bq) mtx_lock(BQ_LOCKPTR((bq)))
119 #define BQ_UNLOCK(bq) mtx_unlock(BQ_LOCKPTR((bq)))
120 #define BQ_ASSERT_LOCKED(bq) mtx_assert(BQ_LOCKPTR((bq)), MA_OWNED)
123 struct bufqueue *bd_subq;
124 struct bufqueue bd_dirtyq;
125 struct bufqueue *bd_cleanq;
126 struct mtx_padalign bd_run_lock;
131 long bd_bufspacethresh;
132 int bd_hifreebuffers;
133 int bd_lofreebuffers;
134 int bd_hidirtybuffers;
135 int bd_lodirtybuffers;
136 int bd_dirtybufthresh;
141 int __aligned(CACHE_LINE_SIZE) bd_numdirtybuffers;
142 int __aligned(CACHE_LINE_SIZE) bd_running;
143 long __aligned(CACHE_LINE_SIZE) bd_bufspace;
144 int __aligned(CACHE_LINE_SIZE) bd_freebuffers;
145 } __aligned(CACHE_LINE_SIZE);
147 #define BD_LOCKPTR(bd) (&(bd)->bd_cleanq->bq_lock)
148 #define BD_LOCK(bd) mtx_lock(BD_LOCKPTR((bd)))
149 #define BD_UNLOCK(bd) mtx_unlock(BD_LOCKPTR((bd)))
150 #define BD_ASSERT_LOCKED(bd) mtx_assert(BD_LOCKPTR((bd)), MA_OWNED)
151 #define BD_RUN_LOCKPTR(bd) (&(bd)->bd_run_lock)
152 #define BD_RUN_LOCK(bd) mtx_lock(BD_RUN_LOCKPTR((bd)))
153 #define BD_RUN_UNLOCK(bd) mtx_unlock(BD_RUN_LOCKPTR((bd)))
154 #define BD_DOMAIN(bd) (bd - bdomain)
156 static char *buf; /* buffer header pool */
160 return ((struct buf *)(buf + (sizeof(struct buf) +
161 sizeof(vm_page_t) * atop(maxbcachebuf)) * i));
164 caddr_t __read_mostly unmapped_buf;
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, CTLFLAG_RD,
326 &unmapped_buf_allowed, 0,
327 "Permit the use of the unmapped i/o");
328 int maxbcachebuf = MAXBCACHEBUF;
329 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0,
330 "Maximum size of a buffer cache block");
333 * This lock synchronizes access to bd_request.
335 static struct mtx_padalign __exclusive_cache_line bdlock;
338 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
339 * waitrunningbufspace().
341 static struct mtx_padalign __exclusive_cache_line rbreqlock;
344 * Lock that protects bdirtywait.
346 static struct mtx_padalign __exclusive_cache_line bdirtylock;
349 * bufdaemon shutdown request and sleep channel.
351 static bool bd_shutdown;
354 * Wakeup point for bufdaemon, as well as indicator of whether it is already
355 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
358 static int bd_request;
361 * Request for the buf daemon to write more buffers than is indicated by
362 * lodirtybuf. This may be necessary to push out excess dependencies or
363 * defragment the address space where a simple count of the number of dirty
364 * buffers is insufficient to characterize the demand for flushing them.
366 static int bd_speedupreq;
369 * Synchronization (sleep/wakeup) variable for active buffer space requests.
370 * Set when wait starts, cleared prior to wakeup().
371 * Used in runningbufwakeup() and waitrunningbufspace().
373 static int runningbufreq;
376 * Synchronization for bwillwrite() waiters.
378 static int bdirtywait;
381 * Definitions for the buffer free lists.
383 #define QUEUE_NONE 0 /* on no queue */
384 #define QUEUE_EMPTY 1 /* empty buffer headers */
385 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
386 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
387 #define QUEUE_SENTINEL 4 /* not an queue index, but mark for sentinel */
389 /* Maximum number of buffer domains. */
390 #define BUF_DOMAINS 8
392 struct bufdomainset bdlodirty; /* Domains > lodirty */
393 struct bufdomainset bdhidirty; /* Domains > hidirty */
395 /* Configured number of clean queues. */
396 static int __read_mostly buf_domains;
398 BITSET_DEFINE(bufdomainset, BUF_DOMAINS);
399 struct bufdomain __exclusive_cache_line bdomain[BUF_DOMAINS];
400 struct bufqueue __exclusive_cache_line bqempty;
403 * per-cpu empty buffer cache.
408 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
413 value = *(long *)arg1;
414 error = sysctl_handle_long(oidp, &value, 0, req);
415 if (error != 0 || req->newptr == NULL)
417 mtx_lock(&rbreqlock);
418 if (arg1 == &hirunningspace) {
419 if (value < lorunningspace)
422 hirunningspace = value;
424 KASSERT(arg1 == &lorunningspace,
425 ("%s: unknown arg1", __func__));
426 if (value > hirunningspace)
429 lorunningspace = value;
431 mtx_unlock(&rbreqlock);
436 sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS)
442 value = *(int *)arg1;
443 error = sysctl_handle_int(oidp, &value, 0, req);
444 if (error != 0 || req->newptr == NULL)
446 *(int *)arg1 = value;
447 for (i = 0; i < buf_domains; i++)
448 *(int *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
455 sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS)
461 value = *(long *)arg1;
462 error = sysctl_handle_long(oidp, &value, 0, req);
463 if (error != 0 || req->newptr == NULL)
465 *(long *)arg1 = value;
466 for (i = 0; i < buf_domains; i++)
467 *(long *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
473 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
474 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
476 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
483 for (i = 0; i < buf_domains; i++)
484 lvalue += bdomain[i].bd_bufspace;
485 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
486 return (sysctl_handle_long(oidp, &lvalue, 0, req));
487 if (lvalue > INT_MAX)
488 /* On overflow, still write out a long to trigger ENOMEM. */
489 return (sysctl_handle_long(oidp, &lvalue, 0, req));
491 return (sysctl_handle_int(oidp, &ivalue, 0, req));
495 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
501 for (i = 0; i < buf_domains; i++)
502 lvalue += bdomain[i].bd_bufspace;
503 return (sysctl_handle_long(oidp, &lvalue, 0, req));
508 sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS)
514 for (i = 0; i < buf_domains; i++)
515 value += bdomain[i].bd_numdirtybuffers;
516 return (sysctl_handle_int(oidp, &value, 0, req));
522 * Wakeup any bwillwrite() waiters.
527 mtx_lock(&bdirtylock);
532 mtx_unlock(&bdirtylock);
538 * Clear a domain from the appropriate bitsets when dirtybuffers
542 bd_clear(struct bufdomain *bd)
545 mtx_lock(&bdirtylock);
546 if (bd->bd_numdirtybuffers <= bd->bd_lodirtybuffers)
547 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
548 if (bd->bd_numdirtybuffers <= bd->bd_hidirtybuffers)
549 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
550 mtx_unlock(&bdirtylock);
556 * Set a domain in the appropriate bitsets when dirtybuffers
560 bd_set(struct bufdomain *bd)
563 mtx_lock(&bdirtylock);
564 if (bd->bd_numdirtybuffers > bd->bd_lodirtybuffers)
565 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
566 if (bd->bd_numdirtybuffers > bd->bd_hidirtybuffers)
567 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
568 mtx_unlock(&bdirtylock);
574 * Decrement the numdirtybuffers count by one and wakeup any
575 * threads blocked in bwillwrite().
578 bdirtysub(struct buf *bp)
580 struct bufdomain *bd;
584 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, -1);
585 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
587 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
594 * Increment the numdirtybuffers count by one and wakeup the buf
598 bdirtyadd(struct buf *bp)
600 struct bufdomain *bd;
604 * Only do the wakeup once as we cross the boundary. The
605 * buf daemon will keep running until the condition clears.
608 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, 1);
609 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
611 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
616 * bufspace_daemon_wakeup:
618 * Wakeup the daemons responsible for freeing clean bufs.
621 bufspace_daemon_wakeup(struct bufdomain *bd)
625 * avoid the lock if the daemon is running.
627 if (atomic_fetchadd_int(&bd->bd_running, 1) == 0) {
629 atomic_store_int(&bd->bd_running, 1);
630 wakeup(&bd->bd_running);
638 * Adjust the reported bufspace for a KVA managed buffer, possibly
639 * waking any waiters.
642 bufspace_adjust(struct buf *bp, int bufsize)
644 struct bufdomain *bd;
648 KASSERT((bp->b_flags & B_MALLOC) == 0,
649 ("bufspace_adjust: malloc buf %p", bp));
651 diff = bufsize - bp->b_bufsize;
653 atomic_subtract_long(&bd->bd_bufspace, -diff);
654 } else if (diff > 0) {
655 space = atomic_fetchadd_long(&bd->bd_bufspace, diff);
656 /* Wake up the daemon on the transition. */
657 if (space < bd->bd_bufspacethresh &&
658 space + diff >= bd->bd_bufspacethresh)
659 bufspace_daemon_wakeup(bd);
661 bp->b_bufsize = bufsize;
667 * Reserve bufspace before calling allocbuf(). metadata has a
668 * different space limit than data.
671 bufspace_reserve(struct bufdomain *bd, int size, bool metadata)
677 limit = bd->bd_maxbufspace;
679 limit = bd->bd_hibufspace;
680 space = atomic_fetchadd_long(&bd->bd_bufspace, size);
683 atomic_subtract_long(&bd->bd_bufspace, size);
687 /* Wake up the daemon on the transition. */
688 if (space < bd->bd_bufspacethresh && new >= bd->bd_bufspacethresh)
689 bufspace_daemon_wakeup(bd);
697 * Release reserved bufspace after bufspace_adjust() has consumed it.
700 bufspace_release(struct bufdomain *bd, int size)
703 atomic_subtract_long(&bd->bd_bufspace, size);
709 * Wait for bufspace, acting as the buf daemon if a locked vnode is
710 * supplied. bd_wanted must be set prior to polling for space. The
711 * operation must be re-tried on return.
714 bufspace_wait(struct bufdomain *bd, struct vnode *vp, int gbflags,
715 int slpflag, int slptimeo)
718 int error, fl, norunbuf;
720 if ((gbflags & GB_NOWAIT_BD) != 0)
725 while (bd->bd_wanted) {
726 if (vp != NULL && vp->v_type != VCHR &&
727 (td->td_pflags & TDP_BUFNEED) == 0) {
730 * getblk() is called with a vnode locked, and
731 * some majority of the dirty buffers may as
732 * well belong to the vnode. Flushing the
733 * buffers there would make a progress that
734 * cannot be achieved by the buf_daemon, that
735 * cannot lock the vnode.
737 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
738 (td->td_pflags & TDP_NORUNNINGBUF);
741 * Play bufdaemon. The getnewbuf() function
742 * may be called while the thread owns lock
743 * for another dirty buffer for the same
744 * vnode, which makes it impossible to use
745 * VOP_FSYNC() there, due to the buffer lock
748 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
749 fl = buf_flush(vp, bd, flushbufqtarget);
750 td->td_pflags &= norunbuf;
754 if (bd->bd_wanted == 0)
757 error = msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
758 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
766 bufspace_daemon_shutdown(void *arg, int howto __unused)
768 struct bufdomain *bd = arg;
771 if (KERNEL_PANICKED())
775 bd->bd_shutdown = true;
776 wakeup(&bd->bd_running);
777 error = msleep(&bd->bd_shutdown, BD_RUN_LOCKPTR(bd), 0,
778 "bufspace_shutdown", 60 * hz);
781 printf("bufspacedaemon wait error: %d\n", error);
787 * buffer space management daemon. Tries to maintain some marginal
788 * amount of free buffer space so that requesting processes neither
789 * block nor work to reclaim buffers.
792 bufspace_daemon(void *arg)
794 struct bufdomain *bd = arg;
796 EVENTHANDLER_REGISTER(shutdown_pre_sync, bufspace_daemon_shutdown, bd,
797 SHUTDOWN_PRI_LAST + 100);
800 while (!bd->bd_shutdown) {
804 * Free buffers from the clean queue until we meet our
807 * Theory of operation: The buffer cache is most efficient
808 * when some free buffer headers and space are always
809 * available to getnewbuf(). This daemon attempts to prevent
810 * the excessive blocking and synchronization associated
811 * with shortfall. It goes through three phases according
814 * 1) The daemon wakes up voluntarily once per-second
815 * during idle periods when the counters are below
816 * the wakeup thresholds (bufspacethresh, lofreebuffers).
818 * 2) The daemon wakes up as we cross the thresholds
819 * ahead of any potential blocking. This may bounce
820 * slightly according to the rate of consumption and
823 * 3) The daemon and consumers are starved for working
824 * clean buffers. This is the 'bufspace' sleep below
825 * which will inefficiently trade bufs with bqrelse
826 * until we return to condition 2.
828 while (bd->bd_bufspace > bd->bd_lobufspace ||
829 bd->bd_freebuffers < bd->bd_hifreebuffers) {
830 if (buf_recycle(bd, false) != 0) {
834 * Speedup dirty if we've run out of clean
835 * buffers. This is possible in particular
836 * because softdep may held many bufs locked
837 * pending writes to other bufs which are
838 * marked for delayed write, exhausting
839 * clean space until they are written.
844 msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
845 PRIBIO|PDROP, "bufspace", hz/10);
853 * Re-check our limits and sleep. bd_running must be
854 * cleared prior to checking the limits to avoid missed
855 * wakeups. The waker will adjust one of bufspace or
856 * freebuffers prior to checking bd_running.
861 atomic_store_int(&bd->bd_running, 0);
862 if (bd->bd_bufspace < bd->bd_bufspacethresh &&
863 bd->bd_freebuffers > bd->bd_lofreebuffers) {
864 msleep(&bd->bd_running, BD_RUN_LOCKPTR(bd),
867 /* Avoid spurious wakeups while running. */
868 atomic_store_int(&bd->bd_running, 1);
871 wakeup(&bd->bd_shutdown);
879 * Adjust the reported bufspace for a malloc managed buffer, possibly
880 * waking any waiters.
883 bufmallocadjust(struct buf *bp, int bufsize)
887 KASSERT((bp->b_flags & B_MALLOC) != 0,
888 ("bufmallocadjust: non-malloc buf %p", bp));
889 diff = bufsize - bp->b_bufsize;
891 atomic_subtract_long(&bufmallocspace, -diff);
893 atomic_add_long(&bufmallocspace, diff);
894 bp->b_bufsize = bufsize;
900 * Wake up processes that are waiting on asynchronous writes to fall
901 * below lorunningspace.
907 mtx_lock(&rbreqlock);
910 wakeup(&runningbufreq);
912 mtx_unlock(&rbreqlock);
918 * Decrement the outstanding write count according.
921 runningbufwakeup(struct buf *bp)
925 bspace = bp->b_runningbufspace;
928 space = atomic_fetchadd_long(&runningbufspace, -bspace);
929 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
931 bp->b_runningbufspace = 0;
933 * Only acquire the lock and wakeup on the transition from exceeding
934 * the threshold to falling below it.
936 if (space < lorunningspace)
938 if (space - bspace > lorunningspace)
944 * waitrunningbufspace()
946 * runningbufspace is a measure of the amount of I/O currently
947 * running. This routine is used in async-write situations to
948 * prevent creating huge backups of pending writes to a device.
949 * Only asynchronous writes are governed by this function.
951 * This does NOT turn an async write into a sync write. It waits
952 * for earlier writes to complete and generally returns before the
953 * caller's write has reached the device.
956 waitrunningbufspace(void)
959 mtx_lock(&rbreqlock);
960 while (runningbufspace > hirunningspace) {
962 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
964 mtx_unlock(&rbreqlock);
968 * vfs_buf_test_cache:
970 * Called when a buffer is extended. This function clears the B_CACHE
971 * bit if the newly extended portion of the buffer does not contain
975 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
976 vm_offset_t size, vm_page_t m)
980 * This function and its results are protected by higher level
981 * synchronization requiring vnode and buf locks to page in and
984 if (bp->b_flags & B_CACHE) {
985 int base = (foff + off) & PAGE_MASK;
986 if (vm_page_is_valid(m, base, size) == 0)
987 bp->b_flags &= ~B_CACHE;
991 /* Wake up the buffer daemon if necessary */
997 if (bd_request == 0) {
1001 mtx_unlock(&bdlock);
1005 * Adjust the maxbcachbuf tunable.
1008 maxbcachebuf_adjust(void)
1013 * maxbcachebuf must be a power of 2 >= MAXBSIZE.
1016 while (i * 2 <= maxbcachebuf)
1019 if (maxbcachebuf < MAXBSIZE)
1020 maxbcachebuf = MAXBSIZE;
1021 if (maxbcachebuf > maxphys)
1022 maxbcachebuf = maxphys;
1023 if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF)
1024 printf("maxbcachebuf=%d\n", maxbcachebuf);
1028 * bd_speedup - speedup the buffer cache flushing code
1037 if (bd_speedupreq == 0 || bd_request == 0)
1042 wakeup(&bd_request);
1043 mtx_unlock(&bdlock);
1047 #define TRANSIENT_DENOM 5
1049 #define TRANSIENT_DENOM 10
1053 * Calculating buffer cache scaling values and reserve space for buffer
1054 * headers. This is called during low level kernel initialization and
1055 * may be called more then once. We CANNOT write to the memory area
1056 * being reserved at this time.
1059 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
1062 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
1065 * With KASAN or KMSAN enabled, the kernel map is shadowed. Account for
1066 * this when sizing maps based on the amount of physical memory
1070 physmem_est = (physmem_est * KASAN_SHADOW_SCALE) /
1071 (KASAN_SHADOW_SCALE + 1);
1072 #elif defined(KMSAN)
1076 * KMSAN cannot reliably determine whether buffer data is initialized
1077 * unless it is updated through a KVA mapping.
1079 unmapped_buf_allowed = 0;
1083 * physmem_est is in pages. Convert it to kilobytes (assumes
1084 * PAGE_SIZE is >= 1K)
1086 physmem_est = physmem_est * (PAGE_SIZE / 1024);
1088 maxbcachebuf_adjust();
1090 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
1091 * For the first 64MB of ram nominally allocate sufficient buffers to
1092 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
1093 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
1094 * the buffer cache we limit the eventual kva reservation to
1097 * factor represents the 1/4 x ram conversion.
1100 int factor = 4 * BKVASIZE / 1024;
1103 if (physmem_est > 4096)
1104 nbuf += min((physmem_est - 4096) / factor,
1106 if (physmem_est > 65536)
1107 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
1108 32 * 1024 * 1024 / (factor * 5));
1110 if (maxbcache && nbuf > maxbcache / BKVASIZE)
1111 nbuf = maxbcache / BKVASIZE;
1116 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
1117 maxbuf = (LONG_MAX / 3) / BKVASIZE;
1118 if (nbuf > maxbuf) {
1120 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
1126 * Ideal allocation size for the transient bio submap is 10%
1127 * of the maximal space buffer map. This roughly corresponds
1128 * to the amount of the buffer mapped for typical UFS load.
1130 * Clip the buffer map to reserve space for the transient
1131 * BIOs, if its extent is bigger than 90% (80% on i386) of the
1132 * maximum buffer map extent on the platform.
1134 * The fall-back to the maxbuf in case of maxbcache unset,
1135 * allows to not trim the buffer KVA for the architectures
1136 * with ample KVA space.
1138 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
1139 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
1140 buf_sz = (long)nbuf * BKVASIZE;
1141 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
1142 (TRANSIENT_DENOM - 1)) {
1144 * There is more KVA than memory. Do not
1145 * adjust buffer map size, and assign the rest
1146 * of maxbuf to transient map.
1148 biotmap_sz = maxbuf_sz - buf_sz;
1151 * Buffer map spans all KVA we could afford on
1152 * this platform. Give 10% (20% on i386) of
1153 * the buffer map to the transient bio map.
1155 biotmap_sz = buf_sz / TRANSIENT_DENOM;
1156 buf_sz -= biotmap_sz;
1158 if (biotmap_sz / INT_MAX > maxphys)
1159 bio_transient_maxcnt = INT_MAX;
1161 bio_transient_maxcnt = biotmap_sz / maxphys;
1163 * Artificially limit to 1024 simultaneous in-flight I/Os
1164 * using the transient mapping.
1166 if (bio_transient_maxcnt > 1024)
1167 bio_transient_maxcnt = 1024;
1169 nbuf = buf_sz / BKVASIZE;
1174 * Pager buffers are allocated for short periods, so scale the
1175 * number of reserved buffers based on the number of CPUs rather
1176 * than amount of memory.
1178 nswbuf = min(nbuf / 4, 32 * mp_ncpus);
1179 if (nswbuf < NSWBUF_MIN)
1180 nswbuf = NSWBUF_MIN;
1184 * Reserve space for the buffer cache buffers
1187 v = (caddr_t)buf + (sizeof(struct buf) + sizeof(vm_page_t) *
1188 atop(maxbcachebuf)) * nbuf;
1194 * Single global constant for BUF_WMESG, to avoid getting multiple
1197 static const char buf_wmesg[] = "bufwait";
1199 /* Initialize the buffer subsystem. Called before use of any buffers. */
1207 KASSERT(maxbcachebuf >= MAXBSIZE,
1208 ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf,
1210 bq_init(&bqempty, QUEUE_EMPTY, -1, "bufq empty lock");
1211 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1212 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1213 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1215 unmapped_buf = (caddr_t)kva_alloc(maxphys);
1217 /* finally, initialize each buffer header and stick on empty q */
1218 for (i = 0; i < nbuf; i++) {
1220 bzero(bp, sizeof(*bp) + sizeof(vm_page_t) * atop(maxbcachebuf));
1221 bp->b_flags = B_INVAL;
1222 bp->b_rcred = NOCRED;
1223 bp->b_wcred = NOCRED;
1224 bp->b_qindex = QUEUE_NONE;
1226 bp->b_subqueue = mp_maxid + 1;
1228 bp->b_data = bp->b_kvabase = unmapped_buf;
1229 LIST_INIT(&bp->b_dep);
1230 BUF_LOCKINIT(bp, buf_wmesg);
1231 bq_insert(&bqempty, bp, false);
1235 * maxbufspace is the absolute maximum amount of buffer space we are
1236 * allowed to reserve in KVM and in real terms. The absolute maximum
1237 * is nominally used by metadata. hibufspace is the nominal maximum
1238 * used by most other requests. The differential is required to
1239 * ensure that metadata deadlocks don't occur.
1241 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1242 * this may result in KVM fragmentation which is not handled optimally
1243 * by the system. XXX This is less true with vmem. We could use
1246 maxbufspace = (long)nbuf * BKVASIZE;
1247 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10);
1248 lobufspace = (hibufspace / 20) * 19; /* 95% */
1249 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1252 * Note: The 16 MiB upper limit for hirunningspace was chosen
1253 * arbitrarily and may need further tuning. It corresponds to
1254 * 128 outstanding write IO requests (if IO size is 128 KiB),
1255 * which fits with many RAID controllers' tagged queuing limits.
1256 * The lower 1 MiB limit is the historical upper limit for
1259 hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf),
1260 16 * 1024 * 1024), 1024 * 1024);
1261 lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf);
1264 * Limit the amount of malloc memory since it is wired permanently into
1265 * the kernel space. Even though this is accounted for in the buffer
1266 * allocation, we don't want the malloced region to grow uncontrolled.
1267 * The malloc scheme improves memory utilization significantly on
1268 * average (small) directories.
1270 maxbufmallocspace = hibufspace / 20;
1273 * Reduce the chance of a deadlock occurring by limiting the number
1274 * of delayed-write dirty buffers we allow to stack up.
1276 hidirtybuffers = nbuf / 4 + 20;
1277 dirtybufthresh = hidirtybuffers * 9 / 10;
1279 * To support extreme low-memory systems, make sure hidirtybuffers
1280 * cannot eat up all available buffer space. This occurs when our
1281 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1282 * buffer space assuming BKVASIZE'd buffers.
1284 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1285 hidirtybuffers >>= 1;
1287 lodirtybuffers = hidirtybuffers / 2;
1290 * lofreebuffers should be sufficient to avoid stalling waiting on
1291 * buf headers under heavy utilization. The bufs in per-cpu caches
1292 * are counted as free but will be unavailable to threads executing
1295 * hifreebuffers is the free target for the bufspace daemon. This
1296 * should be set appropriately to limit work per-iteration.
1298 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1299 hifreebuffers = (3 * lofreebuffers) / 2;
1300 numfreebuffers = nbuf;
1302 /* Setup the kva and free list allocators. */
1303 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1304 buf_zone = uma_zcache_create("buf free cache",
1305 sizeof(struct buf) + sizeof(vm_page_t) * atop(maxbcachebuf),
1306 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1309 * Size the clean queue according to the amount of buffer space.
1310 * One queue per-256mb up to the max. More queues gives better
1311 * concurrency but less accurate LRU.
1313 buf_domains = MIN(howmany(maxbufspace, 256*1024*1024), BUF_DOMAINS);
1314 for (i = 0 ; i < buf_domains; i++) {
1315 struct bufdomain *bd;
1319 bd->bd_freebuffers = nbuf / buf_domains;
1320 bd->bd_hifreebuffers = hifreebuffers / buf_domains;
1321 bd->bd_lofreebuffers = lofreebuffers / buf_domains;
1322 bd->bd_bufspace = 0;
1323 bd->bd_maxbufspace = maxbufspace / buf_domains;
1324 bd->bd_hibufspace = hibufspace / buf_domains;
1325 bd->bd_lobufspace = lobufspace / buf_domains;
1326 bd->bd_bufspacethresh = bufspacethresh / buf_domains;
1327 bd->bd_numdirtybuffers = 0;
1328 bd->bd_hidirtybuffers = hidirtybuffers / buf_domains;
1329 bd->bd_lodirtybuffers = lodirtybuffers / buf_domains;
1330 bd->bd_dirtybufthresh = dirtybufthresh / buf_domains;
1331 /* Don't allow more than 2% of bufs in the per-cpu caches. */
1332 bd->bd_lim = nbuf / buf_domains / 50 / mp_ncpus;
1334 getnewbufcalls = counter_u64_alloc(M_WAITOK);
1335 getnewbufrestarts = counter_u64_alloc(M_WAITOK);
1336 mappingrestarts = counter_u64_alloc(M_WAITOK);
1337 numbufallocfails = counter_u64_alloc(M_WAITOK);
1338 notbufdflushes = counter_u64_alloc(M_WAITOK);
1339 buffreekvacnt = counter_u64_alloc(M_WAITOK);
1340 bufdefragcnt = counter_u64_alloc(M_WAITOK);
1341 bufkvaspace = counter_u64_alloc(M_WAITOK);
1347 vfs_buf_check_mapped(struct buf *bp)
1350 KASSERT(bp->b_kvabase != unmapped_buf,
1351 ("mapped buf: b_kvabase was not updated %p", bp));
1352 KASSERT(bp->b_data != unmapped_buf,
1353 ("mapped buf: b_data was not updated %p", bp));
1354 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1355 maxphys, ("b_data + b_offset unmapped %p", bp));
1359 vfs_buf_check_unmapped(struct buf *bp)
1362 KASSERT(bp->b_data == unmapped_buf,
1363 ("unmapped buf: corrupted b_data %p", bp));
1366 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1367 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1369 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1370 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1374 isbufbusy(struct buf *bp)
1376 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1377 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1383 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1386 bufshutdown(int show_busybufs)
1388 static int first_buf_printf = 1;
1390 int i, iter, nbusy, pbusy;
1396 * Sync filesystems for shutdown
1398 wdog_kern_pat(WD_LASTVAL);
1399 kern_sync(curthread);
1402 * With soft updates, some buffers that are
1403 * written will be remarked as dirty until other
1404 * buffers are written.
1406 for (iter = pbusy = 0; iter < 20; iter++) {
1408 for (i = nbuf - 1; i >= 0; i--) {
1414 if (first_buf_printf)
1415 printf("All buffers synced.");
1418 if (first_buf_printf) {
1419 printf("Syncing disks, buffers remaining... ");
1420 first_buf_printf = 0;
1422 printf("%d ", nbusy);
1427 wdog_kern_pat(WD_LASTVAL);
1428 kern_sync(curthread);
1432 * Spin for a while to allow interrupt threads to run.
1434 DELAY(50000 * iter);
1437 * Context switch several times to allow interrupt
1440 for (subiter = 0; subiter < 50 * iter; subiter++) {
1441 sched_relinquish(curthread);
1448 * Count only busy local buffers to prevent forcing
1449 * a fsck if we're just a client of a wedged NFS server
1452 for (i = nbuf - 1; i >= 0; i--) {
1454 if (isbufbusy(bp)) {
1456 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1457 if (bp->b_dev == NULL) {
1458 TAILQ_REMOVE(&mountlist,
1459 bp->b_vp->v_mount, mnt_list);
1464 if (show_busybufs > 0) {
1466 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1467 nbusy, bp, bp->b_vp, bp->b_flags,
1468 (intmax_t)bp->b_blkno,
1469 (intmax_t)bp->b_lblkno);
1470 BUF_LOCKPRINTINFO(bp);
1471 if (show_busybufs > 1)
1479 * Failed to sync all blocks. Indicate this and don't
1480 * unmount filesystems (thus forcing an fsck on reboot).
1482 BOOTTRACE("shutdown failed to sync buffers");
1483 printf("Giving up on %d buffers\n", nbusy);
1484 DELAY(5000000); /* 5 seconds */
1487 BOOTTRACE("shutdown sync complete");
1488 if (!first_buf_printf)
1489 printf("Final sync complete\n");
1492 * Unmount filesystems and perform swapoff, to quiesce
1493 * the system as much as possible. In particular, no
1494 * I/O should be initiated from top levels since it
1495 * might be abruptly terminated by reset, or otherwise
1496 * erronously handled because other parts of the
1497 * system are disabled.
1499 * Swapoff before unmount, because file-backed swap is
1500 * non-operational after unmount of the underlying
1503 if (!KERNEL_PANICKED()) {
1507 BOOTTRACE("shutdown unmounted all filesystems");
1509 DELAY(100000); /* wait for console output to finish */
1513 bpmap_qenter(struct buf *bp)
1516 BUF_CHECK_MAPPED(bp);
1519 * bp->b_data is relative to bp->b_offset, but
1520 * bp->b_offset may be offset into the first page.
1522 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1523 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1524 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1525 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1528 static inline struct bufdomain *
1529 bufdomain(struct buf *bp)
1532 return (&bdomain[bp->b_domain]);
1535 static struct bufqueue *
1536 bufqueue(struct buf *bp)
1539 switch (bp->b_qindex) {
1542 case QUEUE_SENTINEL:
1547 return (&bufdomain(bp)->bd_dirtyq);
1549 return (&bufdomain(bp)->bd_subq[bp->b_subqueue]);
1553 panic("bufqueue(%p): Unhandled type %d\n", bp, bp->b_qindex);
1557 * Return the locked bufqueue that bp is a member of.
1559 static struct bufqueue *
1560 bufqueue_acquire(struct buf *bp)
1562 struct bufqueue *bq, *nbq;
1565 * bp can be pushed from a per-cpu queue to the
1566 * cleanq while we're waiting on the lock. Retry
1567 * if the queues don't match.
1585 * Insert the buffer into the appropriate free list. Requires a
1586 * locked buffer on entry and buffer is unlocked before return.
1589 binsfree(struct buf *bp, int qindex)
1591 struct bufdomain *bd;
1592 struct bufqueue *bq;
1594 KASSERT(qindex == QUEUE_CLEAN || qindex == QUEUE_DIRTY,
1595 ("binsfree: Invalid qindex %d", qindex));
1596 BUF_ASSERT_XLOCKED(bp);
1599 * Handle delayed bremfree() processing.
1601 if (bp->b_flags & B_REMFREE) {
1602 if (bp->b_qindex == qindex) {
1603 bp->b_flags |= B_REUSE;
1604 bp->b_flags &= ~B_REMFREE;
1608 bq = bufqueue_acquire(bp);
1613 if (qindex == QUEUE_CLEAN) {
1614 if (bd->bd_lim != 0)
1615 bq = &bd->bd_subq[PCPU_GET(cpuid)];
1619 bq = &bd->bd_dirtyq;
1620 bq_insert(bq, bp, true);
1626 * Free a buffer to the buf zone once it no longer has valid contents.
1629 buf_free(struct buf *bp)
1632 if (bp->b_flags & B_REMFREE)
1634 if (bp->b_vflags & BV_BKGRDINPROG)
1635 panic("losing buffer 1");
1636 if (bp->b_rcred != NOCRED) {
1637 crfree(bp->b_rcred);
1638 bp->b_rcred = NOCRED;
1640 if (bp->b_wcred != NOCRED) {
1641 crfree(bp->b_wcred);
1642 bp->b_wcred = NOCRED;
1644 if (!LIST_EMPTY(&bp->b_dep))
1647 atomic_add_int(&bufdomain(bp)->bd_freebuffers, 1);
1648 MPASS((bp->b_flags & B_MAXPHYS) == 0);
1650 uma_zfree(buf_zone, bp);
1656 * Import bufs into the uma cache from the buf list. The system still
1657 * expects a static array of bufs and much of the synchronization
1658 * around bufs assumes type stable storage. As a result, UMA is used
1659 * only as a per-cpu cache of bufs still maintained on a global list.
1662 buf_import(void *arg, void **store, int cnt, int domain, int flags)
1668 for (i = 0; i < cnt; i++) {
1669 bp = TAILQ_FIRST(&bqempty.bq_queue);
1672 bq_remove(&bqempty, bp);
1675 BQ_UNLOCK(&bqempty);
1683 * Release bufs from the uma cache back to the buffer queues.
1686 buf_release(void *arg, void **store, int cnt)
1688 struct bufqueue *bq;
1694 for (i = 0; i < cnt; i++) {
1696 /* Inline bq_insert() to batch locking. */
1697 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1698 bp->b_flags &= ~(B_AGE | B_REUSE);
1700 bp->b_qindex = bq->bq_index;
1708 * Allocate an empty buffer header.
1711 buf_alloc(struct bufdomain *bd)
1714 int freebufs, error;
1717 * We can only run out of bufs in the buf zone if the average buf
1718 * is less than BKVASIZE. In this case the actual wait/block will
1719 * come from buf_reycle() failing to flush one of these small bufs.
1722 freebufs = atomic_fetchadd_int(&bd->bd_freebuffers, -1);
1724 bp = uma_zalloc(buf_zone, M_NOWAIT);
1726 atomic_add_int(&bd->bd_freebuffers, 1);
1727 bufspace_daemon_wakeup(bd);
1728 counter_u64_add(numbufallocfails, 1);
1732 * Wake-up the bufspace daemon on transition below threshold.
1734 if (freebufs == bd->bd_lofreebuffers)
1735 bufspace_daemon_wakeup(bd);
1737 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
1738 KASSERT(error == 0, ("%s: BUF_LOCK on free buf %p: %d.", __func__, bp,
1742 KASSERT(bp->b_vp == NULL,
1743 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1744 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1745 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1746 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1747 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1748 KASSERT(bp->b_npages == 0,
1749 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1750 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1751 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1752 MPASS((bp->b_flags & B_MAXPHYS) == 0);
1754 bp->b_domain = BD_DOMAIN(bd);
1760 bp->b_blkno = bp->b_lblkno = 0;
1761 bp->b_offset = NOOFFSET;
1767 bp->b_dirtyoff = bp->b_dirtyend = 0;
1768 bp->b_bufobj = NULL;
1769 bp->b_data = bp->b_kvabase = unmapped_buf;
1770 bp->b_fsprivate1 = NULL;
1771 bp->b_fsprivate2 = NULL;
1772 bp->b_fsprivate3 = NULL;
1773 LIST_INIT(&bp->b_dep);
1781 * Free a buffer from the given bufqueue. kva controls whether the
1782 * freed buf must own some kva resources. This is used for
1786 buf_recycle(struct bufdomain *bd, bool kva)
1788 struct bufqueue *bq;
1789 struct buf *bp, *nbp;
1792 counter_u64_add(bufdefragcnt, 1);
1796 KASSERT(BQ_LOCKPTR(bq) == BD_LOCKPTR(bd),
1797 ("buf_recycle: Locks don't match"));
1798 nbp = TAILQ_FIRST(&bq->bq_queue);
1801 * Run scan, possibly freeing data and/or kva mappings on the fly
1804 while ((bp = nbp) != NULL) {
1806 * Calculate next bp (we can only use it if we do not
1807 * release the bqlock).
1809 nbp = TAILQ_NEXT(bp, b_freelist);
1812 * If we are defragging then we need a buffer with
1813 * some kva to reclaim.
1815 if (kva && bp->b_kvasize == 0)
1818 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1822 * Implement a second chance algorithm for frequently
1825 if ((bp->b_flags & B_REUSE) != 0) {
1826 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1827 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1828 bp->b_flags &= ~B_REUSE;
1834 * Skip buffers with background writes in progress.
1836 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1841 KASSERT(bp->b_qindex == QUEUE_CLEAN,
1842 ("buf_recycle: inconsistent queue %d bp %p",
1844 KASSERT(bp->b_domain == BD_DOMAIN(bd),
1845 ("getnewbuf: queue domain %d doesn't match request %d",
1846 bp->b_domain, (int)BD_DOMAIN(bd)));
1848 * NOTE: nbp is now entirely invalid. We can only restart
1849 * the scan from this point on.
1855 * Requeue the background write buffer with error and
1858 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1861 nbp = TAILQ_FIRST(&bq->bq_queue);
1864 bp->b_flags |= B_INVAL;
1877 * Mark the buffer for removal from the appropriate free list.
1881 bremfree(struct buf *bp)
1884 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1885 KASSERT((bp->b_flags & B_REMFREE) == 0,
1886 ("bremfree: buffer %p already marked for delayed removal.", bp));
1887 KASSERT(bp->b_qindex != QUEUE_NONE,
1888 ("bremfree: buffer %p not on a queue.", bp));
1889 BUF_ASSERT_XLOCKED(bp);
1891 bp->b_flags |= B_REMFREE;
1897 * Force an immediate removal from a free list. Used only in nfs when
1898 * it abuses the b_freelist pointer.
1901 bremfreef(struct buf *bp)
1903 struct bufqueue *bq;
1905 bq = bufqueue_acquire(bp);
1911 bq_init(struct bufqueue *bq, int qindex, int subqueue, const char *lockname)
1914 mtx_init(&bq->bq_lock, lockname, NULL, MTX_DEF);
1915 TAILQ_INIT(&bq->bq_queue);
1917 bq->bq_index = qindex;
1918 bq->bq_subqueue = subqueue;
1922 bd_init(struct bufdomain *bd)
1926 /* Per-CPU clean buf queues, plus one global queue. */
1927 bd->bd_subq = mallocarray(mp_maxid + 2, sizeof(struct bufqueue),
1928 M_BIOBUF, M_WAITOK | M_ZERO);
1929 bd->bd_cleanq = &bd->bd_subq[mp_maxid + 1];
1930 bq_init(bd->bd_cleanq, QUEUE_CLEAN, mp_maxid + 1, "bufq clean lock");
1931 bq_init(&bd->bd_dirtyq, QUEUE_DIRTY, -1, "bufq dirty lock");
1932 for (i = 0; i <= mp_maxid; i++)
1933 bq_init(&bd->bd_subq[i], QUEUE_CLEAN, i,
1934 "bufq clean subqueue lock");
1935 mtx_init(&bd->bd_run_lock, "bufspace daemon run lock", NULL, MTX_DEF);
1941 * Removes a buffer from the free list, must be called with the
1942 * correct qlock held.
1945 bq_remove(struct bufqueue *bq, struct buf *bp)
1948 CTR3(KTR_BUF, "bq_remove(%p) vp %p flags %X",
1949 bp, bp->b_vp, bp->b_flags);
1950 KASSERT(bp->b_qindex != QUEUE_NONE,
1951 ("bq_remove: buffer %p not on a queue.", bp));
1952 KASSERT(bufqueue(bp) == bq,
1953 ("bq_remove: Remove buffer %p from wrong queue.", bp));
1955 BQ_ASSERT_LOCKED(bq);
1956 if (bp->b_qindex != QUEUE_EMPTY) {
1957 BUF_ASSERT_XLOCKED(bp);
1959 KASSERT(bq->bq_len >= 1,
1960 ("queue %d underflow", bp->b_qindex));
1961 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1963 bp->b_qindex = QUEUE_NONE;
1964 bp->b_flags &= ~(B_REMFREE | B_REUSE);
1968 bd_flush(struct bufdomain *bd, struct bufqueue *bq)
1972 BQ_ASSERT_LOCKED(bq);
1973 if (bq != bd->bd_cleanq) {
1975 while ((bp = TAILQ_FIRST(&bq->bq_queue)) != NULL) {
1976 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1977 TAILQ_INSERT_TAIL(&bd->bd_cleanq->bq_queue, bp,
1979 bp->b_subqueue = bd->bd_cleanq->bq_subqueue;
1981 bd->bd_cleanq->bq_len += bq->bq_len;
1984 if (bd->bd_wanted) {
1986 wakeup(&bd->bd_wanted);
1988 if (bq != bd->bd_cleanq)
1993 bd_flushall(struct bufdomain *bd)
1995 struct bufqueue *bq;
1999 if (bd->bd_lim == 0)
2002 for (i = 0; i <= mp_maxid; i++) {
2003 bq = &bd->bd_subq[i];
2004 if (bq->bq_len == 0)
2016 bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock)
2018 struct bufdomain *bd;
2020 if (bp->b_qindex != QUEUE_NONE)
2021 panic("bq_insert: free buffer %p onto another queue?", bp);
2024 if (bp->b_flags & B_AGE) {
2025 /* Place this buf directly on the real queue. */
2026 if (bq->bq_index == QUEUE_CLEAN)
2029 TAILQ_INSERT_HEAD(&bq->bq_queue, bp, b_freelist);
2032 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
2034 bp->b_flags &= ~(B_AGE | B_REUSE);
2036 bp->b_qindex = bq->bq_index;
2037 bp->b_subqueue = bq->bq_subqueue;
2040 * Unlock before we notify so that we don't wakeup a waiter that
2041 * fails a trylock on the buf and sleeps again.
2046 if (bp->b_qindex == QUEUE_CLEAN) {
2048 * Flush the per-cpu queue and notify any waiters.
2050 if (bd->bd_wanted || (bq != bd->bd_cleanq &&
2051 bq->bq_len >= bd->bd_lim))
2060 * Free the kva allocation for a buffer.
2064 bufkva_free(struct buf *bp)
2068 if (bp->b_kvasize == 0) {
2069 KASSERT(bp->b_kvabase == unmapped_buf &&
2070 bp->b_data == unmapped_buf,
2071 ("Leaked KVA space on %p", bp));
2072 } else if (buf_mapped(bp))
2073 BUF_CHECK_MAPPED(bp);
2075 BUF_CHECK_UNMAPPED(bp);
2077 if (bp->b_kvasize == 0)
2080 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
2081 counter_u64_add(bufkvaspace, -bp->b_kvasize);
2082 counter_u64_add(buffreekvacnt, 1);
2083 bp->b_data = bp->b_kvabase = unmapped_buf;
2090 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
2093 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
2098 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
2099 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
2100 MPASS((bp->b_flags & B_MAXPHYS) == 0);
2101 KASSERT(maxsize <= maxbcachebuf,
2102 ("bufkva_alloc kva too large %d %u", maxsize, maxbcachebuf));
2107 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
2110 * Buffer map is too fragmented. Request the caller
2111 * to defragment the map.
2115 bp->b_kvabase = (caddr_t)addr;
2116 bp->b_kvasize = maxsize;
2117 counter_u64_add(bufkvaspace, bp->b_kvasize);
2118 if ((gbflags & GB_UNMAPPED) != 0) {
2119 bp->b_data = unmapped_buf;
2120 BUF_CHECK_UNMAPPED(bp);
2122 bp->b_data = bp->b_kvabase;
2123 BUF_CHECK_MAPPED(bp);
2131 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
2132 * callback that fires to avoid returning failure.
2135 bufkva_reclaim(vmem_t *vmem, int flags)
2142 for (i = 0; i < 5; i++) {
2143 for (q = 0; q < buf_domains; q++)
2144 if (buf_recycle(&bdomain[q], true) != 0)
2153 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
2154 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
2155 * the buffer is valid and we do not have to do anything.
2158 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize, int cnt,
2159 struct ucred * cred, int flags, void (*ckhashfunc)(struct buf *))
2167 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
2168 if (inmem(vp, *rablkno))
2170 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
2171 if ((rabp->b_flags & B_CACHE) != 0) {
2178 racct_add_buf(curproc, rabp, 0);
2179 PROC_UNLOCK(curproc);
2182 td->td_ru.ru_inblock++;
2183 rabp->b_flags |= B_ASYNC;
2184 rabp->b_flags &= ~B_INVAL;
2185 if ((flags & GB_CKHASH) != 0) {
2186 rabp->b_flags |= B_CKHASH;
2187 rabp->b_ckhashcalc = ckhashfunc;
2189 rabp->b_ioflags &= ~BIO_ERROR;
2190 rabp->b_iocmd = BIO_READ;
2191 if (rabp->b_rcred == NOCRED && cred != NOCRED)
2192 rabp->b_rcred = crhold(cred);
2193 vfs_busy_pages(rabp, 0);
2195 rabp->b_iooffset = dbtob(rabp->b_blkno);
2201 * Entry point for bread() and breadn() via #defines in sys/buf.h.
2203 * Get a buffer with the specified data. Look in the cache first. We
2204 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
2205 * is set, the buffer is valid and we do not have to do anything, see
2206 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
2208 * Always return a NULL buffer pointer (in bpp) when returning an error.
2210 * The blkno parameter is the logical block being requested. Normally
2211 * the mapping of logical block number to disk block address is done
2212 * by calling VOP_BMAP(). However, if the mapping is already known, the
2213 * disk block address can be passed using the dblkno parameter. If the
2214 * disk block address is not known, then the same value should be passed
2215 * for blkno and dblkno.
2218 breadn_flags(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size,
2219 daddr_t *rablkno, int *rabsize, int cnt, struct ucred *cred, int flags,
2220 void (*ckhashfunc)(struct buf *), struct buf **bpp)
2224 int error, readwait, rv;
2226 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
2229 * Can only return NULL if GB_LOCK_NOWAIT or GB_SPARSE flags
2232 error = getblkx(vp, blkno, dblkno, size, 0, 0, flags, &bp);
2237 KASSERT(blkno == bp->b_lblkno,
2238 ("getblkx returned buffer for blkno %jd instead of blkno %jd",
2239 (intmax_t)bp->b_lblkno, (intmax_t)blkno));
2240 flags &= ~GB_NOSPARSE;
2244 * If not found in cache, do some I/O
2247 if ((bp->b_flags & B_CACHE) == 0) {
2250 PROC_LOCK(td->td_proc);
2251 racct_add_buf(td->td_proc, bp, 0);
2252 PROC_UNLOCK(td->td_proc);
2255 td->td_ru.ru_inblock++;
2256 bp->b_iocmd = BIO_READ;
2257 bp->b_flags &= ~B_INVAL;
2258 if ((flags & GB_CKHASH) != 0) {
2259 bp->b_flags |= B_CKHASH;
2260 bp->b_ckhashcalc = ckhashfunc;
2262 if ((flags & GB_CVTENXIO) != 0)
2263 bp->b_xflags |= BX_CVTENXIO;
2264 bp->b_ioflags &= ~BIO_ERROR;
2265 if (bp->b_rcred == NOCRED && cred != NOCRED)
2266 bp->b_rcred = crhold(cred);
2267 vfs_busy_pages(bp, 0);
2268 bp->b_iooffset = dbtob(bp->b_blkno);
2274 * Attempt to initiate asynchronous I/O on read-ahead blocks.
2276 breada(vp, rablkno, rabsize, cnt, cred, flags, ckhashfunc);
2290 * Write, release buffer on completion. (Done by iodone
2291 * if async). Do not bother writing anything if the buffer
2294 * Note that we set B_CACHE here, indicating that buffer is
2295 * fully valid and thus cacheable. This is true even of NFS
2296 * now so we set it generally. This could be set either here
2297 * or in biodone() since the I/O is synchronous. We put it
2301 bufwrite(struct buf *bp)
2308 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2309 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
2310 bp->b_flags |= B_INVAL | B_RELBUF;
2311 bp->b_flags &= ~B_CACHE;
2315 if (bp->b_flags & B_INVAL) {
2320 if (bp->b_flags & B_BARRIER)
2321 atomic_add_long(&barrierwrites, 1);
2323 oldflags = bp->b_flags;
2325 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
2326 ("FFS background buffer should not get here %p", bp));
2330 vp_md = vp->v_vflag & VV_MD;
2335 * Mark the buffer clean. Increment the bufobj write count
2336 * before bundirty() call, to prevent other thread from seeing
2337 * empty dirty list and zero counter for writes in progress,
2338 * falsely indicating that the bufobj is clean.
2340 bufobj_wref(bp->b_bufobj);
2343 bp->b_flags &= ~B_DONE;
2344 bp->b_ioflags &= ~BIO_ERROR;
2345 bp->b_flags |= B_CACHE;
2346 bp->b_iocmd = BIO_WRITE;
2348 vfs_busy_pages(bp, 1);
2351 * Normal bwrites pipeline writes
2353 bp->b_runningbufspace = bp->b_bufsize;
2354 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
2359 racct_add_buf(curproc, bp, 1);
2360 PROC_UNLOCK(curproc);
2363 curthread->td_ru.ru_oublock++;
2364 if (oldflags & B_ASYNC)
2366 bp->b_iooffset = dbtob(bp->b_blkno);
2367 buf_track(bp, __func__);
2370 if ((oldflags & B_ASYNC) == 0) {
2371 int rtval = bufwait(bp);
2374 } else if (space > hirunningspace) {
2376 * don't allow the async write to saturate the I/O
2377 * system. We will not deadlock here because
2378 * we are blocking waiting for I/O that is already in-progress
2379 * to complete. We do not block here if it is the update
2380 * or syncer daemon trying to clean up as that can lead
2383 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
2384 waitrunningbufspace();
2391 bufbdflush(struct bufobj *bo, struct buf *bp)
2394 struct bufdomain *bd;
2396 bd = &bdomain[bo->bo_domain];
2397 if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh + 10) {
2398 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
2400 } else if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh) {
2403 * Try to find a buffer to flush.
2405 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2406 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2408 LK_EXCLUSIVE | LK_NOWAIT, NULL))
2411 panic("bdwrite: found ourselves");
2413 /* Don't countdeps with the bo lock held. */
2414 if (buf_countdeps(nbp, 0)) {
2419 if (nbp->b_flags & B_CLUSTEROK) {
2420 vfs_bio_awrite(nbp);
2425 dirtybufferflushes++;
2434 * Delayed write. (Buffer is marked dirty). Do not bother writing
2435 * anything if the buffer is marked invalid.
2437 * Note that since the buffer must be completely valid, we can safely
2438 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2439 * biodone() in order to prevent getblk from writing the buffer
2440 * out synchronously.
2443 bdwrite(struct buf *bp)
2445 struct thread *td = curthread;
2449 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2450 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2451 KASSERT((bp->b_flags & B_BARRIER) == 0,
2452 ("Barrier request in delayed write %p", bp));
2454 if (bp->b_flags & B_INVAL) {
2460 * If we have too many dirty buffers, don't create any more.
2461 * If we are wildly over our limit, then force a complete
2462 * cleanup. Otherwise, just keep the situation from getting
2463 * out of control. Note that we have to avoid a recursive
2464 * disaster and not try to clean up after our own cleanup!
2468 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2469 td->td_pflags |= TDP_INBDFLUSH;
2471 td->td_pflags &= ~TDP_INBDFLUSH;
2477 * Set B_CACHE, indicating that the buffer is fully valid. This is
2478 * true even of NFS now.
2480 bp->b_flags |= B_CACHE;
2483 * This bmap keeps the system from needing to do the bmap later,
2484 * perhaps when the system is attempting to do a sync. Since it
2485 * is likely that the indirect block -- or whatever other datastructure
2486 * that the filesystem needs is still in memory now, it is a good
2487 * thing to do this. Note also, that if the pageout daemon is
2488 * requesting a sync -- there might not be enough memory to do
2489 * the bmap then... So, this is important to do.
2491 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2492 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2495 buf_track(bp, __func__);
2498 * Set the *dirty* buffer range based upon the VM system dirty
2501 * Mark the buffer pages as clean. We need to do this here to
2502 * satisfy the vnode_pager and the pageout daemon, so that it
2503 * thinks that the pages have been "cleaned". Note that since
2504 * the pages are in a delayed write buffer -- the VFS layer
2505 * "will" see that the pages get written out on the next sync,
2506 * or perhaps the cluster will be completed.
2508 vfs_clean_pages_dirty_buf(bp);
2512 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2513 * due to the softdep code.
2520 * Turn buffer into delayed write request. We must clear BIO_READ and
2521 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2522 * itself to properly update it in the dirty/clean lists. We mark it
2523 * B_DONE to ensure that any asynchronization of the buffer properly
2524 * clears B_DONE ( else a panic will occur later ).
2526 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2527 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2528 * should only be called if the buffer is known-good.
2530 * Since the buffer is not on a queue, we do not update the numfreebuffers
2533 * The buffer must be on QUEUE_NONE.
2536 bdirty(struct buf *bp)
2539 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2540 bp, bp->b_vp, bp->b_flags);
2541 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2542 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2543 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2544 bp->b_flags &= ~(B_RELBUF);
2545 bp->b_iocmd = BIO_WRITE;
2547 if ((bp->b_flags & B_DELWRI) == 0) {
2548 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2557 * Clear B_DELWRI for buffer.
2559 * Since the buffer is not on a queue, we do not update the numfreebuffers
2562 * The buffer must be on QUEUE_NONE.
2566 bundirty(struct buf *bp)
2569 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2570 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2571 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2572 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2574 if (bp->b_flags & B_DELWRI) {
2575 bp->b_flags &= ~B_DELWRI;
2580 * Since it is now being written, we can clear its deferred write flag.
2582 bp->b_flags &= ~B_DEFERRED;
2588 * Asynchronous write. Start output on a buffer, but do not wait for
2589 * it to complete. The buffer is released when the output completes.
2591 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2592 * B_INVAL buffers. Not us.
2595 bawrite(struct buf *bp)
2598 bp->b_flags |= B_ASYNC;
2605 * Asynchronous barrier write. Start output on a buffer, but do not
2606 * wait for it to complete. Place a write barrier after this write so
2607 * that this buffer and all buffers written before it are committed to
2608 * the disk before any buffers written after this write are committed
2609 * to the disk. The buffer is released when the output completes.
2612 babarrierwrite(struct buf *bp)
2615 bp->b_flags |= B_ASYNC | B_BARRIER;
2622 * Synchronous barrier write. Start output on a buffer and wait for
2623 * it to complete. Place a write barrier after this write so that
2624 * this buffer and all buffers written before it are committed to
2625 * the disk before any buffers written after this write are committed
2626 * to the disk. The buffer is released when the output completes.
2629 bbarrierwrite(struct buf *bp)
2632 bp->b_flags |= B_BARRIER;
2633 return (bwrite(bp));
2639 * Called prior to the locking of any vnodes when we are expecting to
2640 * write. We do not want to starve the buffer cache with too many
2641 * dirty buffers so we block here. By blocking prior to the locking
2642 * of any vnodes we attempt to avoid the situation where a locked vnode
2643 * prevents the various system daemons from flushing related buffers.
2649 if (buf_dirty_count_severe()) {
2650 mtx_lock(&bdirtylock);
2651 while (buf_dirty_count_severe()) {
2653 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2656 mtx_unlock(&bdirtylock);
2661 * Return true if we have too many dirty buffers.
2664 buf_dirty_count_severe(void)
2667 return (!BIT_EMPTY(BUF_DOMAINS, &bdhidirty));
2673 * Release a busy buffer and, if requested, free its resources. The
2674 * buffer will be stashed in the appropriate bufqueue[] allowing it
2675 * to be accessed later as a cache entity or reused for other purposes.
2678 brelse(struct buf *bp)
2680 struct mount *v_mnt;
2684 * Many functions erroneously call brelse with a NULL bp under rare
2685 * error conditions. Simply return when called with a NULL bp.
2689 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2690 bp, bp->b_vp, bp->b_flags);
2691 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2692 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2693 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2694 ("brelse: non-VMIO buffer marked NOREUSE"));
2696 if (BUF_LOCKRECURSED(bp)) {
2698 * Do not process, in particular, do not handle the
2699 * B_INVAL/B_RELBUF and do not release to free list.
2705 if (bp->b_flags & B_MANAGED) {
2710 if (LIST_EMPTY(&bp->b_dep)) {
2711 bp->b_flags &= ~B_IOSTARTED;
2713 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2714 ("brelse: SU io not finished bp %p", bp));
2717 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2718 BO_LOCK(bp->b_bufobj);
2719 bp->b_vflags &= ~BV_BKGRDERR;
2720 BO_UNLOCK(bp->b_bufobj);
2724 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2725 (bp->b_flags & B_INVALONERR)) {
2727 * Forced invalidation of dirty buffer contents, to be used
2728 * after a failed write in the rare case that the loss of the
2729 * contents is acceptable. The buffer is invalidated and
2732 bp->b_flags |= B_INVAL | B_RELBUF | B_NOCACHE;
2733 bp->b_flags &= ~(B_ASYNC | B_CACHE);
2736 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2737 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2738 !(bp->b_flags & B_INVAL)) {
2740 * Failed write, redirty. All errors except ENXIO (which
2741 * means the device is gone) are treated as being
2744 * XXX Treating EIO as transient is not correct; the
2745 * contract with the local storage device drivers is that
2746 * they will only return EIO once the I/O is no longer
2747 * retriable. Network I/O also respects this through the
2748 * guarantees of TCP and/or the internal retries of NFS.
2749 * ENOMEM might be transient, but we also have no way of
2750 * knowing when its ok to retry/reschedule. In general,
2751 * this entire case should be made obsolete through better
2752 * error handling/recovery and resource scheduling.
2754 * Do this also for buffers that failed with ENXIO, but have
2755 * non-empty dependencies - the soft updates code might need
2756 * to access the buffer to untangle them.
2758 * Must clear BIO_ERROR to prevent pages from being scrapped.
2760 bp->b_ioflags &= ~BIO_ERROR;
2762 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2763 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2765 * Either a failed read I/O, or we were asked to free or not
2766 * cache the buffer, or we failed to write to a device that's
2767 * no longer present.
2769 bp->b_flags |= B_INVAL;
2770 if (!LIST_EMPTY(&bp->b_dep))
2772 if (bp->b_flags & B_DELWRI)
2774 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2775 if ((bp->b_flags & B_VMIO) == 0) {
2783 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2784 * is called with B_DELWRI set, the underlying pages may wind up
2785 * getting freed causing a previous write (bdwrite()) to get 'lost'
2786 * because pages associated with a B_DELWRI bp are marked clean.
2788 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2789 * if B_DELWRI is set.
2791 if (bp->b_flags & B_DELWRI)
2792 bp->b_flags &= ~B_RELBUF;
2795 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2796 * constituted, not even NFS buffers now. Two flags effect this. If
2797 * B_INVAL, the struct buf is invalidated but the VM object is kept
2798 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2800 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2801 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2802 * buffer is also B_INVAL because it hits the re-dirtying code above.
2804 * Normally we can do this whether a buffer is B_DELWRI or not. If
2805 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2806 * the commit state and we cannot afford to lose the buffer. If the
2807 * buffer has a background write in progress, we need to keep it
2808 * around to prevent it from being reconstituted and starting a second
2812 v_mnt = bp->b_vp != NULL ? bp->b_vp->v_mount : NULL;
2814 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2815 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2816 (v_mnt == NULL || (v_mnt->mnt_vfc->vfc_flags & VFCF_NETWORK) == 0 ||
2817 vn_isdisk(bp->b_vp) || (bp->b_flags & B_DELWRI) == 0)) {
2818 vfs_vmio_invalidate(bp);
2822 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2823 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2825 bp->b_flags &= ~B_NOREUSE;
2826 if (bp->b_vp != NULL)
2831 * If the buffer has junk contents signal it and eventually
2832 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2835 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2836 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2837 bp->b_flags |= B_INVAL;
2838 if (bp->b_flags & B_INVAL) {
2839 if (bp->b_flags & B_DELWRI)
2845 buf_track(bp, __func__);
2847 /* buffers with no memory */
2848 if (bp->b_bufsize == 0) {
2852 /* buffers with junk contents */
2853 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2854 (bp->b_ioflags & BIO_ERROR)) {
2855 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2856 if (bp->b_vflags & BV_BKGRDINPROG)
2857 panic("losing buffer 2");
2858 qindex = QUEUE_CLEAN;
2859 bp->b_flags |= B_AGE;
2860 /* remaining buffers */
2861 } else if (bp->b_flags & B_DELWRI)
2862 qindex = QUEUE_DIRTY;
2864 qindex = QUEUE_CLEAN;
2866 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2867 panic("brelse: not dirty");
2869 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
2870 bp->b_xflags &= ~(BX_CVTENXIO);
2871 /* binsfree unlocks bp. */
2872 binsfree(bp, qindex);
2876 * Release a buffer back to the appropriate queue but do not try to free
2877 * it. The buffer is expected to be used again soon.
2879 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2880 * biodone() to requeue an async I/O on completion. It is also used when
2881 * known good buffers need to be requeued but we think we may need the data
2884 * XXX we should be able to leave the B_RELBUF hint set on completion.
2887 bqrelse(struct buf *bp)
2891 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2892 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2893 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2895 qindex = QUEUE_NONE;
2896 if (BUF_LOCKRECURSED(bp)) {
2897 /* do not release to free list */
2901 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2902 bp->b_xflags &= ~(BX_CVTENXIO);
2904 if (LIST_EMPTY(&bp->b_dep)) {
2905 bp->b_flags &= ~B_IOSTARTED;
2907 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2908 ("bqrelse: SU io not finished bp %p", bp));
2911 if (bp->b_flags & B_MANAGED) {
2912 if (bp->b_flags & B_REMFREE)
2917 /* buffers with stale but valid contents */
2918 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2919 BV_BKGRDERR)) == BV_BKGRDERR) {
2920 BO_LOCK(bp->b_bufobj);
2921 bp->b_vflags &= ~BV_BKGRDERR;
2922 BO_UNLOCK(bp->b_bufobj);
2923 qindex = QUEUE_DIRTY;
2925 if ((bp->b_flags & B_DELWRI) == 0 &&
2926 (bp->b_xflags & BX_VNDIRTY))
2927 panic("bqrelse: not dirty");
2928 if ((bp->b_flags & B_NOREUSE) != 0) {
2932 qindex = QUEUE_CLEAN;
2934 buf_track(bp, __func__);
2935 /* binsfree unlocks bp. */
2936 binsfree(bp, qindex);
2940 buf_track(bp, __func__);
2946 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2947 * restore bogus pages.
2950 vfs_vmio_iodone(struct buf *bp)
2955 struct vnode *vp __unused;
2956 int i, iosize, resid;
2959 obj = bp->b_bufobj->bo_object;
2960 KASSERT(blockcount_read(&obj->paging_in_progress) >= bp->b_npages,
2961 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2962 blockcount_read(&obj->paging_in_progress), bp->b_npages));
2965 VNPASS(vp->v_holdcnt > 0, vp);
2966 VNPASS(vp->v_object != NULL, vp);
2968 foff = bp->b_offset;
2969 KASSERT(bp->b_offset != NOOFFSET,
2970 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2973 iosize = bp->b_bcount - bp->b_resid;
2974 for (i = 0; i < bp->b_npages; i++) {
2975 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2980 * cleanup bogus pages, restoring the originals
2983 if (m == bogus_page) {
2985 m = vm_page_relookup(obj, OFF_TO_IDX(foff));
2987 panic("biodone: page disappeared!");
2989 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2991 * In the write case, the valid and clean bits are
2992 * already changed correctly ( see bdwrite() ), so we
2993 * only need to do this here in the read case.
2995 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2996 resid)) == 0, ("vfs_vmio_iodone: page %p "
2997 "has unexpected dirty bits", m));
2998 vfs_page_set_valid(bp, foff, m);
3000 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3001 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
3002 (intmax_t)foff, (uintmax_t)m->pindex));
3005 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3008 vm_object_pip_wakeupn(obj, bp->b_npages);
3009 if (bogus && buf_mapped(bp)) {
3010 BUF_CHECK_MAPPED(bp);
3011 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3012 bp->b_pages, bp->b_npages);
3017 * Perform page invalidation when a buffer is released. The fully invalid
3018 * pages will be reclaimed later in vfs_vmio_truncate().
3021 vfs_vmio_invalidate(struct buf *bp)
3025 int flags, i, resid, poffset, presid;
3027 if (buf_mapped(bp)) {
3028 BUF_CHECK_MAPPED(bp);
3029 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
3031 BUF_CHECK_UNMAPPED(bp);
3033 * Get the base offset and length of the buffer. Note that
3034 * in the VMIO case if the buffer block size is not
3035 * page-aligned then b_data pointer may not be page-aligned.
3036 * But our b_pages[] array *IS* page aligned.
3038 * block sizes less then DEV_BSIZE (usually 512) are not
3039 * supported due to the page granularity bits (m->valid,
3040 * m->dirty, etc...).
3042 * See man buf(9) for more information
3044 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3045 obj = bp->b_bufobj->bo_object;
3046 resid = bp->b_bufsize;
3047 poffset = bp->b_offset & PAGE_MASK;
3048 VM_OBJECT_WLOCK(obj);
3049 for (i = 0; i < bp->b_npages; i++) {
3051 if (m == bogus_page)
3052 panic("vfs_vmio_invalidate: Unexpected bogus page.");
3053 bp->b_pages[i] = NULL;
3055 presid = resid > (PAGE_SIZE - poffset) ?
3056 (PAGE_SIZE - poffset) : resid;
3057 KASSERT(presid >= 0, ("brelse: extra page"));
3058 vm_page_busy_acquire(m, VM_ALLOC_SBUSY);
3059 if (pmap_page_wired_mappings(m) == 0)
3060 vm_page_set_invalid(m, poffset, presid);
3062 vm_page_release_locked(m, flags);
3066 VM_OBJECT_WUNLOCK(obj);
3071 * Page-granular truncation of an existing VMIO buffer.
3074 vfs_vmio_truncate(struct buf *bp, int desiredpages)
3080 if (bp->b_npages == desiredpages)
3083 if (buf_mapped(bp)) {
3084 BUF_CHECK_MAPPED(bp);
3085 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
3086 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
3088 BUF_CHECK_UNMAPPED(bp);
3091 * The object lock is needed only if we will attempt to free pages.
3093 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3094 if ((bp->b_flags & B_DIRECT) != 0) {
3095 flags |= VPR_TRYFREE;
3096 obj = bp->b_bufobj->bo_object;
3097 VM_OBJECT_WLOCK(obj);
3101 for (i = desiredpages; i < bp->b_npages; i++) {
3103 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
3104 bp->b_pages[i] = NULL;
3106 vm_page_release_locked(m, flags);
3108 vm_page_release(m, flags);
3111 VM_OBJECT_WUNLOCK(obj);
3112 bp->b_npages = desiredpages;
3116 * Byte granular extension of VMIO buffers.
3119 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
3122 * We are growing the buffer, possibly in a
3123 * byte-granular fashion.
3131 * Step 1, bring in the VM pages from the object, allocating
3132 * them if necessary. We must clear B_CACHE if these pages
3133 * are not valid for the range covered by the buffer.
3135 obj = bp->b_bufobj->bo_object;
3136 if (bp->b_npages < desiredpages) {
3137 KASSERT(desiredpages <= atop(maxbcachebuf),
3138 ("vfs_vmio_extend past maxbcachebuf %p %d %u",
3139 bp, desiredpages, maxbcachebuf));
3142 * We must allocate system pages since blocking
3143 * here could interfere with paging I/O, no
3144 * matter which process we are.
3146 * Only exclusive busy can be tested here.
3147 * Blocking on shared busy might lead to
3148 * deadlocks once allocbuf() is called after
3149 * pages are vfs_busy_pages().
3151 (void)vm_page_grab_pages_unlocked(obj,
3152 OFF_TO_IDX(bp->b_offset) + bp->b_npages,
3153 VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
3154 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
3155 &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
3156 bp->b_npages = desiredpages;
3160 * Step 2. We've loaded the pages into the buffer,
3161 * we have to figure out if we can still have B_CACHE
3162 * set. Note that B_CACHE is set according to the
3163 * byte-granular range ( bcount and size ), not the
3164 * aligned range ( newbsize ).
3166 * The VM test is against m->valid, which is DEV_BSIZE
3167 * aligned. Needless to say, the validity of the data
3168 * needs to also be DEV_BSIZE aligned. Note that this
3169 * fails with NFS if the server or some other client
3170 * extends the file's EOF. If our buffer is resized,
3171 * B_CACHE may remain set! XXX
3173 toff = bp->b_bcount;
3174 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3175 while ((bp->b_flags & B_CACHE) && toff < size) {
3178 if (tinc > (size - toff))
3180 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
3181 m = bp->b_pages[pi];
3182 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
3188 * Step 3, fixup the KVA pmap.
3193 BUF_CHECK_UNMAPPED(bp);
3197 * Check to see if a block at a particular lbn is available for a clustered
3201 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
3208 /* If the buf isn't in core skip it */
3209 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
3212 /* If the buf is busy we don't want to wait for it */
3213 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
3216 /* Only cluster with valid clusterable delayed write buffers */
3217 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
3218 (B_DELWRI | B_CLUSTEROK))
3221 if (bpa->b_bufsize != size)
3225 * Check to see if it is in the expected place on disk and that the
3226 * block has been mapped.
3228 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
3238 * Implement clustered async writes for clearing out B_DELWRI buffers.
3239 * This is much better then the old way of writing only one buffer at
3240 * a time. Note that we may not be presented with the buffers in the
3241 * correct order, so we search for the cluster in both directions.
3244 vfs_bio_awrite(struct buf *bp)
3249 daddr_t lblkno = bp->b_lblkno;
3250 struct vnode *vp = bp->b_vp;
3258 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
3260 * right now we support clustered writing only to regular files. If
3261 * we find a clusterable block we could be in the middle of a cluster
3262 * rather then at the beginning.
3264 if ((vp->v_type == VREG) &&
3265 (vp->v_mount != 0) && /* Only on nodes that have the size info */
3266 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
3267 size = vp->v_mount->mnt_stat.f_iosize;
3268 maxcl = maxphys / size;
3271 for (i = 1; i < maxcl; i++)
3272 if (vfs_bio_clcheck(vp, size, lblkno + i,
3273 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
3276 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
3277 if (vfs_bio_clcheck(vp, size, lblkno - j,
3278 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
3284 * this is a possible cluster write
3288 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
3294 bp->b_flags |= B_ASYNC;
3296 * default (old) behavior, writing out only one block
3298 * XXX returns b_bufsize instead of b_bcount for nwritten?
3300 nwritten = bp->b_bufsize;
3309 * Allocate KVA for an empty buf header according to gbflags.
3312 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
3315 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
3317 * In order to keep fragmentation sane we only allocate kva
3318 * in BKVASIZE chunks. XXX with vmem we can do page size.
3320 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
3322 if (maxsize != bp->b_kvasize &&
3323 bufkva_alloc(bp, maxsize, gbflags))
3332 * Find and initialize a new buffer header, freeing up existing buffers
3333 * in the bufqueues as necessary. The new buffer is returned locked.
3336 * We have insufficient buffer headers
3337 * We have insufficient buffer space
3338 * buffer_arena is too fragmented ( space reservation fails )
3339 * If we have to flush dirty buffers ( but we try to avoid this )
3341 * The caller is responsible for releasing the reserved bufspace after
3342 * allocbuf() is called.
3345 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
3347 struct bufdomain *bd;
3349 bool metadata, reserved;
3352 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3353 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3354 if (!unmapped_buf_allowed)
3355 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3357 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
3365 bd = &bdomain[vp->v_bufobj.bo_domain];
3367 counter_u64_add(getnewbufcalls, 1);
3370 if (reserved == false &&
3371 bufspace_reserve(bd, maxsize, metadata) != 0) {
3372 counter_u64_add(getnewbufrestarts, 1);
3376 if ((bp = buf_alloc(bd)) == NULL) {
3377 counter_u64_add(getnewbufrestarts, 1);
3380 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
3383 } while (buf_recycle(bd, false) == 0);
3386 bufspace_release(bd, maxsize);
3388 bp->b_flags |= B_INVAL;
3391 bufspace_wait(bd, vp, gbflags, slpflag, slptimeo);
3399 * buffer flushing daemon. Buffers are normally flushed by the
3400 * update daemon but if it cannot keep up this process starts to
3401 * take the load in an attempt to prevent getnewbuf() from blocking.
3403 static struct kproc_desc buf_kp = {
3408 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3411 buf_flush(struct vnode *vp, struct bufdomain *bd, int target)
3415 flushed = flushbufqueues(vp, bd, target, 0);
3418 * Could not find any buffers without rollback
3419 * dependencies, so just write the first one
3420 * in the hopes of eventually making progress.
3422 if (vp != NULL && target > 2)
3424 flushbufqueues(vp, bd, target, 1);
3430 buf_daemon_shutdown(void *arg __unused, int howto __unused)
3434 if (KERNEL_PANICKED())
3439 wakeup(&bd_request);
3440 error = msleep(&bd_shutdown, &bdlock, 0, "buf_daemon_shutdown",
3442 mtx_unlock(&bdlock);
3444 printf("bufdaemon wait error: %d\n", error);
3450 struct bufdomain *bd;
3456 * This process needs to be suspended prior to shutdown sync.
3458 EVENTHANDLER_REGISTER(shutdown_pre_sync, buf_daemon_shutdown, NULL,
3459 SHUTDOWN_PRI_LAST + 100);
3462 * Start the buf clean daemons as children threads.
3464 for (i = 0 ; i < buf_domains; i++) {
3467 error = kthread_add((void (*)(void *))bufspace_daemon,
3468 &bdomain[i], curproc, NULL, 0, 0, "bufspacedaemon-%d", i);
3470 panic("error %d spawning bufspace daemon", error);
3474 * This process is allowed to take the buffer cache to the limit
3476 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3478 while (!bd_shutdown) {
3480 mtx_unlock(&bdlock);
3483 * Save speedupreq for this pass and reset to capture new
3486 speedupreq = bd_speedupreq;
3490 * Flush each domain sequentially according to its level and
3491 * the speedup request.
3493 for (i = 0; i < buf_domains; i++) {
3496 lodirty = bd->bd_numdirtybuffers / 2;
3498 lodirty = bd->bd_lodirtybuffers;
3499 while (bd->bd_numdirtybuffers > lodirty) {
3500 if (buf_flush(NULL, bd,
3501 bd->bd_numdirtybuffers - lodirty) == 0)
3503 kern_yield(PRI_USER);
3508 * Only clear bd_request if we have reached our low water
3509 * mark. The buf_daemon normally waits 1 second and
3510 * then incrementally flushes any dirty buffers that have
3511 * built up, within reason.
3513 * If we were unable to hit our low water mark and couldn't
3514 * find any flushable buffers, we sleep for a short period
3515 * to avoid endless loops on unlockable buffers.
3520 if (BIT_EMPTY(BUF_DOMAINS, &bdlodirty)) {
3522 * We reached our low water mark, reset the
3523 * request and sleep until we are needed again.
3524 * The sleep is just so the suspend code works.
3528 * Do an extra wakeup in case dirty threshold
3529 * changed via sysctl and the explicit transition
3530 * out of shortfall was missed.
3533 if (runningbufspace <= lorunningspace)
3535 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3538 * We couldn't find any flushable dirty buffers but
3539 * still have too many dirty buffers, we
3540 * have to sleep and try again. (rare)
3542 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3545 wakeup(&bd_shutdown);
3546 mtx_unlock(&bdlock);
3553 * Try to flush a buffer in the dirty queue. We must be careful to
3554 * free up B_INVAL buffers instead of write them, which NFS is
3555 * particularly sensitive to.
3557 static int flushwithdeps = 0;
3558 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW | CTLFLAG_STATS,
3560 "Number of buffers flushed with dependencies that require rollbacks");
3563 flushbufqueues(struct vnode *lvp, struct bufdomain *bd, int target,
3566 struct bufqueue *bq;
3567 struct buf *sentinel;
3577 bq = &bd->bd_dirtyq;
3579 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3580 sentinel->b_qindex = QUEUE_SENTINEL;
3582 TAILQ_INSERT_HEAD(&bq->bq_queue, sentinel, b_freelist);
3584 while (flushed != target) {
3587 bp = TAILQ_NEXT(sentinel, b_freelist);
3589 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3590 TAILQ_INSERT_AFTER(&bq->bq_queue, bp, sentinel,
3597 * Skip sentinels inserted by other invocations of the
3598 * flushbufqueues(), taking care to not reorder them.
3600 * Only flush the buffers that belong to the
3601 * vnode locked by the curthread.
3603 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3608 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3614 * BKGRDINPROG can only be set with the buf and bufobj
3615 * locks both held. We tolerate a race to clear it here.
3617 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3618 (bp->b_flags & B_DELWRI) == 0) {
3622 if (bp->b_flags & B_INVAL) {
3629 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3630 if (flushdeps == 0) {
3638 * We must hold the lock on a vnode before writing
3639 * one of its buffers. Otherwise we may confuse, or
3640 * in the case of a snapshot vnode, deadlock the
3643 * The lock order here is the reverse of the normal
3644 * of vnode followed by buf lock. This is ok because
3645 * the NOWAIT will prevent deadlock.
3648 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3654 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3656 ASSERT_VOP_LOCKED(vp, "getbuf");
3658 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3659 vn_lock(vp, LK_TRYUPGRADE);
3662 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3663 bp, bp->b_vp, bp->b_flags);
3664 if (curproc == bufdaemonproc) {
3669 counter_u64_add(notbufdflushes, 1);
3671 vn_finished_write(mp);
3674 flushwithdeps += hasdeps;
3678 * Sleeping on runningbufspace while holding
3679 * vnode lock leads to deadlock.
3681 if (curproc == bufdaemonproc &&
3682 runningbufspace > hirunningspace)
3683 waitrunningbufspace();
3686 vn_finished_write(mp);
3690 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3692 free(sentinel, M_TEMP);
3697 * Check to see if a block is currently memory resident.
3700 incore(struct bufobj *bo, daddr_t blkno)
3702 return (gbincore_unlocked(bo, blkno));
3706 * Returns true if no I/O is needed to access the
3707 * associated VM object. This is like incore except
3708 * it also hunts around in the VM system for the data.
3711 inmem(struct vnode * vp, daddr_t blkno)
3714 vm_offset_t toff, tinc, size;
3719 ASSERT_VOP_LOCKED(vp, "inmem");
3721 if (incore(&vp->v_bufobj, blkno))
3723 if (vp->v_mount == NULL)
3730 if (size > vp->v_mount->mnt_stat.f_iosize)
3731 size = vp->v_mount->mnt_stat.f_iosize;
3732 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3734 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3735 m = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3741 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3742 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3744 * Consider page validity only if page mapping didn't change
3747 valid = vm_page_is_valid(m,
3748 (vm_offset_t)((toff + off) & PAGE_MASK), tinc);
3749 n = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3761 * Set the dirty range for a buffer based on the status of the dirty
3762 * bits in the pages comprising the buffer. The range is limited
3763 * to the size of the buffer.
3765 * Tell the VM system that the pages associated with this buffer
3766 * are clean. This is used for delayed writes where the data is
3767 * going to go to disk eventually without additional VM intevention.
3769 * Note that while we only really need to clean through to b_bcount, we
3770 * just go ahead and clean through to b_bufsize.
3773 vfs_clean_pages_dirty_buf(struct buf *bp)
3775 vm_ooffset_t foff, noff, eoff;
3779 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3782 foff = bp->b_offset;
3783 KASSERT(bp->b_offset != NOOFFSET,
3784 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3786 vfs_busy_pages_acquire(bp);
3787 vfs_setdirty_range(bp);
3788 for (i = 0; i < bp->b_npages; i++) {
3789 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3791 if (eoff > bp->b_offset + bp->b_bufsize)
3792 eoff = bp->b_offset + bp->b_bufsize;
3794 vfs_page_set_validclean(bp, foff, m);
3795 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3798 vfs_busy_pages_release(bp);
3802 vfs_setdirty_range(struct buf *bp)
3804 vm_offset_t boffset;
3805 vm_offset_t eoffset;
3809 * test the pages to see if they have been modified directly
3810 * by users through the VM system.
3812 for (i = 0; i < bp->b_npages; i++)
3813 vm_page_test_dirty(bp->b_pages[i]);
3816 * Calculate the encompassing dirty range, boffset and eoffset,
3817 * (eoffset - boffset) bytes.
3820 for (i = 0; i < bp->b_npages; i++) {
3821 if (bp->b_pages[i]->dirty)
3824 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3826 for (i = bp->b_npages - 1; i >= 0; --i) {
3827 if (bp->b_pages[i]->dirty) {
3831 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3834 * Fit it to the buffer.
3837 if (eoffset > bp->b_bcount)
3838 eoffset = bp->b_bcount;
3841 * If we have a good dirty range, merge with the existing
3845 if (boffset < eoffset) {
3846 if (bp->b_dirtyoff > boffset)
3847 bp->b_dirtyoff = boffset;
3848 if (bp->b_dirtyend < eoffset)
3849 bp->b_dirtyend = eoffset;
3854 * Allocate the KVA mapping for an existing buffer.
3855 * If an unmapped buffer is provided but a mapped buffer is requested, take
3856 * also care to properly setup mappings between pages and KVA.
3859 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3861 int bsize, maxsize, need_mapping, need_kva;
3864 need_mapping = bp->b_data == unmapped_buf &&
3865 (gbflags & GB_UNMAPPED) == 0;
3866 need_kva = bp->b_kvabase == unmapped_buf &&
3867 bp->b_data == unmapped_buf &&
3868 (gbflags & GB_KVAALLOC) != 0;
3869 if (!need_mapping && !need_kva)
3872 BUF_CHECK_UNMAPPED(bp);
3874 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3876 * Buffer is not mapped, but the KVA was already
3877 * reserved at the time of the instantiation. Use the
3884 * Calculate the amount of the address space we would reserve
3885 * if the buffer was mapped.
3887 bsize = vn_isdisk(bp->b_vp) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3888 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3889 offset = blkno * bsize;
3890 maxsize = size + (offset & PAGE_MASK);
3891 maxsize = imax(maxsize, bsize);
3893 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3894 if ((gbflags & GB_NOWAIT_BD) != 0) {
3896 * XXXKIB: defragmentation cannot
3897 * succeed, not sure what else to do.
3899 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3901 counter_u64_add(mappingrestarts, 1);
3902 bufspace_wait(bufdomain(bp), bp->b_vp, gbflags, 0, 0);
3906 /* b_offset is handled by bpmap_qenter. */
3907 bp->b_data = bp->b_kvabase;
3908 BUF_CHECK_MAPPED(bp);
3914 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3920 error = getblkx(vp, blkno, blkno, size, slpflag, slptimeo, flags, &bp);
3929 * Get a block given a specified block and offset into a file/device.
3930 * The buffers B_DONE bit will be cleared on return, making it almost
3931 * ready for an I/O initiation. B_INVAL may or may not be set on
3932 * return. The caller should clear B_INVAL prior to initiating a
3935 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3936 * an existing buffer.
3938 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3939 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3940 * and then cleared based on the backing VM. If the previous buffer is
3941 * non-0-sized but invalid, B_CACHE will be cleared.
3943 * If getblk() must create a new buffer, the new buffer is returned with
3944 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3945 * case it is returned with B_INVAL clear and B_CACHE set based on the
3948 * getblk() also forces a bwrite() for any B_DELWRI buffer whose
3949 * B_CACHE bit is clear.
3951 * What this means, basically, is that the caller should use B_CACHE to
3952 * determine whether the buffer is fully valid or not and should clear
3953 * B_INVAL prior to issuing a read. If the caller intends to validate
3954 * the buffer by loading its data area with something, the caller needs
3955 * to clear B_INVAL. If the caller does this without issuing an I/O,
3956 * the caller should set B_CACHE ( as an optimization ), else the caller
3957 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3958 * a write attempt or if it was a successful read. If the caller
3959 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3960 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3962 * The blkno parameter is the logical block being requested. Normally
3963 * the mapping of logical block number to disk block address is done
3964 * by calling VOP_BMAP(). However, if the mapping is already known, the
3965 * disk block address can be passed using the dblkno parameter. If the
3966 * disk block address is not known, then the same value should be passed
3967 * for blkno and dblkno.
3970 getblkx(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size, int slpflag,
3971 int slptimeo, int flags, struct buf **bpp)
3976 int bsize, error, maxsize, vmio;
3979 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3980 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3981 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3982 if (vp->v_type != VCHR)
3983 ASSERT_VOP_LOCKED(vp, "getblk");
3984 if (size > maxbcachebuf)
3985 panic("getblk: size(%d) > maxbcachebuf(%d)\n", size,
3987 if (!unmapped_buf_allowed)
3988 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3993 /* Attempt lockless lookup first. */
3994 bp = gbincore_unlocked(bo, blkno);
3997 * With GB_NOCREAT we must be sure about not finding the buffer
3998 * as it may have been reassigned during unlocked lookup.
4000 if ((flags & GB_NOCREAT) != 0)
4002 goto newbuf_unlocked;
4005 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL, "getblku", 0,
4010 /* Verify buf identify has not changed since lookup. */
4011 if (bp->b_bufobj == bo && bp->b_lblkno == blkno)
4012 goto foundbuf_fastpath;
4014 /* It changed, fallback to locked lookup. */
4019 bp = gbincore(bo, blkno);
4024 * Buffer is in-core. If the buffer is not busy nor managed,
4025 * it must be on a queue.
4027 lockflags = LK_EXCLUSIVE | LK_INTERLOCK |
4028 ((flags & GB_LOCK_NOWAIT) != 0 ? LK_NOWAIT : LK_SLEEPFAIL);
4030 lockflags |= (flags & GB_NOWITNESS) != 0 ? LK_NOWITNESS : 0;
4033 error = BUF_TIMELOCK(bp, lockflags,
4034 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
4037 * If we slept and got the lock we have to restart in case
4038 * the buffer changed identities.
4040 if (error == ENOLCK)
4042 /* We timed out or were interrupted. */
4043 else if (error != 0)
4047 /* If recursed, assume caller knows the rules. */
4048 if (BUF_LOCKRECURSED(bp))
4052 * The buffer is locked. B_CACHE is cleared if the buffer is
4053 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
4054 * and for a VMIO buffer B_CACHE is adjusted according to the
4057 if (bp->b_flags & B_INVAL)
4058 bp->b_flags &= ~B_CACHE;
4059 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
4060 bp->b_flags |= B_CACHE;
4061 if (bp->b_flags & B_MANAGED)
4062 MPASS(bp->b_qindex == QUEUE_NONE);
4067 * check for size inconsistencies for non-VMIO case.
4069 if (bp->b_bcount != size) {
4070 if ((bp->b_flags & B_VMIO) == 0 ||
4071 (size > bp->b_kvasize)) {
4072 if (bp->b_flags & B_DELWRI) {
4073 bp->b_flags |= B_NOCACHE;
4076 if (LIST_EMPTY(&bp->b_dep)) {
4077 bp->b_flags |= B_RELBUF;
4080 bp->b_flags |= B_NOCACHE;
4089 * Handle the case of unmapped buffer which should
4090 * become mapped, or the buffer for which KVA
4091 * reservation is requested.
4093 bp_unmapped_get_kva(bp, blkno, size, flags);
4096 * If the size is inconsistent in the VMIO case, we can resize
4097 * the buffer. This might lead to B_CACHE getting set or
4098 * cleared. If the size has not changed, B_CACHE remains
4099 * unchanged from its previous state.
4103 KASSERT(bp->b_offset != NOOFFSET,
4104 ("getblk: no buffer offset"));
4107 * A buffer with B_DELWRI set and B_CACHE clear must
4108 * be committed before we can return the buffer in
4109 * order to prevent the caller from issuing a read
4110 * ( due to B_CACHE not being set ) and overwriting
4113 * Most callers, including NFS and FFS, need this to
4114 * operate properly either because they assume they
4115 * can issue a read if B_CACHE is not set, or because
4116 * ( for example ) an uncached B_DELWRI might loop due
4117 * to softupdates re-dirtying the buffer. In the latter
4118 * case, B_CACHE is set after the first write completes,
4119 * preventing further loops.
4120 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
4121 * above while extending the buffer, we cannot allow the
4122 * buffer to remain with B_CACHE set after the write
4123 * completes or it will represent a corrupt state. To
4124 * deal with this we set B_NOCACHE to scrap the buffer
4127 * We might be able to do something fancy, like setting
4128 * B_CACHE in bwrite() except if B_DELWRI is already set,
4129 * so the below call doesn't set B_CACHE, but that gets real
4130 * confusing. This is much easier.
4133 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
4134 bp->b_flags |= B_NOCACHE;
4138 bp->b_flags &= ~B_DONE;
4141 * Buffer is not in-core, create new buffer. The buffer
4142 * returned by getnewbuf() is locked. Note that the returned
4143 * buffer is also considered valid (not marked B_INVAL).
4148 * If the user does not want us to create the buffer, bail out
4151 if (flags & GB_NOCREAT)
4154 bsize = vn_isdisk(vp) ? DEV_BSIZE : bo->bo_bsize;
4155 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
4156 offset = blkno * bsize;
4157 vmio = vp->v_object != NULL;
4159 maxsize = size + (offset & PAGE_MASK);
4162 /* Do not allow non-VMIO notmapped buffers. */
4163 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
4165 maxsize = imax(maxsize, bsize);
4166 if ((flags & GB_NOSPARSE) != 0 && vmio &&
4168 error = VOP_BMAP(vp, blkno, NULL, &d_blkno, 0, 0);
4169 KASSERT(error != EOPNOTSUPP,
4170 ("GB_NOSPARSE from fs not supporting bmap, vp %p",
4175 return (EJUSTRETURN);
4178 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
4180 if (slpflag || slptimeo)
4183 * XXX This is here until the sleep path is diagnosed
4184 * enough to work under very low memory conditions.
4186 * There's an issue on low memory, 4BSD+non-preempt
4187 * systems (eg MIPS routers with 32MB RAM) where buffer
4188 * exhaustion occurs without sleeping for buffer
4189 * reclaimation. This just sticks in a loop and
4190 * constantly attempts to allocate a buffer, which
4191 * hits exhaustion and tries to wakeup bufdaemon.
4192 * This never happens because we never yield.
4194 * The real solution is to identify and fix these cases
4195 * so we aren't effectively busy-waiting in a loop
4196 * until the reclaimation path has cycles to run.
4198 kern_yield(PRI_USER);
4203 * This code is used to make sure that a buffer is not
4204 * created while the getnewbuf routine is blocked.
4205 * This can be a problem whether the vnode is locked or not.
4206 * If the buffer is created out from under us, we have to
4207 * throw away the one we just created.
4209 * Note: this must occur before we associate the buffer
4210 * with the vp especially considering limitations in
4211 * the splay tree implementation when dealing with duplicate
4215 if (gbincore(bo, blkno)) {
4217 bp->b_flags |= B_INVAL;
4218 bufspace_release(bufdomain(bp), maxsize);
4224 * Insert the buffer into the hash, so that it can
4225 * be found by incore.
4227 bp->b_lblkno = blkno;
4228 bp->b_blkno = d_blkno;
4229 bp->b_offset = offset;
4234 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
4235 * buffer size starts out as 0, B_CACHE will be set by
4236 * allocbuf() for the VMIO case prior to it testing the
4237 * backing store for validity.
4241 bp->b_flags |= B_VMIO;
4242 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
4243 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
4244 bp, vp->v_object, bp->b_bufobj->bo_object));
4246 bp->b_flags &= ~B_VMIO;
4247 KASSERT(bp->b_bufobj->bo_object == NULL,
4248 ("ARGH! has b_bufobj->bo_object %p %p\n",
4249 bp, bp->b_bufobj->bo_object));
4250 BUF_CHECK_MAPPED(bp);
4254 bufspace_release(bufdomain(bp), maxsize);
4255 bp->b_flags &= ~B_DONE;
4257 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
4259 buf_track(bp, __func__);
4260 KASSERT(bp->b_bufobj == bo,
4261 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
4267 * Get an empty, disassociated buffer of given size. The buffer is initially
4271 geteblk(int size, int flags)
4276 maxsize = (size + BKVAMASK) & ~BKVAMASK;
4277 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
4278 if ((flags & GB_NOWAIT_BD) &&
4279 (curthread->td_pflags & TDP_BUFNEED) != 0)
4283 bufspace_release(bufdomain(bp), maxsize);
4284 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
4289 * Truncate the backing store for a non-vmio buffer.
4292 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
4295 if (bp->b_flags & B_MALLOC) {
4297 * malloced buffers are not shrunk
4299 if (newbsize == 0) {
4300 bufmallocadjust(bp, 0);
4301 free(bp->b_data, M_BIOBUF);
4302 bp->b_data = bp->b_kvabase;
4303 bp->b_flags &= ~B_MALLOC;
4307 vm_hold_free_pages(bp, newbsize);
4308 bufspace_adjust(bp, newbsize);
4312 * Extend the backing for a non-VMIO buffer.
4315 vfs_nonvmio_extend(struct buf *bp, int newbsize)
4321 * We only use malloced memory on the first allocation.
4322 * and revert to page-allocated memory when the buffer
4325 * There is a potential smp race here that could lead
4326 * to bufmallocspace slightly passing the max. It
4327 * is probably extremely rare and not worth worrying
4330 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
4331 bufmallocspace < maxbufmallocspace) {
4332 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
4333 bp->b_flags |= B_MALLOC;
4334 bufmallocadjust(bp, newbsize);
4339 * If the buffer is growing on its other-than-first
4340 * allocation then we revert to the page-allocation
4345 if (bp->b_flags & B_MALLOC) {
4346 origbuf = bp->b_data;
4347 origbufsize = bp->b_bufsize;
4348 bp->b_data = bp->b_kvabase;
4349 bufmallocadjust(bp, 0);
4350 bp->b_flags &= ~B_MALLOC;
4351 newbsize = round_page(newbsize);
4353 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
4354 (vm_offset_t) bp->b_data + newbsize);
4355 if (origbuf != NULL) {
4356 bcopy(origbuf, bp->b_data, origbufsize);
4357 free(origbuf, M_BIOBUF);
4359 bufspace_adjust(bp, newbsize);
4363 * This code constitutes the buffer memory from either anonymous system
4364 * memory (in the case of non-VMIO operations) or from an associated
4365 * VM object (in the case of VMIO operations). This code is able to
4366 * resize a buffer up or down.
4368 * Note that this code is tricky, and has many complications to resolve
4369 * deadlock or inconsistent data situations. Tread lightly!!!
4370 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
4371 * the caller. Calling this code willy nilly can result in the loss of data.
4373 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
4374 * B_CACHE for the non-VMIO case.
4377 allocbuf(struct buf *bp, int size)
4381 if (bp->b_bcount == size)
4384 KASSERT(bp->b_kvasize == 0 || bp->b_kvasize >= size,
4385 ("allocbuf: buffer too small %p %#x %#x",
4386 bp, bp->b_kvasize, size));
4388 newbsize = roundup2(size, DEV_BSIZE);
4389 if ((bp->b_flags & B_VMIO) == 0) {
4390 if ((bp->b_flags & B_MALLOC) == 0)
4391 newbsize = round_page(newbsize);
4393 * Just get anonymous memory from the kernel. Don't
4394 * mess with B_CACHE.
4396 if (newbsize < bp->b_bufsize)
4397 vfs_nonvmio_truncate(bp, newbsize);
4398 else if (newbsize > bp->b_bufsize)
4399 vfs_nonvmio_extend(bp, newbsize);
4403 desiredpages = size == 0 ? 0 :
4404 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
4406 KASSERT((bp->b_flags & B_MALLOC) == 0,
4407 ("allocbuf: VMIO buffer can't be malloced %p", bp));
4410 * Set B_CACHE initially if buffer is 0 length or will become
4413 if (size == 0 || bp->b_bufsize == 0)
4414 bp->b_flags |= B_CACHE;
4416 if (newbsize < bp->b_bufsize)
4417 vfs_vmio_truncate(bp, desiredpages);
4418 /* XXX This looks as if it should be newbsize > b_bufsize */
4419 else if (size > bp->b_bcount)
4420 vfs_vmio_extend(bp, desiredpages, size);
4421 bufspace_adjust(bp, newbsize);
4423 bp->b_bcount = size; /* requested buffer size. */
4427 extern int inflight_transient_maps;
4429 static struct bio_queue nondump_bios;
4432 biodone(struct bio *bp)
4435 void (*done)(struct bio *);
4436 vm_offset_t start, end;
4438 biotrack(bp, __func__);
4441 * Avoid completing I/O when dumping after a panic since that may
4442 * result in a deadlock in the filesystem or pager code. Note that
4443 * this doesn't affect dumps that were started manually since we aim
4444 * to keep the system usable after it has been resumed.
4446 if (__predict_false(dumping && SCHEDULER_STOPPED())) {
4447 TAILQ_INSERT_HEAD(&nondump_bios, bp, bio_queue);
4450 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
4451 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
4452 bp->bio_flags |= BIO_UNMAPPED;
4453 start = trunc_page((vm_offset_t)bp->bio_data);
4454 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
4455 bp->bio_data = unmapped_buf;
4456 pmap_qremove(start, atop(end - start));
4457 vmem_free(transient_arena, start, end - start);
4458 atomic_add_int(&inflight_transient_maps, -1);
4460 done = bp->bio_done;
4462 * The check for done == biodone is to allow biodone to be
4463 * used as a bio_done routine.
4465 if (done == NULL || done == biodone) {
4466 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4468 bp->bio_flags |= BIO_DONE;
4476 * Wait for a BIO to finish.
4479 biowait(struct bio *bp, const char *wmesg)
4483 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4485 while ((bp->bio_flags & BIO_DONE) == 0)
4486 msleep(bp, mtxp, PRIBIO, wmesg, 0);
4488 if (bp->bio_error != 0)
4489 return (bp->bio_error);
4490 if (!(bp->bio_flags & BIO_ERROR))
4496 biofinish(struct bio *bp, struct devstat *stat, int error)
4500 bp->bio_error = error;
4501 bp->bio_flags |= BIO_ERROR;
4504 devstat_end_transaction_bio(stat, bp);
4508 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4510 biotrack_buf(struct bio *bp, const char *location)
4513 buf_track(bp->bio_track_bp, location);
4520 * Wait for buffer I/O completion, returning error status. The buffer
4521 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
4522 * error and cleared.
4525 bufwait(struct buf *bp)
4527 if (bp->b_iocmd == BIO_READ)
4528 bwait(bp, PRIBIO, "biord");
4530 bwait(bp, PRIBIO, "biowr");
4531 if (bp->b_flags & B_EINTR) {
4532 bp->b_flags &= ~B_EINTR;
4535 if (bp->b_ioflags & BIO_ERROR) {
4536 return (bp->b_error ? bp->b_error : EIO);
4545 * Finish I/O on a buffer, optionally calling a completion function.
4546 * This is usually called from an interrupt so process blocking is
4549 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4550 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
4551 * assuming B_INVAL is clear.
4553 * For the VMIO case, we set B_CACHE if the op was a read and no
4554 * read error occurred, or if the op was a write. B_CACHE is never
4555 * set if the buffer is invalid or otherwise uncacheable.
4557 * bufdone does not mess with B_INVAL, allowing the I/O routine or the
4558 * initiator to leave B_INVAL set to brelse the buffer out of existence
4559 * in the biodone routine.
4562 bufdone(struct buf *bp)
4564 struct bufobj *dropobj;
4565 void (*biodone)(struct buf *);
4567 buf_track(bp, __func__);
4568 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4571 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4573 runningbufwakeup(bp);
4574 if (bp->b_iocmd == BIO_WRITE)
4575 dropobj = bp->b_bufobj;
4576 /* call optional completion function if requested */
4577 if (bp->b_iodone != NULL) {
4578 biodone = bp->b_iodone;
4579 bp->b_iodone = NULL;
4582 bufobj_wdrop(dropobj);
4585 if (bp->b_flags & B_VMIO) {
4587 * Set B_CACHE if the op was a normal read and no error
4588 * occurred. B_CACHE is set for writes in the b*write()
4591 if (bp->b_iocmd == BIO_READ &&
4592 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4593 !(bp->b_ioflags & BIO_ERROR))
4594 bp->b_flags |= B_CACHE;
4595 vfs_vmio_iodone(bp);
4597 if (!LIST_EMPTY(&bp->b_dep))
4599 if ((bp->b_flags & B_CKHASH) != 0) {
4600 KASSERT(bp->b_iocmd == BIO_READ,
4601 ("bufdone: b_iocmd %d not BIO_READ", bp->b_iocmd));
4602 KASSERT(buf_mapped(bp), ("bufdone: bp %p not mapped", bp));
4603 (*bp->b_ckhashcalc)(bp);
4606 * For asynchronous completions, release the buffer now. The brelse
4607 * will do a wakeup there if necessary - so no need to do a wakeup
4608 * here in the async case. The sync case always needs to do a wakeup.
4610 if (bp->b_flags & B_ASYNC) {
4611 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4612 (bp->b_ioflags & BIO_ERROR))
4619 bufobj_wdrop(dropobj);
4623 * This routine is called in lieu of iodone in the case of
4624 * incomplete I/O. This keeps the busy status for pages
4628 vfs_unbusy_pages(struct buf *bp)
4634 runningbufwakeup(bp);
4635 if (!(bp->b_flags & B_VMIO))
4638 obj = bp->b_bufobj->bo_object;
4639 for (i = 0; i < bp->b_npages; i++) {
4641 if (m == bogus_page) {
4642 m = vm_page_relookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4644 panic("vfs_unbusy_pages: page missing\n");
4646 if (buf_mapped(bp)) {
4647 BUF_CHECK_MAPPED(bp);
4648 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4649 bp->b_pages, bp->b_npages);
4651 BUF_CHECK_UNMAPPED(bp);
4655 vm_object_pip_wakeupn(obj, bp->b_npages);
4659 * vfs_page_set_valid:
4661 * Set the valid bits in a page based on the supplied offset. The
4662 * range is restricted to the buffer's size.
4664 * This routine is typically called after a read completes.
4667 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4672 * Compute the end offset, eoff, such that [off, eoff) does not span a
4673 * page boundary and eoff is not greater than the end of the buffer.
4674 * The end of the buffer, in this case, is our file EOF, not the
4675 * allocation size of the buffer.
4677 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4678 if (eoff > bp->b_offset + bp->b_bcount)
4679 eoff = bp->b_offset + bp->b_bcount;
4682 * Set valid range. This is typically the entire buffer and thus the
4686 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4690 * vfs_page_set_validclean:
4692 * Set the valid bits and clear the dirty bits in a page based on the
4693 * supplied offset. The range is restricted to the buffer's size.
4696 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4698 vm_ooffset_t soff, eoff;
4701 * Start and end offsets in buffer. eoff - soff may not cross a
4702 * page boundary or cross the end of the buffer. The end of the
4703 * buffer, in this case, is our file EOF, not the allocation size
4707 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4708 if (eoff > bp->b_offset + bp->b_bcount)
4709 eoff = bp->b_offset + bp->b_bcount;
4712 * Set valid range. This is typically the entire buffer and thus the
4716 vm_page_set_validclean(
4718 (vm_offset_t) (soff & PAGE_MASK),
4719 (vm_offset_t) (eoff - soff)
4725 * Acquire a shared busy on all pages in the buf.
4728 vfs_busy_pages_acquire(struct buf *bp)
4732 for (i = 0; i < bp->b_npages; i++)
4733 vm_page_busy_acquire(bp->b_pages[i], VM_ALLOC_SBUSY);
4737 vfs_busy_pages_release(struct buf *bp)
4741 for (i = 0; i < bp->b_npages; i++)
4742 vm_page_sunbusy(bp->b_pages[i]);
4746 * This routine is called before a device strategy routine.
4747 * It is used to tell the VM system that paging I/O is in
4748 * progress, and treat the pages associated with the buffer
4749 * almost as being exclusive busy. Also the object paging_in_progress
4750 * flag is handled to make sure that the object doesn't become
4753 * Since I/O has not been initiated yet, certain buffer flags
4754 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4755 * and should be ignored.
4758 vfs_busy_pages(struct buf *bp, int clear_modify)
4766 if (!(bp->b_flags & B_VMIO))
4769 obj = bp->b_bufobj->bo_object;
4770 foff = bp->b_offset;
4771 KASSERT(bp->b_offset != NOOFFSET,
4772 ("vfs_busy_pages: no buffer offset"));
4773 if ((bp->b_flags & B_CLUSTER) == 0) {
4774 vm_object_pip_add(obj, bp->b_npages);
4775 vfs_busy_pages_acquire(bp);
4777 if (bp->b_bufsize != 0)
4778 vfs_setdirty_range(bp);
4780 for (i = 0; i < bp->b_npages; i++) {
4782 vm_page_assert_sbusied(m);
4785 * When readying a buffer for a read ( i.e
4786 * clear_modify == 0 ), it is important to do
4787 * bogus_page replacement for valid pages in
4788 * partially instantiated buffers. Partially
4789 * instantiated buffers can, in turn, occur when
4790 * reconstituting a buffer from its VM backing store
4791 * base. We only have to do this if B_CACHE is
4792 * clear ( which causes the I/O to occur in the
4793 * first place ). The replacement prevents the read
4794 * I/O from overwriting potentially dirty VM-backed
4795 * pages. XXX bogus page replacement is, uh, bogus.
4796 * It may not work properly with small-block devices.
4797 * We need to find a better way.
4800 pmap_remove_write(m);
4801 vfs_page_set_validclean(bp, foff, m);
4802 } else if (vm_page_all_valid(m) &&
4803 (bp->b_flags & B_CACHE) == 0) {
4804 bp->b_pages[i] = bogus_page;
4807 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4809 if (bogus && buf_mapped(bp)) {
4810 BUF_CHECK_MAPPED(bp);
4811 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4812 bp->b_pages, bp->b_npages);
4817 * vfs_bio_set_valid:
4819 * Set the range within the buffer to valid. The range is
4820 * relative to the beginning of the buffer, b_offset. Note that
4821 * b_offset itself may be offset from the beginning of the first
4825 vfs_bio_set_valid(struct buf *bp, int base, int size)
4830 if (!(bp->b_flags & B_VMIO))
4834 * Fixup base to be relative to beginning of first page.
4835 * Set initial n to be the maximum number of bytes in the
4836 * first page that can be validated.
4838 base += (bp->b_offset & PAGE_MASK);
4839 n = PAGE_SIZE - (base & PAGE_MASK);
4842 * Busy may not be strictly necessary here because the pages are
4843 * unlikely to be fully valid and the vnode lock will synchronize
4844 * their access via getpages. It is grabbed for consistency with
4845 * other page validation.
4847 vfs_busy_pages_acquire(bp);
4848 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4852 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4857 vfs_busy_pages_release(bp);
4863 * If the specified buffer is a non-VMIO buffer, clear the entire
4864 * buffer. If the specified buffer is a VMIO buffer, clear and
4865 * validate only the previously invalid portions of the buffer.
4866 * This routine essentially fakes an I/O, so we need to clear
4867 * BIO_ERROR and B_INVAL.
4869 * Note that while we only theoretically need to clear through b_bcount,
4870 * we go ahead and clear through b_bufsize.
4873 vfs_bio_clrbuf(struct buf *bp)
4875 int i, j, sa, ea, slide, zbits;
4876 vm_page_bits_t mask;
4878 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4882 bp->b_flags &= ~B_INVAL;
4883 bp->b_ioflags &= ~BIO_ERROR;
4884 vfs_busy_pages_acquire(bp);
4885 sa = bp->b_offset & PAGE_MASK;
4887 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4888 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4889 ea = slide & PAGE_MASK;
4892 if (bp->b_pages[i] == bogus_page)
4895 zbits = (sizeof(vm_page_bits_t) * NBBY) -
4896 (ea - sa) / DEV_BSIZE;
4897 mask = (VM_PAGE_BITS_ALL >> zbits) << j;
4898 if ((bp->b_pages[i]->valid & mask) == mask)
4900 if ((bp->b_pages[i]->valid & mask) == 0)
4901 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4903 for (; sa < ea; sa += DEV_BSIZE, j++) {
4904 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4905 pmap_zero_page_area(bp->b_pages[i],
4910 vm_page_set_valid_range(bp->b_pages[i], j * DEV_BSIZE,
4911 roundup2(ea - sa, DEV_BSIZE));
4913 vfs_busy_pages_release(bp);
4918 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4923 if (buf_mapped(bp)) {
4924 BUF_CHECK_MAPPED(bp);
4925 bzero(bp->b_data + base, size);
4927 BUF_CHECK_UNMAPPED(bp);
4928 n = PAGE_SIZE - (base & PAGE_MASK);
4929 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4933 pmap_zero_page_area(m, base & PAGE_MASK, n);
4942 * Update buffer flags based on I/O request parameters, optionally releasing the
4943 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM,
4944 * where they may be placed on a page queue (VMIO) or freed immediately (direct
4945 * I/O). Otherwise the buffer is released to the cache.
4948 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4951 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4952 ("buf %p non-VMIO noreuse", bp));
4954 if ((ioflag & IO_DIRECT) != 0)
4955 bp->b_flags |= B_DIRECT;
4956 if ((ioflag & IO_EXT) != 0)
4957 bp->b_xflags |= BX_ALTDATA;
4958 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4959 bp->b_flags |= B_RELBUF;
4960 if ((ioflag & IO_NOREUSE) != 0)
4961 bp->b_flags |= B_NOREUSE;
4969 vfs_bio_brelse(struct buf *bp, int ioflag)
4972 b_io_dismiss(bp, ioflag, true);
4976 vfs_bio_set_flags(struct buf *bp, int ioflag)
4979 b_io_dismiss(bp, ioflag, false);
4983 * vm_hold_load_pages and vm_hold_free_pages get pages into
4984 * a buffers address space. The pages are anonymous and are
4985 * not associated with a file object.
4988 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4994 BUF_CHECK_MAPPED(bp);
4996 to = round_page(to);
4997 from = round_page(from);
4998 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4999 MPASS((bp->b_flags & B_MAXPHYS) == 0);
5000 KASSERT(to - from <= maxbcachebuf,
5001 ("vm_hold_load_pages too large %p %#jx %#jx %u",
5002 bp, (uintmax_t)from, (uintmax_t)to, maxbcachebuf));
5004 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
5006 * note: must allocate system pages since blocking here
5007 * could interfere with paging I/O, no matter which
5010 p = vm_page_alloc_noobj(VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
5011 VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) | VM_ALLOC_WAITOK);
5012 pmap_qenter(pg, &p, 1);
5013 bp->b_pages[index] = p;
5015 bp->b_npages = index;
5018 /* Return pages associated with this buf to the vm system */
5020 vm_hold_free_pages(struct buf *bp, int newbsize)
5024 int index, newnpages;
5026 BUF_CHECK_MAPPED(bp);
5028 from = round_page((vm_offset_t)bp->b_data + newbsize);
5029 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
5030 if (bp->b_npages > newnpages)
5031 pmap_qremove(from, bp->b_npages - newnpages);
5032 for (index = newnpages; index < bp->b_npages; index++) {
5033 p = bp->b_pages[index];
5034 bp->b_pages[index] = NULL;
5035 vm_page_unwire_noq(p);
5038 bp->b_npages = newnpages;
5042 * Map an IO request into kernel virtual address space.
5044 * All requests are (re)mapped into kernel VA space.
5045 * Notice that we use b_bufsize for the size of the buffer
5046 * to be mapped. b_bcount might be modified by the driver.
5048 * Note that even if the caller determines that the address space should
5049 * be valid, a race or a smaller-file mapped into a larger space may
5050 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
5051 * check the return value.
5053 * This function only works with pager buffers.
5056 vmapbuf(struct buf *bp, void *uaddr, size_t len, int mapbuf)
5061 MPASS((bp->b_flags & B_MAXPHYS) != 0);
5062 prot = VM_PROT_READ;
5063 if (bp->b_iocmd == BIO_READ)
5064 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
5065 pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
5066 (vm_offset_t)uaddr, len, prot, bp->b_pages, PBUF_PAGES);
5069 bp->b_bufsize = len;
5070 bp->b_npages = pidx;
5071 bp->b_offset = ((vm_offset_t)uaddr) & PAGE_MASK;
5072 if (mapbuf || !unmapped_buf_allowed) {
5073 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
5074 bp->b_data = bp->b_kvabase + bp->b_offset;
5076 bp->b_data = unmapped_buf;
5081 * Free the io map PTEs associated with this IO operation.
5082 * We also invalidate the TLB entries and restore the original b_addr.
5084 * This function only works with pager buffers.
5087 vunmapbuf(struct buf *bp)
5091 npages = bp->b_npages;
5093 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
5094 vm_page_unhold_pages(bp->b_pages, npages);
5096 bp->b_data = unmapped_buf;
5100 bdone(struct buf *bp)
5104 mtxp = mtx_pool_find(mtxpool_sleep, bp);
5106 bp->b_flags |= B_DONE;
5112 bwait(struct buf *bp, u_char pri, const char *wchan)
5116 mtxp = mtx_pool_find(mtxpool_sleep, bp);
5118 while ((bp->b_flags & B_DONE) == 0)
5119 msleep(bp, mtxp, pri, wchan, 0);
5124 bufsync(struct bufobj *bo, int waitfor)
5127 return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
5131 bufstrategy(struct bufobj *bo, struct buf *bp)
5137 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
5138 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
5139 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
5140 i = VOP_STRATEGY(vp, bp);
5141 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
5145 * Initialize a struct bufobj before use. Memory is assumed zero filled.
5148 bufobj_init(struct bufobj *bo, void *private)
5150 static volatile int bufobj_cleanq;
5153 atomic_fetchadd_int(&bufobj_cleanq, 1) % buf_domains;
5154 rw_init(BO_LOCKPTR(bo), "bufobj interlock");
5155 bo->bo_private = private;
5156 TAILQ_INIT(&bo->bo_clean.bv_hd);
5157 pctrie_init(&bo->bo_clean.bv_root);
5158 TAILQ_INIT(&bo->bo_dirty.bv_hd);
5159 pctrie_init(&bo->bo_dirty.bv_root);
5163 bufobj_wrefl(struct bufobj *bo)
5166 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5167 ASSERT_BO_WLOCKED(bo);
5172 bufobj_wref(struct bufobj *bo)
5175 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5182 bufobj_wdrop(struct bufobj *bo)
5185 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
5187 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
5188 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
5189 bo->bo_flag &= ~BO_WWAIT;
5190 wakeup(&bo->bo_numoutput);
5196 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
5200 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
5201 ASSERT_BO_WLOCKED(bo);
5203 while (bo->bo_numoutput) {
5204 bo->bo_flag |= BO_WWAIT;
5205 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
5206 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
5214 * Set bio_data or bio_ma for struct bio from the struct buf.
5217 bdata2bio(struct buf *bp, struct bio *bip)
5220 if (!buf_mapped(bp)) {
5221 KASSERT(unmapped_buf_allowed, ("unmapped"));
5222 bip->bio_ma = bp->b_pages;
5223 bip->bio_ma_n = bp->b_npages;
5224 bip->bio_data = unmapped_buf;
5225 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
5226 bip->bio_flags |= BIO_UNMAPPED;
5227 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
5228 PAGE_SIZE == bp->b_npages,
5229 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
5230 (long long)bip->bio_length, bip->bio_ma_n));
5232 bip->bio_data = bp->b_data;
5238 memdesc_bio(struct bio *bio)
5240 if ((bio->bio_flags & BIO_VLIST) != 0)
5241 return (memdesc_vlist((struct bus_dma_segment *)bio->bio_data,
5244 if ((bio->bio_flags & BIO_UNMAPPED) != 0)
5245 return (memdesc_vmpages(bio->bio_ma, bio->bio_bcount,
5246 bio->bio_ma_offset));
5248 return (memdesc_vaddr(bio->bio_data, bio->bio_bcount));
5251 static int buf_pager_relbuf;
5252 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
5253 &buf_pager_relbuf, 0,
5254 "Make buffer pager release buffers after reading");
5257 * The buffer pager. It uses buffer reads to validate pages.
5259 * In contrast to the generic local pager from vm/vnode_pager.c, this
5260 * pager correctly and easily handles volumes where the underlying
5261 * device block size is greater than the machine page size. The
5262 * buffer cache transparently extends the requested page run to be
5263 * aligned at the block boundary, and does the necessary bogus page
5264 * replacements in the addends to avoid obliterating already valid
5267 * The only non-trivial issue is that the exclusive busy state for
5268 * pages, which is assumed by the vm_pager_getpages() interface, is
5269 * incompatible with the VMIO buffer cache's desire to share-busy the
5270 * pages. This function performs a trivial downgrade of the pages'
5271 * state before reading buffers, and a less trivial upgrade from the
5272 * shared-busy to excl-busy state after the read.
5275 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
5276 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
5277 vbg_get_blksize_t get_blksize)
5284 vm_ooffset_t la, lb, poff, poffe;
5286 int br_flags, error, i, pgsin, pgsin_a, pgsin_b;
5289 object = vp->v_object;
5292 la = IDX_TO_OFF(ma[count - 1]->pindex);
5293 if (la >= object->un_pager.vnp.vnp_size)
5294 return (VM_PAGER_BAD);
5297 * Change the meaning of la from where the last requested page starts
5298 * to where it ends, because that's the end of the requested region
5299 * and the start of the potential read-ahead region.
5302 lpart = la > object->un_pager.vnp.vnp_size;
5303 error = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)),
5306 return (VM_PAGER_ERROR);
5309 * Calculate read-ahead, behind and total pages.
5312 lb = IDX_TO_OFF(ma[0]->pindex);
5313 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
5315 if (rbehind != NULL)
5317 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
5318 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
5319 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
5324 VM_CNT_INC(v_vnodein);
5325 VM_CNT_ADD(v_vnodepgsin, pgsin);
5327 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
5328 != 0) ? GB_UNMAPPED : 0;
5330 for (i = 0; i < count; i++) {
5331 if (ma[i] != bogus_page)
5332 vm_page_busy_downgrade(ma[i]);
5336 for (i = 0; i < count; i++) {
5338 if (m == bogus_page)
5342 * Pages are shared busy and the object lock is not
5343 * owned, which together allow for the pages'
5344 * invalidation. The racy test for validity avoids
5345 * useless creation of the buffer for the most typical
5346 * case when invalidation is not used in redo or for
5347 * parallel read. The shared->excl upgrade loop at
5348 * the end of the function catches the race in a
5349 * reliable way (protected by the object lock).
5351 if (vm_page_all_valid(m))
5354 poff = IDX_TO_OFF(m->pindex);
5355 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
5356 for (; poff < poffe; poff += bsize) {
5357 lbn = get_lblkno(vp, poff);
5362 error = get_blksize(vp, lbn, &bsize);
5364 error = bread_gb(vp, lbn, bsize,
5365 curthread->td_ucred, br_flags, &bp);
5368 if (bp->b_rcred == curthread->td_ucred) {
5369 crfree(bp->b_rcred);
5370 bp->b_rcred = NOCRED;
5372 if (LIST_EMPTY(&bp->b_dep)) {
5374 * Invalidation clears m->valid, but
5375 * may leave B_CACHE flag if the
5376 * buffer existed at the invalidation
5377 * time. In this case, recycle the
5378 * buffer to do real read on next
5379 * bread() after redo.
5381 * Otherwise B_RELBUF is not strictly
5382 * necessary, enable to reduce buf
5385 if (buf_pager_relbuf ||
5386 !vm_page_all_valid(m))
5387 bp->b_flags |= B_RELBUF;
5389 bp->b_flags &= ~B_NOCACHE;
5395 KASSERT(1 /* racy, enable for debugging */ ||
5396 vm_page_all_valid(m) || i == count - 1,
5397 ("buf %d %p invalid", i, m));
5398 if (i == count - 1 && lpart) {
5399 if (!vm_page_none_valid(m) &&
5400 !vm_page_all_valid(m))
5401 vm_page_zero_invalid(m, TRUE);
5408 for (i = 0; i < count; i++) {
5409 if (ma[i] == bogus_page)
5411 if (vm_page_busy_tryupgrade(ma[i]) == 0) {
5412 vm_page_sunbusy(ma[i]);
5413 ma[i] = vm_page_grab_unlocked(object, ma[i]->pindex,
5418 * Since the pages were only sbusy while neither the
5419 * buffer nor the object lock was held by us, or
5420 * reallocated while vm_page_grab() slept for busy
5421 * relinguish, they could have been invalidated.
5422 * Recheck the valid bits and re-read as needed.
5424 * Note that the last page is made fully valid in the
5425 * read loop, and partial validity for the page at
5426 * index count - 1 could mean that the page was
5427 * invalidated or removed, so we must restart for
5430 if (!vm_page_all_valid(ma[i]))
5433 if (redo && error == 0)
5435 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
5438 #include "opt_ddb.h"
5440 #include <ddb/ddb.h>
5442 /* DDB command to show buffer data */
5443 DB_SHOW_COMMAND(buffer, db_show_buffer)
5446 struct buf *bp = (struct buf *)addr;
5447 #ifdef FULL_BUF_TRACKING
5452 db_printf("usage: show buffer <addr>\n");
5456 db_printf("buf at %p\n", bp);
5457 db_printf("b_flags = 0x%b, b_xflags=0x%b\n",
5458 (u_int)bp->b_flags, PRINT_BUF_FLAGS,
5459 (u_int)bp->b_xflags, PRINT_BUF_XFLAGS);
5460 db_printf("b_vflags=0x%b b_ioflags0x%b\n",
5461 (u_int)bp->b_vflags, PRINT_BUF_VFLAGS,
5462 (u_int)bp->b_ioflags, PRINT_BIO_FLAGS);
5464 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
5465 "b_bufobj = (%p), b_data = %p\n, b_blkno = %jd, b_lblkno = %jd, "
5466 "b_vp = %p, b_dep = %p\n",
5467 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
5468 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
5469 (intmax_t)bp->b_lblkno, bp->b_vp, bp->b_dep.lh_first);
5470 db_printf("b_kvabase = %p, b_kvasize = %d\n",
5471 bp->b_kvabase, bp->b_kvasize);
5474 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
5475 for (i = 0; i < bp->b_npages; i++) {
5479 db_printf("(%p, 0x%lx, 0x%lx)", m->object,
5481 (u_long)VM_PAGE_TO_PHYS(m));
5483 db_printf("( ??? )");
5484 if ((i + 1) < bp->b_npages)
5489 BUF_LOCKPRINTINFO(bp);
5490 #if defined(FULL_BUF_TRACKING)
5491 db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
5493 i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
5494 for (j = 1; j <= BUF_TRACKING_SIZE; j++) {
5495 if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL)
5497 db_printf(" %2u: %s\n", j,
5498 bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
5500 #elif defined(BUF_TRACKING)
5501 db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
5506 DB_SHOW_COMMAND_FLAGS(bufqueues, bufqueues, DB_CMD_MEMSAFE)
5508 struct bufdomain *bd;
5513 db_printf("bqempty: %d\n", bqempty.bq_len);
5515 for (i = 0; i < buf_domains; i++) {
5517 db_printf("Buf domain %d\n", i);
5518 db_printf("\tfreebufs\t%d\n", bd->bd_freebuffers);
5519 db_printf("\tlofreebufs\t%d\n", bd->bd_lofreebuffers);
5520 db_printf("\thifreebufs\t%d\n", bd->bd_hifreebuffers);
5522 db_printf("\tbufspace\t%ld\n", bd->bd_bufspace);
5523 db_printf("\tmaxbufspace\t%ld\n", bd->bd_maxbufspace);
5524 db_printf("\thibufspace\t%ld\n", bd->bd_hibufspace);
5525 db_printf("\tlobufspace\t%ld\n", bd->bd_lobufspace);
5526 db_printf("\tbufspacethresh\t%ld\n", bd->bd_bufspacethresh);
5528 db_printf("\tnumdirtybuffers\t%d\n", bd->bd_numdirtybuffers);
5529 db_printf("\tlodirtybuffers\t%d\n", bd->bd_lodirtybuffers);
5530 db_printf("\thidirtybuffers\t%d\n", bd->bd_hidirtybuffers);
5531 db_printf("\tdirtybufthresh\t%d\n", bd->bd_dirtybufthresh);
5534 TAILQ_FOREACH(bp, &bd->bd_cleanq->bq_queue, b_freelist)
5535 total += bp->b_bufsize;
5536 db_printf("\tcleanq count\t%d (%ld)\n",
5537 bd->bd_cleanq->bq_len, total);
5539 TAILQ_FOREACH(bp, &bd->bd_dirtyq.bq_queue, b_freelist)
5540 total += bp->b_bufsize;
5541 db_printf("\tdirtyq count\t%d (%ld)\n",
5542 bd->bd_dirtyq.bq_len, total);
5543 db_printf("\twakeup\t\t%d\n", bd->bd_wanted);
5544 db_printf("\tlim\t\t%d\n", bd->bd_lim);
5545 db_printf("\tCPU ");
5546 for (j = 0; j <= mp_maxid; j++)
5547 db_printf("%d, ", bd->bd_subq[j].bq_len);
5551 for (j = 0; j < nbuf; j++) {
5553 if (bp->b_domain == i && BUF_ISLOCKED(bp)) {
5555 total += bp->b_bufsize;
5558 db_printf("\tLocked buffers: %d space %ld\n", cnt, total);
5561 for (j = 0; j < nbuf; j++) {
5563 if (bp->b_domain == i) {
5565 total += bp->b_bufsize;
5568 db_printf("\tTotal buffers: %d space %ld\n", cnt, total);
5572 DB_SHOW_COMMAND_FLAGS(lockedbufs, lockedbufs, DB_CMD_MEMSAFE)
5577 for (i = 0; i < nbuf; i++) {
5579 if (BUF_ISLOCKED(bp)) {
5580 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5588 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
5594 db_printf("usage: show vnodebufs <addr>\n");
5597 vp = (struct vnode *)addr;
5598 db_printf("Clean buffers:\n");
5599 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
5600 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5603 db_printf("Dirty buffers:\n");
5604 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5605 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5610 DB_COMMAND_FLAGS(countfreebufs, db_coundfreebufs, DB_CMD_MEMSAFE)
5613 int i, used = 0, nfree = 0;
5616 db_printf("usage: countfreebufs\n");
5620 for (i = 0; i < nbuf; i++) {
5622 if (bp->b_qindex == QUEUE_EMPTY)
5628 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5630 db_printf("numfreebuffers is %d\n", numfreebuffers);