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 #include <sys/param.h>
49 #include <sys/systm.h>
52 #include <sys/bitset.h>
53 #include <sys/boottrace.h>
56 #include <sys/counter.h>
57 #include <sys/devicestat.h>
58 #include <sys/eventhandler.h>
61 #include <sys/limits.h>
63 #include <sys/malloc.h>
64 #include <sys/memdesc.h>
65 #include <sys/mount.h>
66 #include <sys/mutex.h>
67 #include <sys/kernel.h>
68 #include <sys/kthread.h>
69 #include <sys/pctrie.h>
71 #include <sys/racct.h>
72 #include <sys/refcount.h>
73 #include <sys/resourcevar.h>
74 #include <sys/rwlock.h>
75 #include <sys/sched.h>
77 #include <sys/sysctl.h>
78 #include <sys/syscallsubr.h>
80 #include <sys/vmmeter.h>
81 #include <sys/vnode.h>
82 #include <sys/watchdog.h>
83 #include <geom/geom.h>
85 #include <vm/vm_param.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_pager.h>
91 #include <vm/vm_extern.h>
92 #include <vm/vm_map.h>
93 #include <vm/swap_pager.h>
95 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer");
97 struct bio_ops bioops; /* I/O operation notification */
99 struct buf_ops buf_ops_bio = {
100 .bop_name = "buf_ops_bio",
101 .bop_write = bufwrite,
102 .bop_strategy = bufstrategy,
104 .bop_bdflush = bufbdflush,
108 struct mtx_padalign bq_lock;
109 TAILQ_HEAD(, buf) bq_queue;
111 uint16_t bq_subqueue;
113 } __aligned(CACHE_LINE_SIZE);
115 #define BQ_LOCKPTR(bq) (&(bq)->bq_lock)
116 #define BQ_LOCK(bq) mtx_lock(BQ_LOCKPTR((bq)))
117 #define BQ_UNLOCK(bq) mtx_unlock(BQ_LOCKPTR((bq)))
118 #define BQ_ASSERT_LOCKED(bq) mtx_assert(BQ_LOCKPTR((bq)), MA_OWNED)
121 struct bufqueue *bd_subq;
122 struct bufqueue bd_dirtyq;
123 struct bufqueue *bd_cleanq;
124 struct mtx_padalign bd_run_lock;
129 long bd_bufspacethresh;
130 int bd_hifreebuffers;
131 int bd_lofreebuffers;
132 int bd_hidirtybuffers;
133 int bd_lodirtybuffers;
134 int bd_dirtybufthresh;
139 int __aligned(CACHE_LINE_SIZE) bd_numdirtybuffers;
140 int __aligned(CACHE_LINE_SIZE) bd_running;
141 long __aligned(CACHE_LINE_SIZE) bd_bufspace;
142 int __aligned(CACHE_LINE_SIZE) bd_freebuffers;
143 } __aligned(CACHE_LINE_SIZE);
145 #define BD_LOCKPTR(bd) (&(bd)->bd_cleanq->bq_lock)
146 #define BD_LOCK(bd) mtx_lock(BD_LOCKPTR((bd)))
147 #define BD_UNLOCK(bd) mtx_unlock(BD_LOCKPTR((bd)))
148 #define BD_ASSERT_LOCKED(bd) mtx_assert(BD_LOCKPTR((bd)), MA_OWNED)
149 #define BD_RUN_LOCKPTR(bd) (&(bd)->bd_run_lock)
150 #define BD_RUN_LOCK(bd) mtx_lock(BD_RUN_LOCKPTR((bd)))
151 #define BD_RUN_UNLOCK(bd) mtx_unlock(BD_RUN_LOCKPTR((bd)))
152 #define BD_DOMAIN(bd) (bd - bdomain)
154 static char *buf; /* buffer header pool */
158 return ((struct buf *)(buf + (sizeof(struct buf) +
159 sizeof(vm_page_t) * atop(maxbcachebuf)) * i));
162 caddr_t __read_mostly unmapped_buf;
164 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */
165 struct proc *bufdaemonproc;
167 static void vm_hold_free_pages(struct buf *bp, int newbsize);
168 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
170 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m);
171 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off,
173 static void vfs_clean_pages_dirty_buf(struct buf *bp);
174 static void vfs_setdirty_range(struct buf *bp);
175 static void vfs_vmio_invalidate(struct buf *bp);
176 static void vfs_vmio_truncate(struct buf *bp, int npages);
177 static void vfs_vmio_extend(struct buf *bp, int npages, int size);
178 static int vfs_bio_clcheck(struct vnode *vp, int size,
179 daddr_t lblkno, daddr_t blkno);
180 static void breada(struct vnode *, daddr_t *, int *, int, struct ucred *, int,
181 void (*)(struct buf *));
182 static int buf_flush(struct vnode *vp, struct bufdomain *, int);
183 static int flushbufqueues(struct vnode *, struct bufdomain *, int, int);
184 static void buf_daemon(void);
185 static __inline void bd_wakeup(void);
186 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS);
187 static void bufkva_reclaim(vmem_t *, int);
188 static void bufkva_free(struct buf *);
189 static int buf_import(void *, void **, int, int, int);
190 static void buf_release(void *, void **, int);
191 static void maxbcachebuf_adjust(void);
192 static inline struct bufdomain *bufdomain(struct buf *);
193 static void bq_remove(struct bufqueue *bq, struct buf *bp);
194 static void bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock);
195 static int buf_recycle(struct bufdomain *, bool kva);
196 static void bq_init(struct bufqueue *bq, int qindex, int cpu,
197 const char *lockname);
198 static void bd_init(struct bufdomain *bd);
199 static int bd_flushall(struct bufdomain *bd);
200 static int sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS);
201 static int sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS);
203 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS);
204 int vmiodirenable = TRUE;
205 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
206 "Use the VM system for directory writes");
207 long runningbufspace;
208 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
209 "Amount of presently outstanding async buffer io");
210 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD,
211 NULL, 0, sysctl_bufspace, "L", "Physical memory used for buffers");
212 static counter_u64_t bufkvaspace;
213 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace,
214 "Kernel virtual memory used for buffers");
215 static long maxbufspace;
216 SYSCTL_PROC(_vfs, OID_AUTO, maxbufspace,
217 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &maxbufspace,
218 __offsetof(struct bufdomain, bd_maxbufspace), sysctl_bufdomain_long, "L",
219 "Maximum allowed value of bufspace (including metadata)");
220 static long bufmallocspace;
221 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
222 "Amount of malloced memory for buffers");
223 static long maxbufmallocspace;
224 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace,
225 0, "Maximum amount of malloced memory for buffers");
226 static long lobufspace;
227 SYSCTL_PROC(_vfs, OID_AUTO, lobufspace,
228 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &lobufspace,
229 __offsetof(struct bufdomain, bd_lobufspace), sysctl_bufdomain_long, "L",
230 "Minimum amount of buffers we want to have");
232 SYSCTL_PROC(_vfs, OID_AUTO, hibufspace,
233 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &hibufspace,
234 __offsetof(struct bufdomain, bd_hibufspace), sysctl_bufdomain_long, "L",
235 "Maximum allowed value of bufspace (excluding metadata)");
237 SYSCTL_PROC(_vfs, OID_AUTO, bufspacethresh,
238 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &bufspacethresh,
239 __offsetof(struct bufdomain, bd_bufspacethresh), sysctl_bufdomain_long, "L",
240 "Bufspace consumed before waking the daemon to free some");
241 static counter_u64_t buffreekvacnt;
242 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt,
243 "Number of times we have freed the KVA space from some buffer");
244 static counter_u64_t bufdefragcnt;
245 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt,
246 "Number of times we have had to repeat buffer allocation to defragment");
247 static long lorunningspace;
248 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
249 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L",
250 "Minimum preferred space used for in-progress I/O");
251 static long hirunningspace;
252 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE |
253 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L",
254 "Maximum amount of space to use for in-progress I/O");
255 int dirtybufferflushes;
256 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes,
257 0, "Number of bdwrite to bawrite conversions to limit dirty buffers");
259 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip,
260 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk");
261 int altbufferflushes;
262 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW | CTLFLAG_STATS,
263 &altbufferflushes, 0, "Number of fsync flushes to limit dirty buffers");
264 static int recursiveflushes;
265 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW | CTLFLAG_STATS,
266 &recursiveflushes, 0, "Number of flushes skipped due to being recursive");
267 static int sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS);
268 SYSCTL_PROC(_vfs, OID_AUTO, numdirtybuffers,
269 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RD, NULL, 0, sysctl_numdirtybuffers, "I",
270 "Number of buffers that are dirty (has unwritten changes) at the moment");
271 static int lodirtybuffers;
272 SYSCTL_PROC(_vfs, OID_AUTO, lodirtybuffers,
273 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lodirtybuffers,
274 __offsetof(struct bufdomain, bd_lodirtybuffers), sysctl_bufdomain_int, "I",
275 "How many buffers we want to have free before bufdaemon can sleep");
276 static int hidirtybuffers;
277 SYSCTL_PROC(_vfs, OID_AUTO, hidirtybuffers,
278 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hidirtybuffers,
279 __offsetof(struct bufdomain, bd_hidirtybuffers), sysctl_bufdomain_int, "I",
280 "When the number of dirty buffers is considered severe");
282 SYSCTL_PROC(_vfs, OID_AUTO, dirtybufthresh,
283 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &dirtybufthresh,
284 __offsetof(struct bufdomain, bd_dirtybufthresh), sysctl_bufdomain_int, "I",
285 "Number of bdwrite to bawrite conversions to clear dirty buffers");
286 static int numfreebuffers;
287 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
288 "Number of free buffers");
289 static int lofreebuffers;
290 SYSCTL_PROC(_vfs, OID_AUTO, lofreebuffers,
291 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lofreebuffers,
292 __offsetof(struct bufdomain, bd_lofreebuffers), sysctl_bufdomain_int, "I",
293 "Target number of free buffers");
294 static int hifreebuffers;
295 SYSCTL_PROC(_vfs, OID_AUTO, hifreebuffers,
296 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hifreebuffers,
297 __offsetof(struct bufdomain, bd_hifreebuffers), sysctl_bufdomain_int, "I",
298 "Threshold for clean buffer recycling");
299 static counter_u64_t getnewbufcalls;
300 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD,
301 &getnewbufcalls, "Number of calls to getnewbuf");
302 static counter_u64_t getnewbufrestarts;
303 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD,
305 "Number of times getnewbuf has had to restart a buffer acquisition");
306 static counter_u64_t mappingrestarts;
307 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RD,
309 "Number of times getblk has had to restart a buffer mapping for "
311 static counter_u64_t numbufallocfails;
312 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW,
313 &numbufallocfails, "Number of times buffer allocations failed");
314 static int flushbufqtarget = 100;
315 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0,
316 "Amount of work to do in flushbufqueues when helping bufdaemon");
317 static counter_u64_t notbufdflushes;
318 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes,
319 "Number of dirty buffer flushes done by the bufdaemon helpers");
320 static long barrierwrites;
321 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW | CTLFLAG_STATS,
322 &barrierwrites, 0, "Number of barrier writes");
323 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed,
324 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
325 &unmapped_buf_allowed, 0,
326 "Permit the use of the unmapped i/o");
327 int maxbcachebuf = MAXBCACHEBUF;
328 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0,
329 "Maximum size of a buffer cache block");
332 * This lock synchronizes access to bd_request.
334 static struct mtx_padalign __exclusive_cache_line bdlock;
337 * This lock protects the runningbufreq and synchronizes runningbufwakeup and
338 * waitrunningbufspace().
340 static struct mtx_padalign __exclusive_cache_line rbreqlock;
343 * Lock that protects bdirtywait.
345 static struct mtx_padalign __exclusive_cache_line bdirtylock;
348 * bufdaemon shutdown request and sleep channel.
350 static bool bd_shutdown;
353 * Wakeup point for bufdaemon, as well as indicator of whether it is already
354 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it
357 static int bd_request;
360 * Request for the buf daemon to write more buffers than is indicated by
361 * lodirtybuf. This may be necessary to push out excess dependencies or
362 * defragment the address space where a simple count of the number of dirty
363 * buffers is insufficient to characterize the demand for flushing them.
365 static int bd_speedupreq;
368 * Synchronization (sleep/wakeup) variable for active buffer space requests.
369 * Set when wait starts, cleared prior to wakeup().
370 * Used in runningbufwakeup() and waitrunningbufspace().
372 static int runningbufreq;
375 * Synchronization for bwillwrite() waiters.
377 static int bdirtywait;
380 * Definitions for the buffer free lists.
382 #define QUEUE_NONE 0 /* on no queue */
383 #define QUEUE_EMPTY 1 /* empty buffer headers */
384 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */
385 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */
386 #define QUEUE_SENTINEL 4 /* not an queue index, but mark for sentinel */
388 /* Maximum number of buffer domains. */
389 #define BUF_DOMAINS 8
391 struct bufdomainset bdlodirty; /* Domains > lodirty */
392 struct bufdomainset bdhidirty; /* Domains > hidirty */
394 /* Configured number of clean queues. */
395 static int __read_mostly buf_domains;
397 BITSET_DEFINE(bufdomainset, BUF_DOMAINS);
398 struct bufdomain __exclusive_cache_line bdomain[BUF_DOMAINS];
399 struct bufqueue __exclusive_cache_line bqempty;
402 * per-cpu empty buffer cache.
407 sysctl_runningspace(SYSCTL_HANDLER_ARGS)
412 value = *(long *)arg1;
413 error = sysctl_handle_long(oidp, &value, 0, req);
414 if (error != 0 || req->newptr == NULL)
416 mtx_lock(&rbreqlock);
417 if (arg1 == &hirunningspace) {
418 if (value < lorunningspace)
421 hirunningspace = value;
423 KASSERT(arg1 == &lorunningspace,
424 ("%s: unknown arg1", __func__));
425 if (value > hirunningspace)
428 lorunningspace = value;
430 mtx_unlock(&rbreqlock);
435 sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS)
441 value = *(int *)arg1;
442 error = sysctl_handle_int(oidp, &value, 0, req);
443 if (error != 0 || req->newptr == NULL)
445 *(int *)arg1 = value;
446 for (i = 0; i < buf_domains; i++)
447 *(int *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
454 sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS)
460 value = *(long *)arg1;
461 error = sysctl_handle_long(oidp, &value, 0, req);
462 if (error != 0 || req->newptr == NULL)
464 *(long *)arg1 = value;
465 for (i = 0; i < buf_domains; i++)
466 *(long *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) =
472 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
473 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7)
475 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
482 for (i = 0; i < buf_domains; i++)
483 lvalue += bdomain[i].bd_bufspace;
484 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long))
485 return (sysctl_handle_long(oidp, &lvalue, 0, req));
486 if (lvalue > INT_MAX)
487 /* On overflow, still write out a long to trigger ENOMEM. */
488 return (sysctl_handle_long(oidp, &lvalue, 0, req));
490 return (sysctl_handle_int(oidp, &ivalue, 0, req));
494 sysctl_bufspace(SYSCTL_HANDLER_ARGS)
500 for (i = 0; i < buf_domains; i++)
501 lvalue += bdomain[i].bd_bufspace;
502 return (sysctl_handle_long(oidp, &lvalue, 0, req));
507 sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS)
513 for (i = 0; i < buf_domains; i++)
514 value += bdomain[i].bd_numdirtybuffers;
515 return (sysctl_handle_int(oidp, &value, 0, req));
521 * Wakeup any bwillwrite() waiters.
526 mtx_lock(&bdirtylock);
531 mtx_unlock(&bdirtylock);
537 * Clear a domain from the appropriate bitsets when dirtybuffers
541 bd_clear(struct bufdomain *bd)
544 mtx_lock(&bdirtylock);
545 if (bd->bd_numdirtybuffers <= bd->bd_lodirtybuffers)
546 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
547 if (bd->bd_numdirtybuffers <= bd->bd_hidirtybuffers)
548 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
549 mtx_unlock(&bdirtylock);
555 * Set a domain in the appropriate bitsets when dirtybuffers
559 bd_set(struct bufdomain *bd)
562 mtx_lock(&bdirtylock);
563 if (bd->bd_numdirtybuffers > bd->bd_lodirtybuffers)
564 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty);
565 if (bd->bd_numdirtybuffers > bd->bd_hidirtybuffers)
566 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty);
567 mtx_unlock(&bdirtylock);
573 * Decrement the numdirtybuffers count by one and wakeup any
574 * threads blocked in bwillwrite().
577 bdirtysub(struct buf *bp)
579 struct bufdomain *bd;
583 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, -1);
584 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
586 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
593 * Increment the numdirtybuffers count by one and wakeup the buf
597 bdirtyadd(struct buf *bp)
599 struct bufdomain *bd;
603 * Only do the wakeup once as we cross the boundary. The
604 * buf daemon will keep running until the condition clears.
607 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, 1);
608 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2)
610 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers)
615 * bufspace_daemon_wakeup:
617 * Wakeup the daemons responsible for freeing clean bufs.
620 bufspace_daemon_wakeup(struct bufdomain *bd)
624 * avoid the lock if the daemon is running.
626 if (atomic_fetchadd_int(&bd->bd_running, 1) == 0) {
628 atomic_store_int(&bd->bd_running, 1);
629 wakeup(&bd->bd_running);
637 * Adjust the reported bufspace for a KVA managed buffer, possibly
638 * waking any waiters.
641 bufspace_adjust(struct buf *bp, int bufsize)
643 struct bufdomain *bd;
647 KASSERT((bp->b_flags & B_MALLOC) == 0,
648 ("bufspace_adjust: malloc buf %p", bp));
650 diff = bufsize - bp->b_bufsize;
652 atomic_subtract_long(&bd->bd_bufspace, -diff);
653 } else if (diff > 0) {
654 space = atomic_fetchadd_long(&bd->bd_bufspace, diff);
655 /* Wake up the daemon on the transition. */
656 if (space < bd->bd_bufspacethresh &&
657 space + diff >= bd->bd_bufspacethresh)
658 bufspace_daemon_wakeup(bd);
660 bp->b_bufsize = bufsize;
666 * Reserve bufspace before calling allocbuf(). metadata has a
667 * different space limit than data.
670 bufspace_reserve(struct bufdomain *bd, int size, bool metadata)
676 limit = bd->bd_maxbufspace;
678 limit = bd->bd_hibufspace;
679 space = atomic_fetchadd_long(&bd->bd_bufspace, size);
682 atomic_subtract_long(&bd->bd_bufspace, size);
686 /* Wake up the daemon on the transition. */
687 if (space < bd->bd_bufspacethresh && new >= bd->bd_bufspacethresh)
688 bufspace_daemon_wakeup(bd);
696 * Release reserved bufspace after bufspace_adjust() has consumed it.
699 bufspace_release(struct bufdomain *bd, int size)
702 atomic_subtract_long(&bd->bd_bufspace, size);
708 * Wait for bufspace, acting as the buf daemon if a locked vnode is
709 * supplied. bd_wanted must be set prior to polling for space. The
710 * operation must be re-tried on return.
713 bufspace_wait(struct bufdomain *bd, struct vnode *vp, int gbflags,
714 int slpflag, int slptimeo)
717 int error, fl, norunbuf;
719 if ((gbflags & GB_NOWAIT_BD) != 0)
724 while (bd->bd_wanted) {
725 if (vp != NULL && vp->v_type != VCHR &&
726 (td->td_pflags & TDP_BUFNEED) == 0) {
729 * getblk() is called with a vnode locked, and
730 * some majority of the dirty buffers may as
731 * well belong to the vnode. Flushing the
732 * buffers there would make a progress that
733 * cannot be achieved by the buf_daemon, that
734 * cannot lock the vnode.
736 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) |
737 (td->td_pflags & TDP_NORUNNINGBUF);
740 * Play bufdaemon. The getnewbuf() function
741 * may be called while the thread owns lock
742 * for another dirty buffer for the same
743 * vnode, which makes it impossible to use
744 * VOP_FSYNC() there, due to the buffer lock
747 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF;
748 fl = buf_flush(vp, bd, flushbufqtarget);
749 td->td_pflags &= norunbuf;
753 if (bd->bd_wanted == 0)
756 error = msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
757 (PRIBIO + 4) | slpflag, "newbuf", slptimeo);
765 bufspace_daemon_shutdown(void *arg, int howto __unused)
767 struct bufdomain *bd = arg;
770 if (KERNEL_PANICKED())
774 bd->bd_shutdown = true;
775 wakeup(&bd->bd_running);
776 error = msleep(&bd->bd_shutdown, BD_RUN_LOCKPTR(bd), 0,
777 "bufspace_shutdown", 60 * hz);
780 printf("bufspacedaemon wait error: %d\n", error);
786 * buffer space management daemon. Tries to maintain some marginal
787 * amount of free buffer space so that requesting processes neither
788 * block nor work to reclaim buffers.
791 bufspace_daemon(void *arg)
793 struct bufdomain *bd = arg;
795 EVENTHANDLER_REGISTER(shutdown_pre_sync, bufspace_daemon_shutdown, bd,
796 SHUTDOWN_PRI_LAST + 100);
799 while (!bd->bd_shutdown) {
803 * Free buffers from the clean queue until we meet our
806 * Theory of operation: The buffer cache is most efficient
807 * when some free buffer headers and space are always
808 * available to getnewbuf(). This daemon attempts to prevent
809 * the excessive blocking and synchronization associated
810 * with shortfall. It goes through three phases according
813 * 1) The daemon wakes up voluntarily once per-second
814 * during idle periods when the counters are below
815 * the wakeup thresholds (bufspacethresh, lofreebuffers).
817 * 2) The daemon wakes up as we cross the thresholds
818 * ahead of any potential blocking. This may bounce
819 * slightly according to the rate of consumption and
822 * 3) The daemon and consumers are starved for working
823 * clean buffers. This is the 'bufspace' sleep below
824 * which will inefficiently trade bufs with bqrelse
825 * until we return to condition 2.
827 while (bd->bd_bufspace > bd->bd_lobufspace ||
828 bd->bd_freebuffers < bd->bd_hifreebuffers) {
829 if (buf_recycle(bd, false) != 0) {
833 * Speedup dirty if we've run out of clean
834 * buffers. This is possible in particular
835 * because softdep may held many bufs locked
836 * pending writes to other bufs which are
837 * marked for delayed write, exhausting
838 * clean space until they are written.
843 msleep(&bd->bd_wanted, BD_LOCKPTR(bd),
844 PRIBIO|PDROP, "bufspace", hz/10);
852 * Re-check our limits and sleep. bd_running must be
853 * cleared prior to checking the limits to avoid missed
854 * wakeups. The waker will adjust one of bufspace or
855 * freebuffers prior to checking bd_running.
860 atomic_store_int(&bd->bd_running, 0);
861 if (bd->bd_bufspace < bd->bd_bufspacethresh &&
862 bd->bd_freebuffers > bd->bd_lofreebuffers) {
863 msleep(&bd->bd_running, BD_RUN_LOCKPTR(bd),
866 /* Avoid spurious wakeups while running. */
867 atomic_store_int(&bd->bd_running, 1);
870 wakeup(&bd->bd_shutdown);
878 * Adjust the reported bufspace for a malloc managed buffer, possibly
879 * waking any waiters.
882 bufmallocadjust(struct buf *bp, int bufsize)
886 KASSERT((bp->b_flags & B_MALLOC) != 0,
887 ("bufmallocadjust: non-malloc buf %p", bp));
888 diff = bufsize - bp->b_bufsize;
890 atomic_subtract_long(&bufmallocspace, -diff);
892 atomic_add_long(&bufmallocspace, diff);
893 bp->b_bufsize = bufsize;
899 * Wake up processes that are waiting on asynchronous writes to fall
900 * below lorunningspace.
906 mtx_lock(&rbreqlock);
909 wakeup(&runningbufreq);
911 mtx_unlock(&rbreqlock);
917 * Decrement the outstanding write count according.
920 runningbufwakeup(struct buf *bp)
924 bspace = bp->b_runningbufspace;
927 space = atomic_fetchadd_long(&runningbufspace, -bspace);
928 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld",
930 bp->b_runningbufspace = 0;
932 * Only acquire the lock and wakeup on the transition from exceeding
933 * the threshold to falling below it.
935 if (space < lorunningspace)
937 if (space - bspace > lorunningspace)
943 * waitrunningbufspace()
945 * runningbufspace is a measure of the amount of I/O currently
946 * running. This routine is used in async-write situations to
947 * prevent creating huge backups of pending writes to a device.
948 * Only asynchronous writes are governed by this function.
950 * This does NOT turn an async write into a sync write. It waits
951 * for earlier writes to complete and generally returns before the
952 * caller's write has reached the device.
955 waitrunningbufspace(void)
958 mtx_lock(&rbreqlock);
959 while (runningbufspace > hirunningspace) {
961 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0);
963 mtx_unlock(&rbreqlock);
967 * vfs_buf_test_cache:
969 * Called when a buffer is extended. This function clears the B_CACHE
970 * bit if the newly extended portion of the buffer does not contain
974 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off,
975 vm_offset_t size, vm_page_t m)
979 * This function and its results are protected by higher level
980 * synchronization requiring vnode and buf locks to page in and
983 if (bp->b_flags & B_CACHE) {
984 int base = (foff + off) & PAGE_MASK;
985 if (vm_page_is_valid(m, base, size) == 0)
986 bp->b_flags &= ~B_CACHE;
990 /* Wake up the buffer daemon if necessary */
996 if (bd_request == 0) {
1000 mtx_unlock(&bdlock);
1004 * Adjust the maxbcachbuf tunable.
1007 maxbcachebuf_adjust(void)
1012 * maxbcachebuf must be a power of 2 >= MAXBSIZE.
1015 while (i * 2 <= maxbcachebuf)
1018 if (maxbcachebuf < MAXBSIZE)
1019 maxbcachebuf = MAXBSIZE;
1020 if (maxbcachebuf > maxphys)
1021 maxbcachebuf = maxphys;
1022 if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF)
1023 printf("maxbcachebuf=%d\n", maxbcachebuf);
1027 * bd_speedup - speedup the buffer cache flushing code
1036 if (bd_speedupreq == 0 || bd_request == 0)
1041 wakeup(&bd_request);
1042 mtx_unlock(&bdlock);
1046 #define TRANSIENT_DENOM 5
1048 #define TRANSIENT_DENOM 10
1052 * Calculating buffer cache scaling values and reserve space for buffer
1053 * headers. This is called during low level kernel initialization and
1054 * may be called more then once. We CANNOT write to the memory area
1055 * being reserved at this time.
1058 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est)
1061 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz;
1064 * With KASAN or KMSAN enabled, the kernel map is shadowed. Account for
1065 * this when sizing maps based on the amount of physical memory
1069 physmem_est = (physmem_est * KASAN_SHADOW_SCALE) /
1070 (KASAN_SHADOW_SCALE + 1);
1071 #elif defined(KMSAN)
1075 * KMSAN cannot reliably determine whether buffer data is initialized
1076 * unless it is updated through a KVA mapping.
1078 unmapped_buf_allowed = 0;
1082 * physmem_est is in pages. Convert it to kilobytes (assumes
1083 * PAGE_SIZE is >= 1K)
1085 physmem_est = physmem_est * (PAGE_SIZE / 1024);
1087 maxbcachebuf_adjust();
1089 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
1090 * For the first 64MB of ram nominally allocate sufficient buffers to
1091 * cover 1/4 of our ram. Beyond the first 64MB allocate additional
1092 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing
1093 * the buffer cache we limit the eventual kva reservation to
1096 * factor represents the 1/4 x ram conversion.
1099 int factor = 4 * BKVASIZE / 1024;
1102 if (physmem_est > 4096)
1103 nbuf += min((physmem_est - 4096) / factor,
1105 if (physmem_est > 65536)
1106 nbuf += min((physmem_est - 65536) * 2 / (factor * 5),
1107 32 * 1024 * 1024 / (factor * 5));
1109 if (maxbcache && nbuf > maxbcache / BKVASIZE)
1110 nbuf = maxbcache / BKVASIZE;
1115 /* XXX Avoid unsigned long overflows later on with maxbufspace. */
1116 maxbuf = (LONG_MAX / 3) / BKVASIZE;
1117 if (nbuf > maxbuf) {
1119 printf("Warning: nbufs lowered from %d to %ld\n", nbuf,
1125 * Ideal allocation size for the transient bio submap is 10%
1126 * of the maximal space buffer map. This roughly corresponds
1127 * to the amount of the buffer mapped for typical UFS load.
1129 * Clip the buffer map to reserve space for the transient
1130 * BIOs, if its extent is bigger than 90% (80% on i386) of the
1131 * maximum buffer map extent on the platform.
1133 * The fall-back to the maxbuf in case of maxbcache unset,
1134 * allows to not trim the buffer KVA for the architectures
1135 * with ample KVA space.
1137 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) {
1138 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE;
1139 buf_sz = (long)nbuf * BKVASIZE;
1140 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM *
1141 (TRANSIENT_DENOM - 1)) {
1143 * There is more KVA than memory. Do not
1144 * adjust buffer map size, and assign the rest
1145 * of maxbuf to transient map.
1147 biotmap_sz = maxbuf_sz - buf_sz;
1150 * Buffer map spans all KVA we could afford on
1151 * this platform. Give 10% (20% on i386) of
1152 * the buffer map to the transient bio map.
1154 biotmap_sz = buf_sz / TRANSIENT_DENOM;
1155 buf_sz -= biotmap_sz;
1157 if (biotmap_sz / INT_MAX > maxphys)
1158 bio_transient_maxcnt = INT_MAX;
1160 bio_transient_maxcnt = biotmap_sz / maxphys;
1162 * Artificially limit to 1024 simultaneous in-flight I/Os
1163 * using the transient mapping.
1165 if (bio_transient_maxcnt > 1024)
1166 bio_transient_maxcnt = 1024;
1168 nbuf = buf_sz / BKVASIZE;
1173 * Pager buffers are allocated for short periods, so scale the
1174 * number of reserved buffers based on the number of CPUs rather
1175 * than amount of memory.
1177 nswbuf = min(nbuf / 4, 32 * mp_ncpus);
1178 if (nswbuf < NSWBUF_MIN)
1179 nswbuf = NSWBUF_MIN;
1183 * Reserve space for the buffer cache buffers
1186 v = (caddr_t)buf + (sizeof(struct buf) + sizeof(vm_page_t) *
1187 atop(maxbcachebuf)) * nbuf;
1193 * Single global constant for BUF_WMESG, to avoid getting multiple
1196 static const char buf_wmesg[] = "bufwait";
1198 /* Initialize the buffer subsystem. Called before use of any buffers. */
1206 KASSERT(maxbcachebuf >= MAXBSIZE,
1207 ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf,
1209 bq_init(&bqempty, QUEUE_EMPTY, -1, "bufq empty lock");
1210 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF);
1211 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF);
1212 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF);
1214 unmapped_buf = (caddr_t)kva_alloc(maxphys);
1216 /* finally, initialize each buffer header and stick on empty q */
1217 for (i = 0; i < nbuf; i++) {
1219 bzero(bp, sizeof(*bp) + sizeof(vm_page_t) * atop(maxbcachebuf));
1220 bp->b_flags = B_INVAL;
1221 bp->b_rcred = NOCRED;
1222 bp->b_wcred = NOCRED;
1223 bp->b_qindex = QUEUE_NONE;
1225 bp->b_subqueue = mp_maxid + 1;
1227 bp->b_data = bp->b_kvabase = unmapped_buf;
1228 LIST_INIT(&bp->b_dep);
1229 BUF_LOCKINIT(bp, buf_wmesg);
1230 bq_insert(&bqempty, bp, false);
1234 * maxbufspace is the absolute maximum amount of buffer space we are
1235 * allowed to reserve in KVM and in real terms. The absolute maximum
1236 * is nominally used by metadata. hibufspace is the nominal maximum
1237 * used by most other requests. The differential is required to
1238 * ensure that metadata deadlocks don't occur.
1240 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
1241 * this may result in KVM fragmentation which is not handled optimally
1242 * by the system. XXX This is less true with vmem. We could use
1245 maxbufspace = (long)nbuf * BKVASIZE;
1246 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10);
1247 lobufspace = (hibufspace / 20) * 19; /* 95% */
1248 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2;
1251 * Note: The 16 MiB upper limit for hirunningspace was chosen
1252 * arbitrarily and may need further tuning. It corresponds to
1253 * 128 outstanding write IO requests (if IO size is 128 KiB),
1254 * which fits with many RAID controllers' tagged queuing limits.
1255 * The lower 1 MiB limit is the historical upper limit for
1258 hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf),
1259 16 * 1024 * 1024), 1024 * 1024);
1260 lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf);
1263 * Limit the amount of malloc memory since it is wired permanently into
1264 * the kernel space. Even though this is accounted for in the buffer
1265 * allocation, we don't want the malloced region to grow uncontrolled.
1266 * The malloc scheme improves memory utilization significantly on
1267 * average (small) directories.
1269 maxbufmallocspace = hibufspace / 20;
1272 * Reduce the chance of a deadlock occurring by limiting the number
1273 * of delayed-write dirty buffers we allow to stack up.
1275 hidirtybuffers = nbuf / 4 + 20;
1276 dirtybufthresh = hidirtybuffers * 9 / 10;
1278 * To support extreme low-memory systems, make sure hidirtybuffers
1279 * cannot eat up all available buffer space. This occurs when our
1280 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our
1281 * buffer space assuming BKVASIZE'd buffers.
1283 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
1284 hidirtybuffers >>= 1;
1286 lodirtybuffers = hidirtybuffers / 2;
1289 * lofreebuffers should be sufficient to avoid stalling waiting on
1290 * buf headers under heavy utilization. The bufs in per-cpu caches
1291 * are counted as free but will be unavailable to threads executing
1294 * hifreebuffers is the free target for the bufspace daemon. This
1295 * should be set appropriately to limit work per-iteration.
1297 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus);
1298 hifreebuffers = (3 * lofreebuffers) / 2;
1299 numfreebuffers = nbuf;
1301 /* Setup the kva and free list allocators. */
1302 vmem_set_reclaim(buffer_arena, bufkva_reclaim);
1303 buf_zone = uma_zcache_create("buf free cache",
1304 sizeof(struct buf) + sizeof(vm_page_t) * atop(maxbcachebuf),
1305 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0);
1308 * Size the clean queue according to the amount of buffer space.
1309 * One queue per-256mb up to the max. More queues gives better
1310 * concurrency but less accurate LRU.
1312 buf_domains = MIN(howmany(maxbufspace, 256*1024*1024), BUF_DOMAINS);
1313 for (i = 0 ; i < buf_domains; i++) {
1314 struct bufdomain *bd;
1318 bd->bd_freebuffers = nbuf / buf_domains;
1319 bd->bd_hifreebuffers = hifreebuffers / buf_domains;
1320 bd->bd_lofreebuffers = lofreebuffers / buf_domains;
1321 bd->bd_bufspace = 0;
1322 bd->bd_maxbufspace = maxbufspace / buf_domains;
1323 bd->bd_hibufspace = hibufspace / buf_domains;
1324 bd->bd_lobufspace = lobufspace / buf_domains;
1325 bd->bd_bufspacethresh = bufspacethresh / buf_domains;
1326 bd->bd_numdirtybuffers = 0;
1327 bd->bd_hidirtybuffers = hidirtybuffers / buf_domains;
1328 bd->bd_lodirtybuffers = lodirtybuffers / buf_domains;
1329 bd->bd_dirtybufthresh = dirtybufthresh / buf_domains;
1330 /* Don't allow more than 2% of bufs in the per-cpu caches. */
1331 bd->bd_lim = nbuf / buf_domains / 50 / mp_ncpus;
1333 getnewbufcalls = counter_u64_alloc(M_WAITOK);
1334 getnewbufrestarts = counter_u64_alloc(M_WAITOK);
1335 mappingrestarts = counter_u64_alloc(M_WAITOK);
1336 numbufallocfails = counter_u64_alloc(M_WAITOK);
1337 notbufdflushes = counter_u64_alloc(M_WAITOK);
1338 buffreekvacnt = counter_u64_alloc(M_WAITOK);
1339 bufdefragcnt = counter_u64_alloc(M_WAITOK);
1340 bufkvaspace = counter_u64_alloc(M_WAITOK);
1346 vfs_buf_check_mapped(struct buf *bp)
1349 KASSERT(bp->b_kvabase != unmapped_buf,
1350 ("mapped buf: b_kvabase was not updated %p", bp));
1351 KASSERT(bp->b_data != unmapped_buf,
1352 ("mapped buf: b_data was not updated %p", bp));
1353 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf +
1354 maxphys, ("b_data + b_offset unmapped %p", bp));
1358 vfs_buf_check_unmapped(struct buf *bp)
1361 KASSERT(bp->b_data == unmapped_buf,
1362 ("unmapped buf: corrupted b_data %p", bp));
1365 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp)
1366 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp)
1368 #define BUF_CHECK_MAPPED(bp) do {} while (0)
1369 #define BUF_CHECK_UNMAPPED(bp) do {} while (0)
1373 isbufbusy(struct buf *bp)
1375 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) ||
1376 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
1382 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
1385 bufshutdown(int show_busybufs)
1387 static int first_buf_printf = 1;
1389 int i, iter, nbusy, pbusy;
1395 * Sync filesystems for shutdown
1397 wdog_kern_pat(WD_LASTVAL);
1398 kern_sync(curthread);
1401 * With soft updates, some buffers that are
1402 * written will be remarked as dirty until other
1403 * buffers are written.
1405 for (iter = pbusy = 0; iter < 20; iter++) {
1407 for (i = nbuf - 1; i >= 0; i--) {
1413 if (first_buf_printf)
1414 printf("All buffers synced.");
1417 if (first_buf_printf) {
1418 printf("Syncing disks, buffers remaining... ");
1419 first_buf_printf = 0;
1421 printf("%d ", nbusy);
1426 wdog_kern_pat(WD_LASTVAL);
1427 kern_sync(curthread);
1431 * Spin for a while to allow interrupt threads to run.
1433 DELAY(50000 * iter);
1436 * Context switch several times to allow interrupt
1439 for (subiter = 0; subiter < 50 * iter; subiter++) {
1440 sched_relinquish(curthread);
1447 * Count only busy local buffers to prevent forcing
1448 * a fsck if we're just a client of a wedged NFS server
1451 for (i = nbuf - 1; i >= 0; i--) {
1453 if (isbufbusy(bp)) {
1455 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
1456 if (bp->b_dev == NULL) {
1457 TAILQ_REMOVE(&mountlist,
1458 bp->b_vp->v_mount, mnt_list);
1463 if (show_busybufs > 0) {
1465 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
1466 nbusy, bp, bp->b_vp, bp->b_flags,
1467 (intmax_t)bp->b_blkno,
1468 (intmax_t)bp->b_lblkno);
1469 BUF_LOCKPRINTINFO(bp);
1470 if (show_busybufs > 1)
1478 * Failed to sync all blocks. Indicate this and don't
1479 * unmount filesystems (thus forcing an fsck on reboot).
1481 BOOTTRACE("shutdown failed to sync buffers");
1482 printf("Giving up on %d buffers\n", nbusy);
1483 DELAY(5000000); /* 5 seconds */
1486 BOOTTRACE("shutdown sync complete");
1487 if (!first_buf_printf)
1488 printf("Final sync complete\n");
1491 * Unmount filesystems and perform swapoff, to quiesce
1492 * the system as much as possible. In particular, no
1493 * I/O should be initiated from top levels since it
1494 * might be abruptly terminated by reset, or otherwise
1495 * erronously handled because other parts of the
1496 * system are disabled.
1498 * Swapoff before unmount, because file-backed swap is
1499 * non-operational after unmount of the underlying
1502 if (!KERNEL_PANICKED()) {
1506 BOOTTRACE("shutdown unmounted all filesystems");
1508 DELAY(100000); /* wait for console output to finish */
1512 bpmap_qenter(struct buf *bp)
1515 BUF_CHECK_MAPPED(bp);
1518 * bp->b_data is relative to bp->b_offset, but
1519 * bp->b_offset may be offset into the first page.
1521 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
1522 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1523 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
1524 (vm_offset_t)(bp->b_offset & PAGE_MASK));
1527 static inline struct bufdomain *
1528 bufdomain(struct buf *bp)
1531 return (&bdomain[bp->b_domain]);
1534 static struct bufqueue *
1535 bufqueue(struct buf *bp)
1538 switch (bp->b_qindex) {
1541 case QUEUE_SENTINEL:
1546 return (&bufdomain(bp)->bd_dirtyq);
1548 return (&bufdomain(bp)->bd_subq[bp->b_subqueue]);
1552 panic("bufqueue(%p): Unhandled type %d\n", bp, bp->b_qindex);
1556 * Return the locked bufqueue that bp is a member of.
1558 static struct bufqueue *
1559 bufqueue_acquire(struct buf *bp)
1561 struct bufqueue *bq, *nbq;
1564 * bp can be pushed from a per-cpu queue to the
1565 * cleanq while we're waiting on the lock. Retry
1566 * if the queues don't match.
1584 * Insert the buffer into the appropriate free list. Requires a
1585 * locked buffer on entry and buffer is unlocked before return.
1588 binsfree(struct buf *bp, int qindex)
1590 struct bufdomain *bd;
1591 struct bufqueue *bq;
1593 KASSERT(qindex == QUEUE_CLEAN || qindex == QUEUE_DIRTY,
1594 ("binsfree: Invalid qindex %d", qindex));
1595 BUF_ASSERT_XLOCKED(bp);
1598 * Handle delayed bremfree() processing.
1600 if (bp->b_flags & B_REMFREE) {
1601 if (bp->b_qindex == qindex) {
1602 bp->b_flags |= B_REUSE;
1603 bp->b_flags &= ~B_REMFREE;
1607 bq = bufqueue_acquire(bp);
1612 if (qindex == QUEUE_CLEAN) {
1613 if (bd->bd_lim != 0)
1614 bq = &bd->bd_subq[PCPU_GET(cpuid)];
1618 bq = &bd->bd_dirtyq;
1619 bq_insert(bq, bp, true);
1625 * Free a buffer to the buf zone once it no longer has valid contents.
1628 buf_free(struct buf *bp)
1631 if (bp->b_flags & B_REMFREE)
1633 if (bp->b_vflags & BV_BKGRDINPROG)
1634 panic("losing buffer 1");
1635 if (bp->b_rcred != NOCRED) {
1636 crfree(bp->b_rcred);
1637 bp->b_rcred = NOCRED;
1639 if (bp->b_wcred != NOCRED) {
1640 crfree(bp->b_wcred);
1641 bp->b_wcred = NOCRED;
1643 if (!LIST_EMPTY(&bp->b_dep))
1646 atomic_add_int(&bufdomain(bp)->bd_freebuffers, 1);
1647 MPASS((bp->b_flags & B_MAXPHYS) == 0);
1649 uma_zfree(buf_zone, bp);
1655 * Import bufs into the uma cache from the buf list. The system still
1656 * expects a static array of bufs and much of the synchronization
1657 * around bufs assumes type stable storage. As a result, UMA is used
1658 * only as a per-cpu cache of bufs still maintained on a global list.
1661 buf_import(void *arg, void **store, int cnt, int domain, int flags)
1667 for (i = 0; i < cnt; i++) {
1668 bp = TAILQ_FIRST(&bqempty.bq_queue);
1671 bq_remove(&bqempty, bp);
1674 BQ_UNLOCK(&bqempty);
1682 * Release bufs from the uma cache back to the buffer queues.
1685 buf_release(void *arg, void **store, int cnt)
1687 struct bufqueue *bq;
1693 for (i = 0; i < cnt; i++) {
1695 /* Inline bq_insert() to batch locking. */
1696 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1697 bp->b_flags &= ~(B_AGE | B_REUSE);
1699 bp->b_qindex = bq->bq_index;
1707 * Allocate an empty buffer header.
1710 buf_alloc(struct bufdomain *bd)
1713 int freebufs, error;
1716 * We can only run out of bufs in the buf zone if the average buf
1717 * is less than BKVASIZE. In this case the actual wait/block will
1718 * come from buf_reycle() failing to flush one of these small bufs.
1721 freebufs = atomic_fetchadd_int(&bd->bd_freebuffers, -1);
1723 bp = uma_zalloc(buf_zone, M_NOWAIT);
1725 atomic_add_int(&bd->bd_freebuffers, 1);
1726 bufspace_daemon_wakeup(bd);
1727 counter_u64_add(numbufallocfails, 1);
1731 * Wake-up the bufspace daemon on transition below threshold.
1733 if (freebufs == bd->bd_lofreebuffers)
1734 bufspace_daemon_wakeup(bd);
1736 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
1737 KASSERT(error == 0, ("%s: BUF_LOCK on free buf %p: %d.", __func__, bp,
1741 KASSERT(bp->b_vp == NULL,
1742 ("bp: %p still has vnode %p.", bp, bp->b_vp));
1743 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0,
1744 ("invalid buffer %p flags %#x", bp, bp->b_flags));
1745 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0,
1746 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags));
1747 KASSERT(bp->b_npages == 0,
1748 ("bp: %p still has %d vm pages\n", bp, bp->b_npages));
1749 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp));
1750 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp));
1751 MPASS((bp->b_flags & B_MAXPHYS) == 0);
1753 bp->b_domain = BD_DOMAIN(bd);
1759 bp->b_blkno = bp->b_lblkno = 0;
1760 bp->b_offset = NOOFFSET;
1766 bp->b_dirtyoff = bp->b_dirtyend = 0;
1767 bp->b_bufobj = NULL;
1768 bp->b_data = bp->b_kvabase = unmapped_buf;
1769 bp->b_fsprivate1 = NULL;
1770 bp->b_fsprivate2 = NULL;
1771 bp->b_fsprivate3 = NULL;
1772 LIST_INIT(&bp->b_dep);
1780 * Free a buffer from the given bufqueue. kva controls whether the
1781 * freed buf must own some kva resources. This is used for
1785 buf_recycle(struct bufdomain *bd, bool kva)
1787 struct bufqueue *bq;
1788 struct buf *bp, *nbp;
1791 counter_u64_add(bufdefragcnt, 1);
1795 KASSERT(BQ_LOCKPTR(bq) == BD_LOCKPTR(bd),
1796 ("buf_recycle: Locks don't match"));
1797 nbp = TAILQ_FIRST(&bq->bq_queue);
1800 * Run scan, possibly freeing data and/or kva mappings on the fly
1803 while ((bp = nbp) != NULL) {
1805 * Calculate next bp (we can only use it if we do not
1806 * release the bqlock).
1808 nbp = TAILQ_NEXT(bp, b_freelist);
1811 * If we are defragging then we need a buffer with
1812 * some kva to reclaim.
1814 if (kva && bp->b_kvasize == 0)
1817 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
1821 * Implement a second chance algorithm for frequently
1824 if ((bp->b_flags & B_REUSE) != 0) {
1825 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1826 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
1827 bp->b_flags &= ~B_REUSE;
1833 * Skip buffers with background writes in progress.
1835 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
1840 KASSERT(bp->b_qindex == QUEUE_CLEAN,
1841 ("buf_recycle: inconsistent queue %d bp %p",
1843 KASSERT(bp->b_domain == BD_DOMAIN(bd),
1844 ("getnewbuf: queue domain %d doesn't match request %d",
1845 bp->b_domain, (int)BD_DOMAIN(bd)));
1847 * NOTE: nbp is now entirely invalid. We can only restart
1848 * the scan from this point on.
1854 * Requeue the background write buffer with error and
1857 if ((bp->b_vflags & BV_BKGRDERR) != 0) {
1860 nbp = TAILQ_FIRST(&bq->bq_queue);
1863 bp->b_flags |= B_INVAL;
1876 * Mark the buffer for removal from the appropriate free list.
1880 bremfree(struct buf *bp)
1883 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1884 KASSERT((bp->b_flags & B_REMFREE) == 0,
1885 ("bremfree: buffer %p already marked for delayed removal.", bp));
1886 KASSERT(bp->b_qindex != QUEUE_NONE,
1887 ("bremfree: buffer %p not on a queue.", bp));
1888 BUF_ASSERT_XLOCKED(bp);
1890 bp->b_flags |= B_REMFREE;
1896 * Force an immediate removal from a free list. Used only in nfs when
1897 * it abuses the b_freelist pointer.
1900 bremfreef(struct buf *bp)
1902 struct bufqueue *bq;
1904 bq = bufqueue_acquire(bp);
1910 bq_init(struct bufqueue *bq, int qindex, int subqueue, const char *lockname)
1913 mtx_init(&bq->bq_lock, lockname, NULL, MTX_DEF);
1914 TAILQ_INIT(&bq->bq_queue);
1916 bq->bq_index = qindex;
1917 bq->bq_subqueue = subqueue;
1921 bd_init(struct bufdomain *bd)
1925 /* Per-CPU clean buf queues, plus one global queue. */
1926 bd->bd_subq = mallocarray(mp_maxid + 2, sizeof(struct bufqueue),
1927 M_BIOBUF, M_WAITOK | M_ZERO);
1928 bd->bd_cleanq = &bd->bd_subq[mp_maxid + 1];
1929 bq_init(bd->bd_cleanq, QUEUE_CLEAN, mp_maxid + 1, "bufq clean lock");
1930 bq_init(&bd->bd_dirtyq, QUEUE_DIRTY, -1, "bufq dirty lock");
1931 for (i = 0; i <= mp_maxid; i++)
1932 bq_init(&bd->bd_subq[i], QUEUE_CLEAN, i,
1933 "bufq clean subqueue lock");
1934 mtx_init(&bd->bd_run_lock, "bufspace daemon run lock", NULL, MTX_DEF);
1940 * Removes a buffer from the free list, must be called with the
1941 * correct qlock held.
1944 bq_remove(struct bufqueue *bq, struct buf *bp)
1947 CTR3(KTR_BUF, "bq_remove(%p) vp %p flags %X",
1948 bp, bp->b_vp, bp->b_flags);
1949 KASSERT(bp->b_qindex != QUEUE_NONE,
1950 ("bq_remove: buffer %p not on a queue.", bp));
1951 KASSERT(bufqueue(bp) == bq,
1952 ("bq_remove: Remove buffer %p from wrong queue.", bp));
1954 BQ_ASSERT_LOCKED(bq);
1955 if (bp->b_qindex != QUEUE_EMPTY) {
1956 BUF_ASSERT_XLOCKED(bp);
1958 KASSERT(bq->bq_len >= 1,
1959 ("queue %d underflow", bp->b_qindex));
1960 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1962 bp->b_qindex = QUEUE_NONE;
1963 bp->b_flags &= ~(B_REMFREE | B_REUSE);
1967 bd_flush(struct bufdomain *bd, struct bufqueue *bq)
1971 BQ_ASSERT_LOCKED(bq);
1972 if (bq != bd->bd_cleanq) {
1974 while ((bp = TAILQ_FIRST(&bq->bq_queue)) != NULL) {
1975 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist);
1976 TAILQ_INSERT_TAIL(&bd->bd_cleanq->bq_queue, bp,
1978 bp->b_subqueue = bd->bd_cleanq->bq_subqueue;
1980 bd->bd_cleanq->bq_len += bq->bq_len;
1983 if (bd->bd_wanted) {
1985 wakeup(&bd->bd_wanted);
1987 if (bq != bd->bd_cleanq)
1992 bd_flushall(struct bufdomain *bd)
1994 struct bufqueue *bq;
1998 if (bd->bd_lim == 0)
2001 for (i = 0; i <= mp_maxid; i++) {
2002 bq = &bd->bd_subq[i];
2003 if (bq->bq_len == 0)
2015 bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock)
2017 struct bufdomain *bd;
2019 if (bp->b_qindex != QUEUE_NONE)
2020 panic("bq_insert: free buffer %p onto another queue?", bp);
2023 if (bp->b_flags & B_AGE) {
2024 /* Place this buf directly on the real queue. */
2025 if (bq->bq_index == QUEUE_CLEAN)
2028 TAILQ_INSERT_HEAD(&bq->bq_queue, bp, b_freelist);
2031 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist);
2033 bp->b_flags &= ~(B_AGE | B_REUSE);
2035 bp->b_qindex = bq->bq_index;
2036 bp->b_subqueue = bq->bq_subqueue;
2039 * Unlock before we notify so that we don't wakeup a waiter that
2040 * fails a trylock on the buf and sleeps again.
2045 if (bp->b_qindex == QUEUE_CLEAN) {
2047 * Flush the per-cpu queue and notify any waiters.
2049 if (bd->bd_wanted || (bq != bd->bd_cleanq &&
2050 bq->bq_len >= bd->bd_lim))
2059 * Free the kva allocation for a buffer.
2063 bufkva_free(struct buf *bp)
2067 if (bp->b_kvasize == 0) {
2068 KASSERT(bp->b_kvabase == unmapped_buf &&
2069 bp->b_data == unmapped_buf,
2070 ("Leaked KVA space on %p", bp));
2071 } else if (buf_mapped(bp))
2072 BUF_CHECK_MAPPED(bp);
2074 BUF_CHECK_UNMAPPED(bp);
2076 if (bp->b_kvasize == 0)
2079 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize);
2080 counter_u64_add(bufkvaspace, -bp->b_kvasize);
2081 counter_u64_add(buffreekvacnt, 1);
2082 bp->b_data = bp->b_kvabase = unmapped_buf;
2089 * Allocate the buffer KVA and set b_kvasize and b_kvabase.
2092 bufkva_alloc(struct buf *bp, int maxsize, int gbflags)
2097 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0,
2098 ("Invalid gbflags 0x%x in %s", gbflags, __func__));
2099 MPASS((bp->b_flags & B_MAXPHYS) == 0);
2100 KASSERT(maxsize <= maxbcachebuf,
2101 ("bufkva_alloc kva too large %d %u", maxsize, maxbcachebuf));
2106 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr);
2109 * Buffer map is too fragmented. Request the caller
2110 * to defragment the map.
2114 bp->b_kvabase = (caddr_t)addr;
2115 bp->b_kvasize = maxsize;
2116 counter_u64_add(bufkvaspace, bp->b_kvasize);
2117 if ((gbflags & GB_UNMAPPED) != 0) {
2118 bp->b_data = unmapped_buf;
2119 BUF_CHECK_UNMAPPED(bp);
2121 bp->b_data = bp->b_kvabase;
2122 BUF_CHECK_MAPPED(bp);
2130 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem
2131 * callback that fires to avoid returning failure.
2134 bufkva_reclaim(vmem_t *vmem, int flags)
2141 for (i = 0; i < 5; i++) {
2142 for (q = 0; q < buf_domains; q++)
2143 if (buf_recycle(&bdomain[q], true) != 0)
2152 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must
2153 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set,
2154 * the buffer is valid and we do not have to do anything.
2157 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize, int cnt,
2158 struct ucred * cred, int flags, void (*ckhashfunc)(struct buf *))
2166 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
2167 if (inmem(vp, *rablkno))
2169 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0);
2170 if ((rabp->b_flags & B_CACHE) != 0) {
2177 racct_add_buf(curproc, rabp, 0);
2178 PROC_UNLOCK(curproc);
2181 td->td_ru.ru_inblock++;
2182 rabp->b_flags |= B_ASYNC;
2183 rabp->b_flags &= ~B_INVAL;
2184 if ((flags & GB_CKHASH) != 0) {
2185 rabp->b_flags |= B_CKHASH;
2186 rabp->b_ckhashcalc = ckhashfunc;
2188 rabp->b_ioflags &= ~BIO_ERROR;
2189 rabp->b_iocmd = BIO_READ;
2190 if (rabp->b_rcred == NOCRED && cred != NOCRED)
2191 rabp->b_rcred = crhold(cred);
2192 vfs_busy_pages(rabp, 0);
2194 rabp->b_iooffset = dbtob(rabp->b_blkno);
2200 * Entry point for bread() and breadn() via #defines in sys/buf.h.
2202 * Get a buffer with the specified data. Look in the cache first. We
2203 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
2204 * is set, the buffer is valid and we do not have to do anything, see
2205 * getblk(). Also starts asynchronous I/O on read-ahead blocks.
2207 * Always return a NULL buffer pointer (in bpp) when returning an error.
2209 * The blkno parameter is the logical block being requested. Normally
2210 * the mapping of logical block number to disk block address is done
2211 * by calling VOP_BMAP(). However, if the mapping is already known, the
2212 * disk block address can be passed using the dblkno parameter. If the
2213 * disk block address is not known, then the same value should be passed
2214 * for blkno and dblkno.
2217 breadn_flags(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size,
2218 daddr_t *rablkno, int *rabsize, int cnt, struct ucred *cred, int flags,
2219 void (*ckhashfunc)(struct buf *), struct buf **bpp)
2223 int error, readwait, rv;
2225 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size);
2228 * Can only return NULL if GB_LOCK_NOWAIT or GB_SPARSE flags
2231 error = getblkx(vp, blkno, dblkno, size, 0, 0, flags, &bp);
2236 KASSERT(blkno == bp->b_lblkno,
2237 ("getblkx returned buffer for blkno %jd instead of blkno %jd",
2238 (intmax_t)bp->b_lblkno, (intmax_t)blkno));
2239 flags &= ~GB_NOSPARSE;
2243 * If not found in cache, do some I/O
2246 if ((bp->b_flags & B_CACHE) == 0) {
2249 PROC_LOCK(td->td_proc);
2250 racct_add_buf(td->td_proc, bp, 0);
2251 PROC_UNLOCK(td->td_proc);
2254 td->td_ru.ru_inblock++;
2255 bp->b_iocmd = BIO_READ;
2256 bp->b_flags &= ~B_INVAL;
2257 if ((flags & GB_CKHASH) != 0) {
2258 bp->b_flags |= B_CKHASH;
2259 bp->b_ckhashcalc = ckhashfunc;
2261 if ((flags & GB_CVTENXIO) != 0)
2262 bp->b_xflags |= BX_CVTENXIO;
2263 bp->b_ioflags &= ~BIO_ERROR;
2264 if (bp->b_rcred == NOCRED && cred != NOCRED)
2265 bp->b_rcred = crhold(cred);
2266 vfs_busy_pages(bp, 0);
2267 bp->b_iooffset = dbtob(bp->b_blkno);
2273 * Attempt to initiate asynchronous I/O on read-ahead blocks.
2275 breada(vp, rablkno, rabsize, cnt, cred, flags, ckhashfunc);
2289 * Write, release buffer on completion. (Done by iodone
2290 * if async). Do not bother writing anything if the buffer
2293 * Note that we set B_CACHE here, indicating that buffer is
2294 * fully valid and thus cacheable. This is true even of NFS
2295 * now so we set it generally. This could be set either here
2296 * or in biodone() since the I/O is synchronous. We put it
2300 bufwrite(struct buf *bp)
2307 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2308 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) {
2309 bp->b_flags |= B_INVAL | B_RELBUF;
2310 bp->b_flags &= ~B_CACHE;
2314 if (bp->b_flags & B_INVAL) {
2319 if (bp->b_flags & B_BARRIER)
2320 atomic_add_long(&barrierwrites, 1);
2322 oldflags = bp->b_flags;
2324 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG),
2325 ("FFS background buffer should not get here %p", bp));
2329 vp_md = vp->v_vflag & VV_MD;
2334 * Mark the buffer clean. Increment the bufobj write count
2335 * before bundirty() call, to prevent other thread from seeing
2336 * empty dirty list and zero counter for writes in progress,
2337 * falsely indicating that the bufobj is clean.
2339 bufobj_wref(bp->b_bufobj);
2342 bp->b_flags &= ~B_DONE;
2343 bp->b_ioflags &= ~BIO_ERROR;
2344 bp->b_flags |= B_CACHE;
2345 bp->b_iocmd = BIO_WRITE;
2347 vfs_busy_pages(bp, 1);
2350 * Normal bwrites pipeline writes
2352 bp->b_runningbufspace = bp->b_bufsize;
2353 space = atomic_fetchadd_long(&runningbufspace, bp->b_runningbufspace);
2358 racct_add_buf(curproc, bp, 1);
2359 PROC_UNLOCK(curproc);
2362 curthread->td_ru.ru_oublock++;
2363 if (oldflags & B_ASYNC)
2365 bp->b_iooffset = dbtob(bp->b_blkno);
2366 buf_track(bp, __func__);
2369 if ((oldflags & B_ASYNC) == 0) {
2370 int rtval = bufwait(bp);
2373 } else if (space > hirunningspace) {
2375 * don't allow the async write to saturate the I/O
2376 * system. We will not deadlock here because
2377 * we are blocking waiting for I/O that is already in-progress
2378 * to complete. We do not block here if it is the update
2379 * or syncer daemon trying to clean up as that can lead
2382 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md)
2383 waitrunningbufspace();
2390 bufbdflush(struct bufobj *bo, struct buf *bp)
2393 struct bufdomain *bd;
2395 bd = &bdomain[bo->bo_domain];
2396 if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh + 10) {
2397 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread);
2399 } else if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh) {
2402 * Try to find a buffer to flush.
2404 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2405 if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2407 LK_EXCLUSIVE | LK_NOWAIT, NULL))
2410 panic("bdwrite: found ourselves");
2412 /* Don't countdeps with the bo lock held. */
2413 if (buf_countdeps(nbp, 0)) {
2418 if (nbp->b_flags & B_CLUSTEROK) {
2419 vfs_bio_awrite(nbp);
2424 dirtybufferflushes++;
2433 * Delayed write. (Buffer is marked dirty). Do not bother writing
2434 * anything if the buffer is marked invalid.
2436 * Note that since the buffer must be completely valid, we can safely
2437 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
2438 * biodone() in order to prevent getblk from writing the buffer
2439 * out synchronously.
2442 bdwrite(struct buf *bp)
2444 struct thread *td = curthread;
2448 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2449 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2450 KASSERT((bp->b_flags & B_BARRIER) == 0,
2451 ("Barrier request in delayed write %p", bp));
2453 if (bp->b_flags & B_INVAL) {
2459 * If we have too many dirty buffers, don't create any more.
2460 * If we are wildly over our limit, then force a complete
2461 * cleanup. Otherwise, just keep the situation from getting
2462 * out of control. Note that we have to avoid a recursive
2463 * disaster and not try to clean up after our own cleanup!
2467 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) {
2468 td->td_pflags |= TDP_INBDFLUSH;
2470 td->td_pflags &= ~TDP_INBDFLUSH;
2476 * Set B_CACHE, indicating that the buffer is fully valid. This is
2477 * true even of NFS now.
2479 bp->b_flags |= B_CACHE;
2482 * This bmap keeps the system from needing to do the bmap later,
2483 * perhaps when the system is attempting to do a sync. Since it
2484 * is likely that the indirect block -- or whatever other datastructure
2485 * that the filesystem needs is still in memory now, it is a good
2486 * thing to do this. Note also, that if the pageout daemon is
2487 * requesting a sync -- there might not be enough memory to do
2488 * the bmap then... So, this is important to do.
2490 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) {
2491 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
2494 buf_track(bp, __func__);
2497 * Set the *dirty* buffer range based upon the VM system dirty
2500 * Mark the buffer pages as clean. We need to do this here to
2501 * satisfy the vnode_pager and the pageout daemon, so that it
2502 * thinks that the pages have been "cleaned". Note that since
2503 * the pages are in a delayed write buffer -- the VFS layer
2504 * "will" see that the pages get written out on the next sync,
2505 * or perhaps the cluster will be completed.
2507 vfs_clean_pages_dirty_buf(bp);
2511 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
2512 * due to the softdep code.
2519 * Turn buffer into delayed write request. We must clear BIO_READ and
2520 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
2521 * itself to properly update it in the dirty/clean lists. We mark it
2522 * B_DONE to ensure that any asynchronization of the buffer properly
2523 * clears B_DONE ( else a panic will occur later ).
2525 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
2526 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
2527 * should only be called if the buffer is known-good.
2529 * Since the buffer is not on a queue, we do not update the numfreebuffers
2532 * The buffer must be on QUEUE_NONE.
2535 bdirty(struct buf *bp)
2538 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X",
2539 bp, bp->b_vp, bp->b_flags);
2540 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2541 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2542 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
2543 bp->b_flags &= ~(B_RELBUF);
2544 bp->b_iocmd = BIO_WRITE;
2546 if ((bp->b_flags & B_DELWRI) == 0) {
2547 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI;
2556 * Clear B_DELWRI for buffer.
2558 * Since the buffer is not on a queue, we do not update the numfreebuffers
2561 * The buffer must be on QUEUE_NONE.
2565 bundirty(struct buf *bp)
2568 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2569 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2570 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE,
2571 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
2573 if (bp->b_flags & B_DELWRI) {
2574 bp->b_flags &= ~B_DELWRI;
2579 * Since it is now being written, we can clear its deferred write flag.
2581 bp->b_flags &= ~B_DEFERRED;
2587 * Asynchronous write. Start output on a buffer, but do not wait for
2588 * it to complete. The buffer is released when the output completes.
2590 * bwrite() ( or the VOP routine anyway ) is responsible for handling
2591 * B_INVAL buffers. Not us.
2594 bawrite(struct buf *bp)
2597 bp->b_flags |= B_ASYNC;
2604 * Asynchronous barrier write. Start output on a buffer, but do not
2605 * wait for it to complete. Place a write barrier after this write so
2606 * that this buffer and all buffers written before it are committed to
2607 * the disk before any buffers written after this write are committed
2608 * to the disk. The buffer is released when the output completes.
2611 babarrierwrite(struct buf *bp)
2614 bp->b_flags |= B_ASYNC | B_BARRIER;
2621 * Synchronous barrier write. Start output on a buffer and wait for
2622 * it to complete. Place a write barrier after this write so that
2623 * this buffer and all buffers written before it are committed to
2624 * the disk before any buffers written after this write are committed
2625 * to the disk. The buffer is released when the output completes.
2628 bbarrierwrite(struct buf *bp)
2631 bp->b_flags |= B_BARRIER;
2632 return (bwrite(bp));
2638 * Called prior to the locking of any vnodes when we are expecting to
2639 * write. We do not want to starve the buffer cache with too many
2640 * dirty buffers so we block here. By blocking prior to the locking
2641 * of any vnodes we attempt to avoid the situation where a locked vnode
2642 * prevents the various system daemons from flushing related buffers.
2648 if (buf_dirty_count_severe()) {
2649 mtx_lock(&bdirtylock);
2650 while (buf_dirty_count_severe()) {
2652 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4),
2655 mtx_unlock(&bdirtylock);
2660 * Return true if we have too many dirty buffers.
2663 buf_dirty_count_severe(void)
2666 return (!BIT_EMPTY(BUF_DOMAINS, &bdhidirty));
2672 * Release a busy buffer and, if requested, free its resources. The
2673 * buffer will be stashed in the appropriate bufqueue[] allowing it
2674 * to be accessed later as a cache entity or reused for other purposes.
2677 brelse(struct buf *bp)
2679 struct mount *v_mnt;
2683 * Many functions erroneously call brelse with a NULL bp under rare
2684 * error conditions. Simply return when called with a NULL bp.
2688 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X",
2689 bp, bp->b_vp, bp->b_flags);
2690 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2691 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2692 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0,
2693 ("brelse: non-VMIO buffer marked NOREUSE"));
2695 if (BUF_LOCKRECURSED(bp)) {
2697 * Do not process, in particular, do not handle the
2698 * B_INVAL/B_RELBUF and do not release to free list.
2704 if (bp->b_flags & B_MANAGED) {
2709 if (LIST_EMPTY(&bp->b_dep)) {
2710 bp->b_flags &= ~B_IOSTARTED;
2712 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2713 ("brelse: SU io not finished bp %p", bp));
2716 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) {
2717 BO_LOCK(bp->b_bufobj);
2718 bp->b_vflags &= ~BV_BKGRDERR;
2719 BO_UNLOCK(bp->b_bufobj);
2723 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2724 (bp->b_flags & B_INVALONERR)) {
2726 * Forced invalidation of dirty buffer contents, to be used
2727 * after a failed write in the rare case that the loss of the
2728 * contents is acceptable. The buffer is invalidated and
2731 bp->b_flags |= B_INVAL | B_RELBUF | B_NOCACHE;
2732 bp->b_flags &= ~(B_ASYNC | B_CACHE);
2735 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) &&
2736 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) &&
2737 !(bp->b_flags & B_INVAL)) {
2739 * Failed write, redirty. All errors except ENXIO (which
2740 * means the device is gone) are treated as being
2743 * XXX Treating EIO as transient is not correct; the
2744 * contract with the local storage device drivers is that
2745 * they will only return EIO once the I/O is no longer
2746 * retriable. Network I/O also respects this through the
2747 * guarantees of TCP and/or the internal retries of NFS.
2748 * ENOMEM might be transient, but we also have no way of
2749 * knowing when its ok to retry/reschedule. In general,
2750 * this entire case should be made obsolete through better
2751 * error handling/recovery and resource scheduling.
2753 * Do this also for buffers that failed with ENXIO, but have
2754 * non-empty dependencies - the soft updates code might need
2755 * to access the buffer to untangle them.
2757 * Must clear BIO_ERROR to prevent pages from being scrapped.
2759 bp->b_ioflags &= ~BIO_ERROR;
2761 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) ||
2762 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) {
2764 * Either a failed read I/O, or we were asked to free or not
2765 * cache the buffer, or we failed to write to a device that's
2766 * no longer present.
2768 bp->b_flags |= B_INVAL;
2769 if (!LIST_EMPTY(&bp->b_dep))
2771 if (bp->b_flags & B_DELWRI)
2773 bp->b_flags &= ~(B_DELWRI | B_CACHE);
2774 if ((bp->b_flags & B_VMIO) == 0) {
2782 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate()
2783 * is called with B_DELWRI set, the underlying pages may wind up
2784 * getting freed causing a previous write (bdwrite()) to get 'lost'
2785 * because pages associated with a B_DELWRI bp are marked clean.
2787 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even
2788 * if B_DELWRI is set.
2790 if (bp->b_flags & B_DELWRI)
2791 bp->b_flags &= ~B_RELBUF;
2794 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
2795 * constituted, not even NFS buffers now. Two flags effect this. If
2796 * B_INVAL, the struct buf is invalidated but the VM object is kept
2797 * around ( i.e. so it is trivial to reconstitute the buffer later ).
2799 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be
2800 * invalidated. BIO_ERROR cannot be set for a failed write unless the
2801 * buffer is also B_INVAL because it hits the re-dirtying code above.
2803 * Normally we can do this whether a buffer is B_DELWRI or not. If
2804 * the buffer is an NFS buffer, it is tracking piecemeal writes or
2805 * the commit state and we cannot afford to lose the buffer. If the
2806 * buffer has a background write in progress, we need to keep it
2807 * around to prevent it from being reconstituted and starting a second
2811 v_mnt = bp->b_vp != NULL ? bp->b_vp->v_mount : NULL;
2813 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE ||
2814 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) &&
2815 (v_mnt == NULL || (v_mnt->mnt_vfc->vfc_flags & VFCF_NETWORK) == 0 ||
2816 vn_isdisk(bp->b_vp) || (bp->b_flags & B_DELWRI) == 0)) {
2817 vfs_vmio_invalidate(bp);
2821 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 ||
2822 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) {
2824 bp->b_flags &= ~B_NOREUSE;
2825 if (bp->b_vp != NULL)
2830 * If the buffer has junk contents signal it and eventually
2831 * clean up B_DELWRI and diassociate the vnode so that gbincore()
2834 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 ||
2835 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0)
2836 bp->b_flags |= B_INVAL;
2837 if (bp->b_flags & B_INVAL) {
2838 if (bp->b_flags & B_DELWRI)
2844 buf_track(bp, __func__);
2846 /* buffers with no memory */
2847 if (bp->b_bufsize == 0) {
2851 /* buffers with junk contents */
2852 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) ||
2853 (bp->b_ioflags & BIO_ERROR)) {
2854 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA);
2855 if (bp->b_vflags & BV_BKGRDINPROG)
2856 panic("losing buffer 2");
2857 qindex = QUEUE_CLEAN;
2858 bp->b_flags |= B_AGE;
2859 /* remaining buffers */
2860 } else if (bp->b_flags & B_DELWRI)
2861 qindex = QUEUE_DIRTY;
2863 qindex = QUEUE_CLEAN;
2865 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY))
2866 panic("brelse: not dirty");
2868 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
2869 bp->b_xflags &= ~(BX_CVTENXIO);
2870 /* binsfree unlocks bp. */
2871 binsfree(bp, qindex);
2875 * Release a buffer back to the appropriate queue but do not try to free
2876 * it. The buffer is expected to be used again soon.
2878 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
2879 * biodone() to requeue an async I/O on completion. It is also used when
2880 * known good buffers need to be requeued but we think we may need the data
2883 * XXX we should be able to leave the B_RELBUF hint set on completion.
2886 bqrelse(struct buf *bp)
2890 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2891 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
2892 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
2894 qindex = QUEUE_NONE;
2895 if (BUF_LOCKRECURSED(bp)) {
2896 /* do not release to free list */
2900 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
2901 bp->b_xflags &= ~(BX_CVTENXIO);
2903 if (LIST_EMPTY(&bp->b_dep)) {
2904 bp->b_flags &= ~B_IOSTARTED;
2906 KASSERT((bp->b_flags & B_IOSTARTED) == 0,
2907 ("bqrelse: SU io not finished bp %p", bp));
2910 if (bp->b_flags & B_MANAGED) {
2911 if (bp->b_flags & B_REMFREE)
2916 /* buffers with stale but valid contents */
2917 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG |
2918 BV_BKGRDERR)) == BV_BKGRDERR) {
2919 BO_LOCK(bp->b_bufobj);
2920 bp->b_vflags &= ~BV_BKGRDERR;
2921 BO_UNLOCK(bp->b_bufobj);
2922 qindex = QUEUE_DIRTY;
2924 if ((bp->b_flags & B_DELWRI) == 0 &&
2925 (bp->b_xflags & BX_VNDIRTY))
2926 panic("bqrelse: not dirty");
2927 if ((bp->b_flags & B_NOREUSE) != 0) {
2931 qindex = QUEUE_CLEAN;
2933 buf_track(bp, __func__);
2934 /* binsfree unlocks bp. */
2935 binsfree(bp, qindex);
2939 buf_track(bp, __func__);
2945 * Complete I/O to a VMIO backed page. Validate the pages as appropriate,
2946 * restore bogus pages.
2949 vfs_vmio_iodone(struct buf *bp)
2954 struct vnode *vp __unused;
2955 int i, iosize, resid;
2958 obj = bp->b_bufobj->bo_object;
2959 KASSERT(blockcount_read(&obj->paging_in_progress) >= bp->b_npages,
2960 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)",
2961 blockcount_read(&obj->paging_in_progress), bp->b_npages));
2964 VNPASS(vp->v_holdcnt > 0, vp);
2965 VNPASS(vp->v_object != NULL, vp);
2967 foff = bp->b_offset;
2968 KASSERT(bp->b_offset != NOOFFSET,
2969 ("vfs_vmio_iodone: bp %p has no buffer offset", bp));
2972 iosize = bp->b_bcount - bp->b_resid;
2973 for (i = 0; i < bp->b_npages; i++) {
2974 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2979 * cleanup bogus pages, restoring the originals
2982 if (m == bogus_page) {
2984 m = vm_page_relookup(obj, OFF_TO_IDX(foff));
2986 panic("biodone: page disappeared!");
2988 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) {
2990 * In the write case, the valid and clean bits are
2991 * already changed correctly ( see bdwrite() ), so we
2992 * only need to do this here in the read case.
2994 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK,
2995 resid)) == 0, ("vfs_vmio_iodone: page %p "
2996 "has unexpected dirty bits", m));
2997 vfs_page_set_valid(bp, foff, m);
2999 KASSERT(OFF_TO_IDX(foff) == m->pindex,
3000 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch",
3001 (intmax_t)foff, (uintmax_t)m->pindex));
3004 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3007 vm_object_pip_wakeupn(obj, bp->b_npages);
3008 if (bogus && buf_mapped(bp)) {
3009 BUF_CHECK_MAPPED(bp);
3010 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3011 bp->b_pages, bp->b_npages);
3016 * Perform page invalidation when a buffer is released. The fully invalid
3017 * pages will be reclaimed later in vfs_vmio_truncate().
3020 vfs_vmio_invalidate(struct buf *bp)
3024 int flags, i, resid, poffset, presid;
3026 if (buf_mapped(bp)) {
3027 BUF_CHECK_MAPPED(bp);
3028 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages);
3030 BUF_CHECK_UNMAPPED(bp);
3032 * Get the base offset and length of the buffer. Note that
3033 * in the VMIO case if the buffer block size is not
3034 * page-aligned then b_data pointer may not be page-aligned.
3035 * But our b_pages[] array *IS* page aligned.
3037 * block sizes less then DEV_BSIZE (usually 512) are not
3038 * supported due to the page granularity bits (m->valid,
3039 * m->dirty, etc...).
3041 * See man buf(9) for more information
3043 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3044 obj = bp->b_bufobj->bo_object;
3045 resid = bp->b_bufsize;
3046 poffset = bp->b_offset & PAGE_MASK;
3047 VM_OBJECT_WLOCK(obj);
3048 for (i = 0; i < bp->b_npages; i++) {
3050 if (m == bogus_page)
3051 panic("vfs_vmio_invalidate: Unexpected bogus page.");
3052 bp->b_pages[i] = NULL;
3054 presid = resid > (PAGE_SIZE - poffset) ?
3055 (PAGE_SIZE - poffset) : resid;
3056 KASSERT(presid >= 0, ("brelse: extra page"));
3057 vm_page_busy_acquire(m, VM_ALLOC_SBUSY);
3058 if (pmap_page_wired_mappings(m) == 0)
3059 vm_page_set_invalid(m, poffset, presid);
3061 vm_page_release_locked(m, flags);
3065 VM_OBJECT_WUNLOCK(obj);
3070 * Page-granular truncation of an existing VMIO buffer.
3073 vfs_vmio_truncate(struct buf *bp, int desiredpages)
3079 if (bp->b_npages == desiredpages)
3082 if (buf_mapped(bp)) {
3083 BUF_CHECK_MAPPED(bp);
3084 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
3085 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages);
3087 BUF_CHECK_UNMAPPED(bp);
3090 * The object lock is needed only if we will attempt to free pages.
3092 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0;
3093 if ((bp->b_flags & B_DIRECT) != 0) {
3094 flags |= VPR_TRYFREE;
3095 obj = bp->b_bufobj->bo_object;
3096 VM_OBJECT_WLOCK(obj);
3100 for (i = desiredpages; i < bp->b_npages; i++) {
3102 KASSERT(m != bogus_page, ("allocbuf: bogus page found"));
3103 bp->b_pages[i] = NULL;
3105 vm_page_release_locked(m, flags);
3107 vm_page_release(m, flags);
3110 VM_OBJECT_WUNLOCK(obj);
3111 bp->b_npages = desiredpages;
3115 * Byte granular extension of VMIO buffers.
3118 vfs_vmio_extend(struct buf *bp, int desiredpages, int size)
3121 * We are growing the buffer, possibly in a
3122 * byte-granular fashion.
3130 * Step 1, bring in the VM pages from the object, allocating
3131 * them if necessary. We must clear B_CACHE if these pages
3132 * are not valid for the range covered by the buffer.
3134 obj = bp->b_bufobj->bo_object;
3135 if (bp->b_npages < desiredpages) {
3136 KASSERT(desiredpages <= atop(maxbcachebuf),
3137 ("vfs_vmio_extend past maxbcachebuf %p %d %u",
3138 bp, desiredpages, maxbcachebuf));
3141 * We must allocate system pages since blocking
3142 * here could interfere with paging I/O, no
3143 * matter which process we are.
3145 * Only exclusive busy can be tested here.
3146 * Blocking on shared busy might lead to
3147 * deadlocks once allocbuf() is called after
3148 * pages are vfs_busy_pages().
3150 (void)vm_page_grab_pages_unlocked(obj,
3151 OFF_TO_IDX(bp->b_offset) + bp->b_npages,
3152 VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY |
3153 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED,
3154 &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages);
3155 bp->b_npages = desiredpages;
3159 * Step 2. We've loaded the pages into the buffer,
3160 * we have to figure out if we can still have B_CACHE
3161 * set. Note that B_CACHE is set according to the
3162 * byte-granular range ( bcount and size ), not the
3163 * aligned range ( newbsize ).
3165 * The VM test is against m->valid, which is DEV_BSIZE
3166 * aligned. Needless to say, the validity of the data
3167 * needs to also be DEV_BSIZE aligned. Note that this
3168 * fails with NFS if the server or some other client
3169 * extends the file's EOF. If our buffer is resized,
3170 * B_CACHE may remain set! XXX
3172 toff = bp->b_bcount;
3173 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
3174 while ((bp->b_flags & B_CACHE) && toff < size) {
3177 if (tinc > (size - toff))
3179 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT;
3180 m = bp->b_pages[pi];
3181 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m);
3187 * Step 3, fixup the KVA pmap.
3192 BUF_CHECK_UNMAPPED(bp);
3196 * Check to see if a block at a particular lbn is available for a clustered
3200 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno)
3207 /* If the buf isn't in core skip it */
3208 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL)
3211 /* If the buf is busy we don't want to wait for it */
3212 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
3215 /* Only cluster with valid clusterable delayed write buffers */
3216 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) !=
3217 (B_DELWRI | B_CLUSTEROK))
3220 if (bpa->b_bufsize != size)
3224 * Check to see if it is in the expected place on disk and that the
3225 * block has been mapped.
3227 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno))
3237 * Implement clustered async writes for clearing out B_DELWRI buffers.
3238 * This is much better then the old way of writing only one buffer at
3239 * a time. Note that we may not be presented with the buffers in the
3240 * correct order, so we search for the cluster in both directions.
3243 vfs_bio_awrite(struct buf *bp)
3248 daddr_t lblkno = bp->b_lblkno;
3249 struct vnode *vp = bp->b_vp;
3257 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0;
3259 * right now we support clustered writing only to regular files. If
3260 * we find a clusterable block we could be in the middle of a cluster
3261 * rather then at the beginning.
3263 if ((vp->v_type == VREG) &&
3264 (vp->v_mount != 0) && /* Only on nodes that have the size info */
3265 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
3266 size = vp->v_mount->mnt_stat.f_iosize;
3267 maxcl = maxphys / size;
3270 for (i = 1; i < maxcl; i++)
3271 if (vfs_bio_clcheck(vp, size, lblkno + i,
3272 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0)
3275 for (j = 1; i + j <= maxcl && j <= lblkno; j++)
3276 if (vfs_bio_clcheck(vp, size, lblkno - j,
3277 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0)
3283 * this is a possible cluster write
3287 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl,
3293 bp->b_flags |= B_ASYNC;
3295 * default (old) behavior, writing out only one block
3297 * XXX returns b_bufsize instead of b_bcount for nwritten?
3299 nwritten = bp->b_bufsize;
3308 * Allocate KVA for an empty buf header according to gbflags.
3311 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize)
3314 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) {
3316 * In order to keep fragmentation sane we only allocate kva
3317 * in BKVASIZE chunks. XXX with vmem we can do page size.
3319 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
3321 if (maxsize != bp->b_kvasize &&
3322 bufkva_alloc(bp, maxsize, gbflags))
3331 * Find and initialize a new buffer header, freeing up existing buffers
3332 * in the bufqueues as necessary. The new buffer is returned locked.
3335 * We have insufficient buffer headers
3336 * We have insufficient buffer space
3337 * buffer_arena is too fragmented ( space reservation fails )
3338 * If we have to flush dirty buffers ( but we try to avoid this )
3340 * The caller is responsible for releasing the reserved bufspace after
3341 * allocbuf() is called.
3344 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags)
3346 struct bufdomain *bd;
3348 bool metadata, reserved;
3351 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3352 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3353 if (!unmapped_buf_allowed)
3354 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3356 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 ||
3364 bd = &bdomain[vp->v_bufobj.bo_domain];
3366 counter_u64_add(getnewbufcalls, 1);
3369 if (reserved == false &&
3370 bufspace_reserve(bd, maxsize, metadata) != 0) {
3371 counter_u64_add(getnewbufrestarts, 1);
3375 if ((bp = buf_alloc(bd)) == NULL) {
3376 counter_u64_add(getnewbufrestarts, 1);
3379 if (getnewbuf_kva(bp, gbflags, maxsize) == 0)
3382 } while (buf_recycle(bd, false) == 0);
3385 bufspace_release(bd, maxsize);
3387 bp->b_flags |= B_INVAL;
3390 bufspace_wait(bd, vp, gbflags, slpflag, slptimeo);
3398 * buffer flushing daemon. Buffers are normally flushed by the
3399 * update daemon but if it cannot keep up this process starts to
3400 * take the load in an attempt to prevent getnewbuf() from blocking.
3402 static struct kproc_desc buf_kp = {
3407 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp);
3410 buf_flush(struct vnode *vp, struct bufdomain *bd, int target)
3414 flushed = flushbufqueues(vp, bd, target, 0);
3417 * Could not find any buffers without rollback
3418 * dependencies, so just write the first one
3419 * in the hopes of eventually making progress.
3421 if (vp != NULL && target > 2)
3423 flushbufqueues(vp, bd, target, 1);
3429 buf_daemon_shutdown(void *arg __unused, int howto __unused)
3433 if (KERNEL_PANICKED())
3438 wakeup(&bd_request);
3439 error = msleep(&bd_shutdown, &bdlock, 0, "buf_daemon_shutdown",
3441 mtx_unlock(&bdlock);
3443 printf("bufdaemon wait error: %d\n", error);
3449 struct bufdomain *bd;
3455 * This process needs to be suspended prior to shutdown sync.
3457 EVENTHANDLER_REGISTER(shutdown_pre_sync, buf_daemon_shutdown, NULL,
3458 SHUTDOWN_PRI_LAST + 100);
3461 * Start the buf clean daemons as children threads.
3463 for (i = 0 ; i < buf_domains; i++) {
3466 error = kthread_add((void (*)(void *))bufspace_daemon,
3467 &bdomain[i], curproc, NULL, 0, 0, "bufspacedaemon-%d", i);
3469 panic("error %d spawning bufspace daemon", error);
3473 * This process is allowed to take the buffer cache to the limit
3475 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED;
3477 while (!bd_shutdown) {
3479 mtx_unlock(&bdlock);
3482 * Save speedupreq for this pass and reset to capture new
3485 speedupreq = bd_speedupreq;
3489 * Flush each domain sequentially according to its level and
3490 * the speedup request.
3492 for (i = 0; i < buf_domains; i++) {
3495 lodirty = bd->bd_numdirtybuffers / 2;
3497 lodirty = bd->bd_lodirtybuffers;
3498 while (bd->bd_numdirtybuffers > lodirty) {
3499 if (buf_flush(NULL, bd,
3500 bd->bd_numdirtybuffers - lodirty) == 0)
3502 kern_yield(PRI_USER);
3507 * Only clear bd_request if we have reached our low water
3508 * mark. The buf_daemon normally waits 1 second and
3509 * then incrementally flushes any dirty buffers that have
3510 * built up, within reason.
3512 * If we were unable to hit our low water mark and couldn't
3513 * find any flushable buffers, we sleep for a short period
3514 * to avoid endless loops on unlockable buffers.
3519 if (BIT_EMPTY(BUF_DOMAINS, &bdlodirty)) {
3521 * We reached our low water mark, reset the
3522 * request and sleep until we are needed again.
3523 * The sleep is just so the suspend code works.
3527 * Do an extra wakeup in case dirty threshold
3528 * changed via sysctl and the explicit transition
3529 * out of shortfall was missed.
3532 if (runningbufspace <= lorunningspace)
3534 msleep(&bd_request, &bdlock, PVM, "psleep", hz);
3537 * We couldn't find any flushable dirty buffers but
3538 * still have too many dirty buffers, we
3539 * have to sleep and try again. (rare)
3541 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10);
3544 wakeup(&bd_shutdown);
3545 mtx_unlock(&bdlock);
3552 * Try to flush a buffer in the dirty queue. We must be careful to
3553 * free up B_INVAL buffers instead of write them, which NFS is
3554 * particularly sensitive to.
3556 static int flushwithdeps = 0;
3557 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW | CTLFLAG_STATS,
3559 "Number of buffers flushed with dependencies that require rollbacks");
3562 flushbufqueues(struct vnode *lvp, struct bufdomain *bd, int target,
3565 struct bufqueue *bq;
3566 struct buf *sentinel;
3576 bq = &bd->bd_dirtyq;
3578 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO);
3579 sentinel->b_qindex = QUEUE_SENTINEL;
3581 TAILQ_INSERT_HEAD(&bq->bq_queue, sentinel, b_freelist);
3583 while (flushed != target) {
3586 bp = TAILQ_NEXT(sentinel, b_freelist);
3588 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3589 TAILQ_INSERT_AFTER(&bq->bq_queue, bp, sentinel,
3596 * Skip sentinels inserted by other invocations of the
3597 * flushbufqueues(), taking care to not reorder them.
3599 * Only flush the buffers that belong to the
3600 * vnode locked by the curthread.
3602 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL &&
3607 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL);
3613 * BKGRDINPROG can only be set with the buf and bufobj
3614 * locks both held. We tolerate a race to clear it here.
3616 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 ||
3617 (bp->b_flags & B_DELWRI) == 0) {
3621 if (bp->b_flags & B_INVAL) {
3628 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) {
3629 if (flushdeps == 0) {
3637 * We must hold the lock on a vnode before writing
3638 * one of its buffers. Otherwise we may confuse, or
3639 * in the case of a snapshot vnode, deadlock the
3642 * The lock order here is the reverse of the normal
3643 * of vnode followed by buf lock. This is ok because
3644 * the NOWAIT will prevent deadlock.
3647 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3653 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3655 ASSERT_VOP_LOCKED(vp, "getbuf");
3657 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 :
3658 vn_lock(vp, LK_TRYUPGRADE);
3661 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X",
3662 bp, bp->b_vp, bp->b_flags);
3663 if (curproc == bufdaemonproc) {
3668 counter_u64_add(notbufdflushes, 1);
3670 vn_finished_write(mp);
3673 flushwithdeps += hasdeps;
3677 * Sleeping on runningbufspace while holding
3678 * vnode lock leads to deadlock.
3680 if (curproc == bufdaemonproc &&
3681 runningbufspace > hirunningspace)
3682 waitrunningbufspace();
3685 vn_finished_write(mp);
3689 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist);
3691 free(sentinel, M_TEMP);
3696 * Check to see if a block is currently memory resident.
3699 incore(struct bufobj *bo, daddr_t blkno)
3701 return (gbincore_unlocked(bo, blkno));
3705 * Returns true if no I/O is needed to access the
3706 * associated VM object. This is like incore except
3707 * it also hunts around in the VM system for the data.
3710 inmem(struct vnode * vp, daddr_t blkno)
3713 vm_offset_t toff, tinc, size;
3718 ASSERT_VOP_LOCKED(vp, "inmem");
3720 if (incore(&vp->v_bufobj, blkno))
3722 if (vp->v_mount == NULL)
3729 if (size > vp->v_mount->mnt_stat.f_iosize)
3730 size = vp->v_mount->mnt_stat.f_iosize;
3731 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
3733 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
3734 m = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3740 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
3741 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
3743 * Consider page validity only if page mapping didn't change
3746 valid = vm_page_is_valid(m,
3747 (vm_offset_t)((toff + off) & PAGE_MASK), tinc);
3748 n = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff));
3760 * Set the dirty range for a buffer based on the status of the dirty
3761 * bits in the pages comprising the buffer. The range is limited
3762 * to the size of the buffer.
3764 * Tell the VM system that the pages associated with this buffer
3765 * are clean. This is used for delayed writes where the data is
3766 * going to go to disk eventually without additional VM intevention.
3768 * Note that while we only really need to clean through to b_bcount, we
3769 * just go ahead and clean through to b_bufsize.
3772 vfs_clean_pages_dirty_buf(struct buf *bp)
3774 vm_ooffset_t foff, noff, eoff;
3778 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0)
3781 foff = bp->b_offset;
3782 KASSERT(bp->b_offset != NOOFFSET,
3783 ("vfs_clean_pages_dirty_buf: no buffer offset"));
3785 vfs_busy_pages_acquire(bp);
3786 vfs_setdirty_range(bp);
3787 for (i = 0; i < bp->b_npages; i++) {
3788 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3790 if (eoff > bp->b_offset + bp->b_bufsize)
3791 eoff = bp->b_offset + bp->b_bufsize;
3793 vfs_page_set_validclean(bp, foff, m);
3794 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3797 vfs_busy_pages_release(bp);
3801 vfs_setdirty_range(struct buf *bp)
3803 vm_offset_t boffset;
3804 vm_offset_t eoffset;
3808 * test the pages to see if they have been modified directly
3809 * by users through the VM system.
3811 for (i = 0; i < bp->b_npages; i++)
3812 vm_page_test_dirty(bp->b_pages[i]);
3815 * Calculate the encompassing dirty range, boffset and eoffset,
3816 * (eoffset - boffset) bytes.
3819 for (i = 0; i < bp->b_npages; i++) {
3820 if (bp->b_pages[i]->dirty)
3823 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3825 for (i = bp->b_npages - 1; i >= 0; --i) {
3826 if (bp->b_pages[i]->dirty) {
3830 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
3833 * Fit it to the buffer.
3836 if (eoffset > bp->b_bcount)
3837 eoffset = bp->b_bcount;
3840 * If we have a good dirty range, merge with the existing
3844 if (boffset < eoffset) {
3845 if (bp->b_dirtyoff > boffset)
3846 bp->b_dirtyoff = boffset;
3847 if (bp->b_dirtyend < eoffset)
3848 bp->b_dirtyend = eoffset;
3853 * Allocate the KVA mapping for an existing buffer.
3854 * If an unmapped buffer is provided but a mapped buffer is requested, take
3855 * also care to properly setup mappings between pages and KVA.
3858 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags)
3860 int bsize, maxsize, need_mapping, need_kva;
3863 need_mapping = bp->b_data == unmapped_buf &&
3864 (gbflags & GB_UNMAPPED) == 0;
3865 need_kva = bp->b_kvabase == unmapped_buf &&
3866 bp->b_data == unmapped_buf &&
3867 (gbflags & GB_KVAALLOC) != 0;
3868 if (!need_mapping && !need_kva)
3871 BUF_CHECK_UNMAPPED(bp);
3873 if (need_mapping && bp->b_kvabase != unmapped_buf) {
3875 * Buffer is not mapped, but the KVA was already
3876 * reserved at the time of the instantiation. Use the
3883 * Calculate the amount of the address space we would reserve
3884 * if the buffer was mapped.
3886 bsize = vn_isdisk(bp->b_vp) ? DEV_BSIZE : bp->b_bufobj->bo_bsize;
3887 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
3888 offset = blkno * bsize;
3889 maxsize = size + (offset & PAGE_MASK);
3890 maxsize = imax(maxsize, bsize);
3892 while (bufkva_alloc(bp, maxsize, gbflags) != 0) {
3893 if ((gbflags & GB_NOWAIT_BD) != 0) {
3895 * XXXKIB: defragmentation cannot
3896 * succeed, not sure what else to do.
3898 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp);
3900 counter_u64_add(mappingrestarts, 1);
3901 bufspace_wait(bufdomain(bp), bp->b_vp, gbflags, 0, 0);
3905 /* b_offset is handled by bpmap_qenter. */
3906 bp->b_data = bp->b_kvabase;
3907 BUF_CHECK_MAPPED(bp);
3913 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo,
3919 error = getblkx(vp, blkno, blkno, size, slpflag, slptimeo, flags, &bp);
3928 * Get a block given a specified block and offset into a file/device.
3929 * The buffers B_DONE bit will be cleared on return, making it almost
3930 * ready for an I/O initiation. B_INVAL may or may not be set on
3931 * return. The caller should clear B_INVAL prior to initiating a
3934 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
3935 * an existing buffer.
3937 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
3938 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
3939 * and then cleared based on the backing VM. If the previous buffer is
3940 * non-0-sized but invalid, B_CACHE will be cleared.
3942 * If getblk() must create a new buffer, the new buffer is returned with
3943 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
3944 * case it is returned with B_INVAL clear and B_CACHE set based on the
3947 * getblk() also forces a bwrite() for any B_DELWRI buffer whose
3948 * B_CACHE bit is clear.
3950 * What this means, basically, is that the caller should use B_CACHE to
3951 * determine whether the buffer is fully valid or not and should clear
3952 * B_INVAL prior to issuing a read. If the caller intends to validate
3953 * the buffer by loading its data area with something, the caller needs
3954 * to clear B_INVAL. If the caller does this without issuing an I/O,
3955 * the caller should set B_CACHE ( as an optimization ), else the caller
3956 * should issue the I/O and biodone() will set B_CACHE if the I/O was
3957 * a write attempt or if it was a successful read. If the caller
3958 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR
3959 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
3961 * The blkno parameter is the logical block being requested. Normally
3962 * the mapping of logical block number to disk block address is done
3963 * by calling VOP_BMAP(). However, if the mapping is already known, the
3964 * disk block address can be passed using the dblkno parameter. If the
3965 * disk block address is not known, then the same value should be passed
3966 * for blkno and dblkno.
3969 getblkx(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size, int slpflag,
3970 int slptimeo, int flags, struct buf **bpp)
3975 int bsize, error, maxsize, vmio;
3978 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size);
3979 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC,
3980 ("GB_KVAALLOC only makes sense with GB_UNMAPPED"));
3981 if (vp->v_type != VCHR)
3982 ASSERT_VOP_LOCKED(vp, "getblk");
3983 if (size > maxbcachebuf)
3984 panic("getblk: size(%d) > maxbcachebuf(%d)\n", size,
3986 if (!unmapped_buf_allowed)
3987 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
3992 /* Attempt lockless lookup first. */
3993 bp = gbincore_unlocked(bo, blkno);
3996 * With GB_NOCREAT we must be sure about not finding the buffer
3997 * as it may have been reassigned during unlocked lookup.
3999 if ((flags & GB_NOCREAT) != 0)
4001 goto newbuf_unlocked;
4004 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL, "getblku", 0,
4009 /* Verify buf identify has not changed since lookup. */
4010 if (bp->b_bufobj == bo && bp->b_lblkno == blkno)
4011 goto foundbuf_fastpath;
4013 /* It changed, fallback to locked lookup. */
4018 bp = gbincore(bo, blkno);
4023 * Buffer is in-core. If the buffer is not busy nor managed,
4024 * it must be on a queue.
4026 lockflags = LK_EXCLUSIVE | LK_INTERLOCK |
4027 ((flags & GB_LOCK_NOWAIT) != 0 ? LK_NOWAIT : LK_SLEEPFAIL);
4029 lockflags |= (flags & GB_NOWITNESS) != 0 ? LK_NOWITNESS : 0;
4032 error = BUF_TIMELOCK(bp, lockflags,
4033 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo);
4036 * If we slept and got the lock we have to restart in case
4037 * the buffer changed identities.
4039 if (error == ENOLCK)
4041 /* We timed out or were interrupted. */
4042 else if (error != 0)
4046 /* If recursed, assume caller knows the rules. */
4047 if (BUF_LOCKRECURSED(bp))
4051 * The buffer is locked. B_CACHE is cleared if the buffer is
4052 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
4053 * and for a VMIO buffer B_CACHE is adjusted according to the
4056 if (bp->b_flags & B_INVAL)
4057 bp->b_flags &= ~B_CACHE;
4058 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
4059 bp->b_flags |= B_CACHE;
4060 if (bp->b_flags & B_MANAGED)
4061 MPASS(bp->b_qindex == QUEUE_NONE);
4066 * check for size inconsistencies for non-VMIO case.
4068 if (bp->b_bcount != size) {
4069 if ((bp->b_flags & B_VMIO) == 0 ||
4070 (size > bp->b_kvasize)) {
4071 if (bp->b_flags & B_DELWRI) {
4072 bp->b_flags |= B_NOCACHE;
4075 if (LIST_EMPTY(&bp->b_dep)) {
4076 bp->b_flags |= B_RELBUF;
4079 bp->b_flags |= B_NOCACHE;
4088 * Handle the case of unmapped buffer which should
4089 * become mapped, or the buffer for which KVA
4090 * reservation is requested.
4092 bp_unmapped_get_kva(bp, blkno, size, flags);
4095 * If the size is inconsistent in the VMIO case, we can resize
4096 * the buffer. This might lead to B_CACHE getting set or
4097 * cleared. If the size has not changed, B_CACHE remains
4098 * unchanged from its previous state.
4102 KASSERT(bp->b_offset != NOOFFSET,
4103 ("getblk: no buffer offset"));
4106 * A buffer with B_DELWRI set and B_CACHE clear must
4107 * be committed before we can return the buffer in
4108 * order to prevent the caller from issuing a read
4109 * ( due to B_CACHE not being set ) and overwriting
4112 * Most callers, including NFS and FFS, need this to
4113 * operate properly either because they assume they
4114 * can issue a read if B_CACHE is not set, or because
4115 * ( for example ) an uncached B_DELWRI might loop due
4116 * to softupdates re-dirtying the buffer. In the latter
4117 * case, B_CACHE is set after the first write completes,
4118 * preventing further loops.
4119 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
4120 * above while extending the buffer, we cannot allow the
4121 * buffer to remain with B_CACHE set after the write
4122 * completes or it will represent a corrupt state. To
4123 * deal with this we set B_NOCACHE to scrap the buffer
4126 * We might be able to do something fancy, like setting
4127 * B_CACHE in bwrite() except if B_DELWRI is already set,
4128 * so the below call doesn't set B_CACHE, but that gets real
4129 * confusing. This is much easier.
4132 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
4133 bp->b_flags |= B_NOCACHE;
4137 bp->b_flags &= ~B_DONE;
4140 * Buffer is not in-core, create new buffer. The buffer
4141 * returned by getnewbuf() is locked. Note that the returned
4142 * buffer is also considered valid (not marked B_INVAL).
4147 * If the user does not want us to create the buffer, bail out
4150 if (flags & GB_NOCREAT)
4153 bsize = vn_isdisk(vp) ? DEV_BSIZE : bo->bo_bsize;
4154 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize"));
4155 offset = blkno * bsize;
4156 vmio = vp->v_object != NULL;
4158 maxsize = size + (offset & PAGE_MASK);
4161 /* Do not allow non-VMIO notmapped buffers. */
4162 flags &= ~(GB_UNMAPPED | GB_KVAALLOC);
4164 maxsize = imax(maxsize, bsize);
4165 if ((flags & GB_NOSPARSE) != 0 && vmio &&
4167 error = VOP_BMAP(vp, blkno, NULL, &d_blkno, 0, 0);
4168 KASSERT(error != EOPNOTSUPP,
4169 ("GB_NOSPARSE from fs not supporting bmap, vp %p",
4174 return (EJUSTRETURN);
4177 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags);
4179 if (slpflag || slptimeo)
4182 * XXX This is here until the sleep path is diagnosed
4183 * enough to work under very low memory conditions.
4185 * There's an issue on low memory, 4BSD+non-preempt
4186 * systems (eg MIPS routers with 32MB RAM) where buffer
4187 * exhaustion occurs without sleeping for buffer
4188 * reclaimation. This just sticks in a loop and
4189 * constantly attempts to allocate a buffer, which
4190 * hits exhaustion and tries to wakeup bufdaemon.
4191 * This never happens because we never yield.
4193 * The real solution is to identify and fix these cases
4194 * so we aren't effectively busy-waiting in a loop
4195 * until the reclaimation path has cycles to run.
4197 kern_yield(PRI_USER);
4202 * This code is used to make sure that a buffer is not
4203 * created while the getnewbuf routine is blocked.
4204 * This can be a problem whether the vnode is locked or not.
4205 * If the buffer is created out from under us, we have to
4206 * throw away the one we just created.
4208 * Note: this must occur before we associate the buffer
4209 * with the vp especially considering limitations in
4210 * the splay tree implementation when dealing with duplicate
4214 if (gbincore(bo, blkno)) {
4216 bp->b_flags |= B_INVAL;
4217 bufspace_release(bufdomain(bp), maxsize);
4223 * Insert the buffer into the hash, so that it can
4224 * be found by incore.
4226 bp->b_lblkno = blkno;
4227 bp->b_blkno = d_blkno;
4228 bp->b_offset = offset;
4233 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
4234 * buffer size starts out as 0, B_CACHE will be set by
4235 * allocbuf() for the VMIO case prior to it testing the
4236 * backing store for validity.
4240 bp->b_flags |= B_VMIO;
4241 KASSERT(vp->v_object == bp->b_bufobj->bo_object,
4242 ("ARGH! different b_bufobj->bo_object %p %p %p\n",
4243 bp, vp->v_object, bp->b_bufobj->bo_object));
4245 bp->b_flags &= ~B_VMIO;
4246 KASSERT(bp->b_bufobj->bo_object == NULL,
4247 ("ARGH! has b_bufobj->bo_object %p %p\n",
4248 bp, bp->b_bufobj->bo_object));
4249 BUF_CHECK_MAPPED(bp);
4253 bufspace_release(bufdomain(bp), maxsize);
4254 bp->b_flags &= ~B_DONE;
4256 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp);
4258 buf_track(bp, __func__);
4259 KASSERT(bp->b_bufobj == bo,
4260 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
4266 * Get an empty, disassociated buffer of given size. The buffer is initially
4270 geteblk(int size, int flags)
4275 maxsize = (size + BKVAMASK) & ~BKVAMASK;
4276 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) {
4277 if ((flags & GB_NOWAIT_BD) &&
4278 (curthread->td_pflags & TDP_BUFNEED) != 0)
4282 bufspace_release(bufdomain(bp), maxsize);
4283 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
4288 * Truncate the backing store for a non-vmio buffer.
4291 vfs_nonvmio_truncate(struct buf *bp, int newbsize)
4294 if (bp->b_flags & B_MALLOC) {
4296 * malloced buffers are not shrunk
4298 if (newbsize == 0) {
4299 bufmallocadjust(bp, 0);
4300 free(bp->b_data, M_BIOBUF);
4301 bp->b_data = bp->b_kvabase;
4302 bp->b_flags &= ~B_MALLOC;
4306 vm_hold_free_pages(bp, newbsize);
4307 bufspace_adjust(bp, newbsize);
4311 * Extend the backing for a non-VMIO buffer.
4314 vfs_nonvmio_extend(struct buf *bp, int newbsize)
4320 * We only use malloced memory on the first allocation.
4321 * and revert to page-allocated memory when the buffer
4324 * There is a potential smp race here that could lead
4325 * to bufmallocspace slightly passing the max. It
4326 * is probably extremely rare and not worth worrying
4329 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 &&
4330 bufmallocspace < maxbufmallocspace) {
4331 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK);
4332 bp->b_flags |= B_MALLOC;
4333 bufmallocadjust(bp, newbsize);
4338 * If the buffer is growing on its other-than-first
4339 * allocation then we revert to the page-allocation
4344 if (bp->b_flags & B_MALLOC) {
4345 origbuf = bp->b_data;
4346 origbufsize = bp->b_bufsize;
4347 bp->b_data = bp->b_kvabase;
4348 bufmallocadjust(bp, 0);
4349 bp->b_flags &= ~B_MALLOC;
4350 newbsize = round_page(newbsize);
4352 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize,
4353 (vm_offset_t) bp->b_data + newbsize);
4354 if (origbuf != NULL) {
4355 bcopy(origbuf, bp->b_data, origbufsize);
4356 free(origbuf, M_BIOBUF);
4358 bufspace_adjust(bp, newbsize);
4362 * This code constitutes the buffer memory from either anonymous system
4363 * memory (in the case of non-VMIO operations) or from an associated
4364 * VM object (in the case of VMIO operations). This code is able to
4365 * resize a buffer up or down.
4367 * Note that this code is tricky, and has many complications to resolve
4368 * deadlock or inconsistent data situations. Tread lightly!!!
4369 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
4370 * the caller. Calling this code willy nilly can result in the loss of data.
4372 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
4373 * B_CACHE for the non-VMIO case.
4376 allocbuf(struct buf *bp, int size)
4380 if (bp->b_bcount == size)
4383 KASSERT(bp->b_kvasize == 0 || bp->b_kvasize >= size,
4384 ("allocbuf: buffer too small %p %#x %#x",
4385 bp, bp->b_kvasize, size));
4387 newbsize = roundup2(size, DEV_BSIZE);
4388 if ((bp->b_flags & B_VMIO) == 0) {
4389 if ((bp->b_flags & B_MALLOC) == 0)
4390 newbsize = round_page(newbsize);
4392 * Just get anonymous memory from the kernel. Don't
4393 * mess with B_CACHE.
4395 if (newbsize < bp->b_bufsize)
4396 vfs_nonvmio_truncate(bp, newbsize);
4397 else if (newbsize > bp->b_bufsize)
4398 vfs_nonvmio_extend(bp, newbsize);
4402 desiredpages = size == 0 ? 0 :
4403 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
4405 KASSERT((bp->b_flags & B_MALLOC) == 0,
4406 ("allocbuf: VMIO buffer can't be malloced %p", bp));
4409 * Set B_CACHE initially if buffer is 0 length or will become
4412 if (size == 0 || bp->b_bufsize == 0)
4413 bp->b_flags |= B_CACHE;
4415 if (newbsize < bp->b_bufsize)
4416 vfs_vmio_truncate(bp, desiredpages);
4417 /* XXX This looks as if it should be newbsize > b_bufsize */
4418 else if (size > bp->b_bcount)
4419 vfs_vmio_extend(bp, desiredpages, size);
4420 bufspace_adjust(bp, newbsize);
4422 bp->b_bcount = size; /* requested buffer size. */
4426 extern int inflight_transient_maps;
4428 static struct bio_queue nondump_bios;
4431 biodone(struct bio *bp)
4434 void (*done)(struct bio *);
4435 vm_offset_t start, end;
4437 biotrack(bp, __func__);
4440 * Avoid completing I/O when dumping after a panic since that may
4441 * result in a deadlock in the filesystem or pager code. Note that
4442 * this doesn't affect dumps that were started manually since we aim
4443 * to keep the system usable after it has been resumed.
4445 if (__predict_false(dumping && SCHEDULER_STOPPED())) {
4446 TAILQ_INSERT_HEAD(&nondump_bios, bp, bio_queue);
4449 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) {
4450 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING;
4451 bp->bio_flags |= BIO_UNMAPPED;
4452 start = trunc_page((vm_offset_t)bp->bio_data);
4453 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length);
4454 bp->bio_data = unmapped_buf;
4455 pmap_qremove(start, atop(end - start));
4456 vmem_free(transient_arena, start, end - start);
4457 atomic_add_int(&inflight_transient_maps, -1);
4459 done = bp->bio_done;
4461 * The check for done == biodone is to allow biodone to be
4462 * used as a bio_done routine.
4464 if (done == NULL || done == biodone) {
4465 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4467 bp->bio_flags |= BIO_DONE;
4475 * Wait for a BIO to finish.
4478 biowait(struct bio *bp, const char *wmesg)
4482 mtxp = mtx_pool_find(mtxpool_sleep, bp);
4484 while ((bp->bio_flags & BIO_DONE) == 0)
4485 msleep(bp, mtxp, PRIBIO, wmesg, 0);
4487 if (bp->bio_error != 0)
4488 return (bp->bio_error);
4489 if (!(bp->bio_flags & BIO_ERROR))
4495 biofinish(struct bio *bp, struct devstat *stat, int error)
4499 bp->bio_error = error;
4500 bp->bio_flags |= BIO_ERROR;
4503 devstat_end_transaction_bio(stat, bp);
4507 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4509 biotrack_buf(struct bio *bp, const char *location)
4512 buf_track(bp->bio_track_bp, location);
4519 * Wait for buffer I/O completion, returning error status. The buffer
4520 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR
4521 * error and cleared.
4524 bufwait(struct buf *bp)
4526 if (bp->b_iocmd == BIO_READ)
4527 bwait(bp, PRIBIO, "biord");
4529 bwait(bp, PRIBIO, "biowr");
4530 if (bp->b_flags & B_EINTR) {
4531 bp->b_flags &= ~B_EINTR;
4534 if (bp->b_ioflags & BIO_ERROR) {
4535 return (bp->b_error ? bp->b_error : EIO);
4544 * Finish I/O on a buffer, optionally calling a completion function.
4545 * This is usually called from an interrupt so process blocking is
4548 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
4549 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
4550 * assuming B_INVAL is clear.
4552 * For the VMIO case, we set B_CACHE if the op was a read and no
4553 * read error occurred, or if the op was a write. B_CACHE is never
4554 * set if the buffer is invalid or otherwise uncacheable.
4556 * bufdone does not mess with B_INVAL, allowing the I/O routine or the
4557 * initiator to leave B_INVAL set to brelse the buffer out of existence
4558 * in the biodone routine.
4561 bufdone(struct buf *bp)
4563 struct bufobj *dropobj;
4564 void (*biodone)(struct buf *);
4566 buf_track(bp, __func__);
4567 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
4570 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
4572 runningbufwakeup(bp);
4573 if (bp->b_iocmd == BIO_WRITE)
4574 dropobj = bp->b_bufobj;
4575 /* call optional completion function if requested */
4576 if (bp->b_iodone != NULL) {
4577 biodone = bp->b_iodone;
4578 bp->b_iodone = NULL;
4581 bufobj_wdrop(dropobj);
4584 if (bp->b_flags & B_VMIO) {
4586 * Set B_CACHE if the op was a normal read and no error
4587 * occurred. B_CACHE is set for writes in the b*write()
4590 if (bp->b_iocmd == BIO_READ &&
4591 !(bp->b_flags & (B_INVAL|B_NOCACHE)) &&
4592 !(bp->b_ioflags & BIO_ERROR))
4593 bp->b_flags |= B_CACHE;
4594 vfs_vmio_iodone(bp);
4596 if (!LIST_EMPTY(&bp->b_dep))
4598 if ((bp->b_flags & B_CKHASH) != 0) {
4599 KASSERT(bp->b_iocmd == BIO_READ,
4600 ("bufdone: b_iocmd %d not BIO_READ", bp->b_iocmd));
4601 KASSERT(buf_mapped(bp), ("bufdone: bp %p not mapped", bp));
4602 (*bp->b_ckhashcalc)(bp);
4605 * For asynchronous completions, release the buffer now. The brelse
4606 * will do a wakeup there if necessary - so no need to do a wakeup
4607 * here in the async case. The sync case always needs to do a wakeup.
4609 if (bp->b_flags & B_ASYNC) {
4610 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) ||
4611 (bp->b_ioflags & BIO_ERROR))
4618 bufobj_wdrop(dropobj);
4622 * This routine is called in lieu of iodone in the case of
4623 * incomplete I/O. This keeps the busy status for pages
4627 vfs_unbusy_pages(struct buf *bp)
4633 runningbufwakeup(bp);
4634 if (!(bp->b_flags & B_VMIO))
4637 obj = bp->b_bufobj->bo_object;
4638 for (i = 0; i < bp->b_npages; i++) {
4640 if (m == bogus_page) {
4641 m = vm_page_relookup(obj, OFF_TO_IDX(bp->b_offset) + i);
4643 panic("vfs_unbusy_pages: page missing\n");
4645 if (buf_mapped(bp)) {
4646 BUF_CHECK_MAPPED(bp);
4647 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4648 bp->b_pages, bp->b_npages);
4650 BUF_CHECK_UNMAPPED(bp);
4654 vm_object_pip_wakeupn(obj, bp->b_npages);
4658 * vfs_page_set_valid:
4660 * Set the valid bits in a page based on the supplied offset. The
4661 * range is restricted to the buffer's size.
4663 * This routine is typically called after a read completes.
4666 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4671 * Compute the end offset, eoff, such that [off, eoff) does not span a
4672 * page boundary and eoff is not greater than the end of the buffer.
4673 * The end of the buffer, in this case, is our file EOF, not the
4674 * allocation size of the buffer.
4676 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK;
4677 if (eoff > bp->b_offset + bp->b_bcount)
4678 eoff = bp->b_offset + bp->b_bcount;
4681 * Set valid range. This is typically the entire buffer and thus the
4685 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
4689 * vfs_page_set_validclean:
4691 * Set the valid bits and clear the dirty bits in a page based on the
4692 * supplied offset. The range is restricted to the buffer's size.
4695 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m)
4697 vm_ooffset_t soff, eoff;
4700 * Start and end offsets in buffer. eoff - soff may not cross a
4701 * page boundary or cross the end of the buffer. The end of the
4702 * buffer, in this case, is our file EOF, not the allocation size
4706 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4707 if (eoff > bp->b_offset + bp->b_bcount)
4708 eoff = bp->b_offset + bp->b_bcount;
4711 * Set valid range. This is typically the entire buffer and thus the
4715 vm_page_set_validclean(
4717 (vm_offset_t) (soff & PAGE_MASK),
4718 (vm_offset_t) (eoff - soff)
4724 * Acquire a shared busy on all pages in the buf.
4727 vfs_busy_pages_acquire(struct buf *bp)
4731 for (i = 0; i < bp->b_npages; i++)
4732 vm_page_busy_acquire(bp->b_pages[i], VM_ALLOC_SBUSY);
4736 vfs_busy_pages_release(struct buf *bp)
4740 for (i = 0; i < bp->b_npages; i++)
4741 vm_page_sunbusy(bp->b_pages[i]);
4745 * This routine is called before a device strategy routine.
4746 * It is used to tell the VM system that paging I/O is in
4747 * progress, and treat the pages associated with the buffer
4748 * almost as being exclusive busy. Also the object paging_in_progress
4749 * flag is handled to make sure that the object doesn't become
4752 * Since I/O has not been initiated yet, certain buffer flags
4753 * such as BIO_ERROR or B_INVAL may be in an inconsistent state
4754 * and should be ignored.
4757 vfs_busy_pages(struct buf *bp, int clear_modify)
4765 if (!(bp->b_flags & B_VMIO))
4768 obj = bp->b_bufobj->bo_object;
4769 foff = bp->b_offset;
4770 KASSERT(bp->b_offset != NOOFFSET,
4771 ("vfs_busy_pages: no buffer offset"));
4772 if ((bp->b_flags & B_CLUSTER) == 0) {
4773 vm_object_pip_add(obj, bp->b_npages);
4774 vfs_busy_pages_acquire(bp);
4776 if (bp->b_bufsize != 0)
4777 vfs_setdirty_range(bp);
4779 for (i = 0; i < bp->b_npages; i++) {
4781 vm_page_assert_sbusied(m);
4784 * When readying a buffer for a read ( i.e
4785 * clear_modify == 0 ), it is important to do
4786 * bogus_page replacement for valid pages in
4787 * partially instantiated buffers. Partially
4788 * instantiated buffers can, in turn, occur when
4789 * reconstituting a buffer from its VM backing store
4790 * base. We only have to do this if B_CACHE is
4791 * clear ( which causes the I/O to occur in the
4792 * first place ). The replacement prevents the read
4793 * I/O from overwriting potentially dirty VM-backed
4794 * pages. XXX bogus page replacement is, uh, bogus.
4795 * It may not work properly with small-block devices.
4796 * We need to find a better way.
4799 pmap_remove_write(m);
4800 vfs_page_set_validclean(bp, foff, m);
4801 } else if (vm_page_all_valid(m) &&
4802 (bp->b_flags & B_CACHE) == 0) {
4803 bp->b_pages[i] = bogus_page;
4806 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4808 if (bogus && buf_mapped(bp)) {
4809 BUF_CHECK_MAPPED(bp);
4810 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4811 bp->b_pages, bp->b_npages);
4816 * vfs_bio_set_valid:
4818 * Set the range within the buffer to valid. The range is
4819 * relative to the beginning of the buffer, b_offset. Note that
4820 * b_offset itself may be offset from the beginning of the first
4824 vfs_bio_set_valid(struct buf *bp, int base, int size)
4829 if (!(bp->b_flags & B_VMIO))
4833 * Fixup base to be relative to beginning of first page.
4834 * Set initial n to be the maximum number of bytes in the
4835 * first page that can be validated.
4837 base += (bp->b_offset & PAGE_MASK);
4838 n = PAGE_SIZE - (base & PAGE_MASK);
4841 * Busy may not be strictly necessary here because the pages are
4842 * unlikely to be fully valid and the vnode lock will synchronize
4843 * their access via getpages. It is grabbed for consistency with
4844 * other page validation.
4846 vfs_busy_pages_acquire(bp);
4847 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4851 vm_page_set_valid_range(m, base & PAGE_MASK, n);
4856 vfs_busy_pages_release(bp);
4862 * If the specified buffer is a non-VMIO buffer, clear the entire
4863 * buffer. If the specified buffer is a VMIO buffer, clear and
4864 * validate only the previously invalid portions of the buffer.
4865 * This routine essentially fakes an I/O, so we need to clear
4866 * BIO_ERROR and B_INVAL.
4868 * Note that while we only theoretically need to clear through b_bcount,
4869 * we go ahead and clear through b_bufsize.
4872 vfs_bio_clrbuf(struct buf *bp)
4874 int i, j, sa, ea, slide, zbits;
4875 vm_page_bits_t mask;
4877 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) {
4881 bp->b_flags &= ~B_INVAL;
4882 bp->b_ioflags &= ~BIO_ERROR;
4883 vfs_busy_pages_acquire(bp);
4884 sa = bp->b_offset & PAGE_MASK;
4886 for (i = 0; i < bp->b_npages; i++, sa = 0) {
4887 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize);
4888 ea = slide & PAGE_MASK;
4891 if (bp->b_pages[i] == bogus_page)
4894 zbits = (sizeof(vm_page_bits_t) * NBBY) -
4895 (ea - sa) / DEV_BSIZE;
4896 mask = (VM_PAGE_BITS_ALL >> zbits) << j;
4897 if ((bp->b_pages[i]->valid & mask) == mask)
4899 if ((bp->b_pages[i]->valid & mask) == 0)
4900 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa);
4902 for (; sa < ea; sa += DEV_BSIZE, j++) {
4903 if ((bp->b_pages[i]->valid & (1 << j)) == 0) {
4904 pmap_zero_page_area(bp->b_pages[i],
4909 vm_page_set_valid_range(bp->b_pages[i], j * DEV_BSIZE,
4910 roundup2(ea - sa, DEV_BSIZE));
4912 vfs_busy_pages_release(bp);
4917 vfs_bio_bzero_buf(struct buf *bp, int base, int size)
4922 if (buf_mapped(bp)) {
4923 BUF_CHECK_MAPPED(bp);
4924 bzero(bp->b_data + base, size);
4926 BUF_CHECK_UNMAPPED(bp);
4927 n = PAGE_SIZE - (base & PAGE_MASK);
4928 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
4932 pmap_zero_page_area(m, base & PAGE_MASK, n);
4941 * Update buffer flags based on I/O request parameters, optionally releasing the
4942 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM,
4943 * where they may be placed on a page queue (VMIO) or freed immediately (direct
4944 * I/O). Otherwise the buffer is released to the cache.
4947 b_io_dismiss(struct buf *bp, int ioflag, bool release)
4950 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0,
4951 ("buf %p non-VMIO noreuse", bp));
4953 if ((ioflag & IO_DIRECT) != 0)
4954 bp->b_flags |= B_DIRECT;
4955 if ((ioflag & IO_EXT) != 0)
4956 bp->b_xflags |= BX_ALTDATA;
4957 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) {
4958 bp->b_flags |= B_RELBUF;
4959 if ((ioflag & IO_NOREUSE) != 0)
4960 bp->b_flags |= B_NOREUSE;
4968 vfs_bio_brelse(struct buf *bp, int ioflag)
4971 b_io_dismiss(bp, ioflag, true);
4975 vfs_bio_set_flags(struct buf *bp, int ioflag)
4978 b_io_dismiss(bp, ioflag, false);
4982 * vm_hold_load_pages and vm_hold_free_pages get pages into
4983 * a buffers address space. The pages are anonymous and are
4984 * not associated with a file object.
4987 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4993 BUF_CHECK_MAPPED(bp);
4995 to = round_page(to);
4996 from = round_page(from);
4997 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4998 MPASS((bp->b_flags & B_MAXPHYS) == 0);
4999 KASSERT(to - from <= maxbcachebuf,
5000 ("vm_hold_load_pages too large %p %#jx %#jx %u",
5001 bp, (uintmax_t)from, (uintmax_t)to, maxbcachebuf));
5003 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
5005 * note: must allocate system pages since blocking here
5006 * could interfere with paging I/O, no matter which
5009 p = vm_page_alloc_noobj(VM_ALLOC_SYSTEM | VM_ALLOC_WIRED |
5010 VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) | VM_ALLOC_WAITOK);
5011 pmap_qenter(pg, &p, 1);
5012 bp->b_pages[index] = p;
5014 bp->b_npages = index;
5017 /* Return pages associated with this buf to the vm system */
5019 vm_hold_free_pages(struct buf *bp, int newbsize)
5023 int index, newnpages;
5025 BUF_CHECK_MAPPED(bp);
5027 from = round_page((vm_offset_t)bp->b_data + newbsize);
5028 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
5029 if (bp->b_npages > newnpages)
5030 pmap_qremove(from, bp->b_npages - newnpages);
5031 for (index = newnpages; index < bp->b_npages; index++) {
5032 p = bp->b_pages[index];
5033 bp->b_pages[index] = NULL;
5034 vm_page_unwire_noq(p);
5037 bp->b_npages = newnpages;
5041 * Map an IO request into kernel virtual address space.
5043 * All requests are (re)mapped into kernel VA space.
5044 * Notice that we use b_bufsize for the size of the buffer
5045 * to be mapped. b_bcount might be modified by the driver.
5047 * Note that even if the caller determines that the address space should
5048 * be valid, a race or a smaller-file mapped into a larger space may
5049 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST
5050 * check the return value.
5052 * This function only works with pager buffers.
5055 vmapbuf(struct buf *bp, void *uaddr, size_t len, int mapbuf)
5060 MPASS((bp->b_flags & B_MAXPHYS) != 0);
5061 prot = VM_PROT_READ;
5062 if (bp->b_iocmd == BIO_READ)
5063 prot |= VM_PROT_WRITE; /* Less backwards than it looks */
5064 pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
5065 (vm_offset_t)uaddr, len, prot, bp->b_pages, PBUF_PAGES);
5068 bp->b_bufsize = len;
5069 bp->b_npages = pidx;
5070 bp->b_offset = ((vm_offset_t)uaddr) & PAGE_MASK;
5071 if (mapbuf || !unmapped_buf_allowed) {
5072 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx);
5073 bp->b_data = bp->b_kvabase + bp->b_offset;
5075 bp->b_data = unmapped_buf;
5080 * Free the io map PTEs associated with this IO operation.
5081 * We also invalidate the TLB entries and restore the original b_addr.
5083 * This function only works with pager buffers.
5086 vunmapbuf(struct buf *bp)
5090 npages = bp->b_npages;
5092 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
5093 vm_page_unhold_pages(bp->b_pages, npages);
5095 bp->b_data = unmapped_buf;
5099 bdone(struct buf *bp)
5103 mtxp = mtx_pool_find(mtxpool_sleep, bp);
5105 bp->b_flags |= B_DONE;
5111 bwait(struct buf *bp, u_char pri, const char *wchan)
5115 mtxp = mtx_pool_find(mtxpool_sleep, bp);
5117 while ((bp->b_flags & B_DONE) == 0)
5118 msleep(bp, mtxp, pri, wchan, 0);
5123 bufsync(struct bufobj *bo, int waitfor)
5126 return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread));
5130 bufstrategy(struct bufobj *bo, struct buf *bp)
5136 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy"));
5137 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
5138 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp));
5139 i = VOP_STRATEGY(vp, bp);
5140 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp));
5144 * Initialize a struct bufobj before use. Memory is assumed zero filled.
5147 bufobj_init(struct bufobj *bo, void *private)
5149 static volatile int bufobj_cleanq;
5152 atomic_fetchadd_int(&bufobj_cleanq, 1) % buf_domains;
5153 rw_init(BO_LOCKPTR(bo), "bufobj interlock");
5154 bo->bo_private = private;
5155 TAILQ_INIT(&bo->bo_clean.bv_hd);
5156 pctrie_init(&bo->bo_clean.bv_root);
5157 TAILQ_INIT(&bo->bo_dirty.bv_hd);
5158 pctrie_init(&bo->bo_dirty.bv_root);
5162 bufobj_wrefl(struct bufobj *bo)
5165 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5166 ASSERT_BO_WLOCKED(bo);
5171 bufobj_wref(struct bufobj *bo)
5174 KASSERT(bo != NULL, ("NULL bo in bufobj_wref"));
5181 bufobj_wdrop(struct bufobj *bo)
5184 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop"));
5186 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count"));
5187 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) {
5188 bo->bo_flag &= ~BO_WWAIT;
5189 wakeup(&bo->bo_numoutput);
5195 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo)
5199 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait"));
5200 ASSERT_BO_WLOCKED(bo);
5202 while (bo->bo_numoutput) {
5203 bo->bo_flag |= BO_WWAIT;
5204 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo),
5205 slpflag | (PRIBIO + 1), "bo_wwait", timeo);
5213 * Set bio_data or bio_ma for struct bio from the struct buf.
5216 bdata2bio(struct buf *bp, struct bio *bip)
5219 if (!buf_mapped(bp)) {
5220 KASSERT(unmapped_buf_allowed, ("unmapped"));
5221 bip->bio_ma = bp->b_pages;
5222 bip->bio_ma_n = bp->b_npages;
5223 bip->bio_data = unmapped_buf;
5224 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
5225 bip->bio_flags |= BIO_UNMAPPED;
5226 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) /
5227 PAGE_SIZE == bp->b_npages,
5228 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset,
5229 (long long)bip->bio_length, bip->bio_ma_n));
5231 bip->bio_data = bp->b_data;
5237 memdesc_bio(struct bio *bio)
5239 if ((bio->bio_flags & BIO_VLIST) != 0)
5240 return (memdesc_vlist((struct bus_dma_segment *)bio->bio_data,
5243 if ((bio->bio_flags & BIO_UNMAPPED) != 0)
5244 return (memdesc_vmpages(bio->bio_ma, bio->bio_bcount,
5245 bio->bio_ma_offset));
5247 return (memdesc_vaddr(bio->bio_data, bio->bio_bcount));
5250 static int buf_pager_relbuf;
5251 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN,
5252 &buf_pager_relbuf, 0,
5253 "Make buffer pager release buffers after reading");
5256 * The buffer pager. It uses buffer reads to validate pages.
5258 * In contrast to the generic local pager from vm/vnode_pager.c, this
5259 * pager correctly and easily handles volumes where the underlying
5260 * device block size is greater than the machine page size. The
5261 * buffer cache transparently extends the requested page run to be
5262 * aligned at the block boundary, and does the necessary bogus page
5263 * replacements in the addends to avoid obliterating already valid
5266 * The only non-trivial issue is that the exclusive busy state for
5267 * pages, which is assumed by the vm_pager_getpages() interface, is
5268 * incompatible with the VMIO buffer cache's desire to share-busy the
5269 * pages. This function performs a trivial downgrade of the pages'
5270 * state before reading buffers, and a less trivial upgrade from the
5271 * shared-busy to excl-busy state after the read.
5274 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count,
5275 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno,
5276 vbg_get_blksize_t get_blksize)
5283 vm_ooffset_t la, lb, poff, poffe;
5285 int br_flags, error, i, pgsin, pgsin_a, pgsin_b;
5288 object = vp->v_object;
5291 la = IDX_TO_OFF(ma[count - 1]->pindex);
5292 if (la >= object->un_pager.vnp.vnp_size)
5293 return (VM_PAGER_BAD);
5296 * Change the meaning of la from where the last requested page starts
5297 * to where it ends, because that's the end of the requested region
5298 * and the start of the potential read-ahead region.
5301 lpart = la > object->un_pager.vnp.vnp_size;
5302 error = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)),
5305 return (VM_PAGER_ERROR);
5308 * Calculate read-ahead, behind and total pages.
5311 lb = IDX_TO_OFF(ma[0]->pindex);
5312 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs));
5314 if (rbehind != NULL)
5316 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la);
5317 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size)
5318 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size,
5323 VM_CNT_INC(v_vnodein);
5324 VM_CNT_ADD(v_vnodepgsin, pgsin);
5326 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS)
5327 != 0) ? GB_UNMAPPED : 0;
5329 for (i = 0; i < count; i++) {
5330 if (ma[i] != bogus_page)
5331 vm_page_busy_downgrade(ma[i]);
5335 for (i = 0; i < count; i++) {
5337 if (m == bogus_page)
5341 * Pages are shared busy and the object lock is not
5342 * owned, which together allow for the pages'
5343 * invalidation. The racy test for validity avoids
5344 * useless creation of the buffer for the most typical
5345 * case when invalidation is not used in redo or for
5346 * parallel read. The shared->excl upgrade loop at
5347 * the end of the function catches the race in a
5348 * reliable way (protected by the object lock).
5350 if (vm_page_all_valid(m))
5353 poff = IDX_TO_OFF(m->pindex);
5354 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size);
5355 for (; poff < poffe; poff += bsize) {
5356 lbn = get_lblkno(vp, poff);
5361 error = get_blksize(vp, lbn, &bsize);
5363 error = bread_gb(vp, lbn, bsize,
5364 curthread->td_ucred, br_flags, &bp);
5367 if (bp->b_rcred == curthread->td_ucred) {
5368 crfree(bp->b_rcred);
5369 bp->b_rcred = NOCRED;
5371 if (LIST_EMPTY(&bp->b_dep)) {
5373 * Invalidation clears m->valid, but
5374 * may leave B_CACHE flag if the
5375 * buffer existed at the invalidation
5376 * time. In this case, recycle the
5377 * buffer to do real read on next
5378 * bread() after redo.
5380 * Otherwise B_RELBUF is not strictly
5381 * necessary, enable to reduce buf
5384 if (buf_pager_relbuf ||
5385 !vm_page_all_valid(m))
5386 bp->b_flags |= B_RELBUF;
5388 bp->b_flags &= ~B_NOCACHE;
5394 KASSERT(1 /* racy, enable for debugging */ ||
5395 vm_page_all_valid(m) || i == count - 1,
5396 ("buf %d %p invalid", i, m));
5397 if (i == count - 1 && lpart) {
5398 if (!vm_page_none_valid(m) &&
5399 !vm_page_all_valid(m))
5400 vm_page_zero_invalid(m, TRUE);
5407 for (i = 0; i < count; i++) {
5408 if (ma[i] == bogus_page)
5410 if (vm_page_busy_tryupgrade(ma[i]) == 0) {
5411 vm_page_sunbusy(ma[i]);
5412 ma[i] = vm_page_grab_unlocked(object, ma[i]->pindex,
5417 * Since the pages were only sbusy while neither the
5418 * buffer nor the object lock was held by us, or
5419 * reallocated while vm_page_grab() slept for busy
5420 * relinguish, they could have been invalidated.
5421 * Recheck the valid bits and re-read as needed.
5423 * Note that the last page is made fully valid in the
5424 * read loop, and partial validity for the page at
5425 * index count - 1 could mean that the page was
5426 * invalidated or removed, so we must restart for
5429 if (!vm_page_all_valid(ma[i]))
5432 if (redo && error == 0)
5434 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
5437 #include "opt_ddb.h"
5439 #include <ddb/ddb.h>
5441 /* DDB command to show buffer data */
5442 DB_SHOW_COMMAND(buffer, db_show_buffer)
5445 struct buf *bp = (struct buf *)addr;
5446 #ifdef FULL_BUF_TRACKING
5451 db_printf("usage: show buffer <addr>\n");
5455 db_printf("buf at %p\n", bp);
5456 db_printf("b_flags = 0x%b, b_xflags=0x%b\n",
5457 (u_int)bp->b_flags, PRINT_BUF_FLAGS,
5458 (u_int)bp->b_xflags, PRINT_BUF_XFLAGS);
5459 db_printf("b_vflags=0x%b b_ioflags0x%b\n",
5460 (u_int)bp->b_vflags, PRINT_BUF_VFLAGS,
5461 (u_int)bp->b_ioflags, PRINT_BIO_FLAGS);
5463 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n"
5464 "b_bufobj = (%p), b_data = %p\n, b_blkno = %jd, b_lblkno = %jd, "
5465 "b_vp = %p, b_dep = %p\n",
5466 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
5467 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno,
5468 (intmax_t)bp->b_lblkno, bp->b_vp, bp->b_dep.lh_first);
5469 db_printf("b_kvabase = %p, b_kvasize = %d\n",
5470 bp->b_kvabase, bp->b_kvasize);
5473 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
5474 for (i = 0; i < bp->b_npages; i++) {
5478 db_printf("(%p, 0x%lx, 0x%lx)", m->object,
5480 (u_long)VM_PAGE_TO_PHYS(m));
5482 db_printf("( ??? )");
5483 if ((i + 1) < bp->b_npages)
5488 BUF_LOCKPRINTINFO(bp);
5489 #if defined(FULL_BUF_TRACKING)
5490 db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt);
5492 i = bp->b_io_tcnt % BUF_TRACKING_SIZE;
5493 for (j = 1; j <= BUF_TRACKING_SIZE; j++) {
5494 if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL)
5496 db_printf(" %2u: %s\n", j,
5497 bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]);
5499 #elif defined(BUF_TRACKING)
5500 db_printf("b_io_tracking: %s\n", bp->b_io_tracking);
5505 DB_SHOW_COMMAND_FLAGS(bufqueues, bufqueues, DB_CMD_MEMSAFE)
5507 struct bufdomain *bd;
5512 db_printf("bqempty: %d\n", bqempty.bq_len);
5514 for (i = 0; i < buf_domains; i++) {
5516 db_printf("Buf domain %d\n", i);
5517 db_printf("\tfreebufs\t%d\n", bd->bd_freebuffers);
5518 db_printf("\tlofreebufs\t%d\n", bd->bd_lofreebuffers);
5519 db_printf("\thifreebufs\t%d\n", bd->bd_hifreebuffers);
5521 db_printf("\tbufspace\t%ld\n", bd->bd_bufspace);
5522 db_printf("\tmaxbufspace\t%ld\n", bd->bd_maxbufspace);
5523 db_printf("\thibufspace\t%ld\n", bd->bd_hibufspace);
5524 db_printf("\tlobufspace\t%ld\n", bd->bd_lobufspace);
5525 db_printf("\tbufspacethresh\t%ld\n", bd->bd_bufspacethresh);
5527 db_printf("\tnumdirtybuffers\t%d\n", bd->bd_numdirtybuffers);
5528 db_printf("\tlodirtybuffers\t%d\n", bd->bd_lodirtybuffers);
5529 db_printf("\thidirtybuffers\t%d\n", bd->bd_hidirtybuffers);
5530 db_printf("\tdirtybufthresh\t%d\n", bd->bd_dirtybufthresh);
5533 TAILQ_FOREACH(bp, &bd->bd_cleanq->bq_queue, b_freelist)
5534 total += bp->b_bufsize;
5535 db_printf("\tcleanq count\t%d (%ld)\n",
5536 bd->bd_cleanq->bq_len, total);
5538 TAILQ_FOREACH(bp, &bd->bd_dirtyq.bq_queue, b_freelist)
5539 total += bp->b_bufsize;
5540 db_printf("\tdirtyq count\t%d (%ld)\n",
5541 bd->bd_dirtyq.bq_len, total);
5542 db_printf("\twakeup\t\t%d\n", bd->bd_wanted);
5543 db_printf("\tlim\t\t%d\n", bd->bd_lim);
5544 db_printf("\tCPU ");
5545 for (j = 0; j <= mp_maxid; j++)
5546 db_printf("%d, ", bd->bd_subq[j].bq_len);
5550 for (j = 0; j < nbuf; j++) {
5552 if (bp->b_domain == i && BUF_ISLOCKED(bp)) {
5554 total += bp->b_bufsize;
5557 db_printf("\tLocked buffers: %d space %ld\n", cnt, total);
5560 for (j = 0; j < nbuf; j++) {
5562 if (bp->b_domain == i) {
5564 total += bp->b_bufsize;
5567 db_printf("\tTotal buffers: %d space %ld\n", cnt, total);
5571 DB_SHOW_COMMAND_FLAGS(lockedbufs, lockedbufs, DB_CMD_MEMSAFE)
5576 for (i = 0; i < nbuf; i++) {
5578 if (BUF_ISLOCKED(bp)) {
5579 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5587 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs)
5593 db_printf("usage: show vnodebufs <addr>\n");
5596 vp = (struct vnode *)addr;
5597 db_printf("Clean buffers:\n");
5598 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) {
5599 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5602 db_printf("Dirty buffers:\n");
5603 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
5604 db_show_buffer((uintptr_t)bp, 1, 0, NULL);
5609 DB_COMMAND_FLAGS(countfreebufs, db_coundfreebufs, DB_CMD_MEMSAFE)
5612 int i, used = 0, nfree = 0;
5615 db_printf("usage: countfreebufs\n");
5619 for (i = 0; i < nbuf; i++) {
5621 if (bp->b_qindex == QUEUE_EMPTY)
5627 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used,
5629 db_printf("numfreebuffers is %d\n", numfreebuffers);