1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause 3 * 4 * Copyright (c) 2004 Poul-Henning Kamp 5 * Copyright (c) 1994,1997 John S. Dyson 6 * Copyright (c) 2013 The FreeBSD Foundation 7 * All rights reserved. 8 * 9 * Portions of this software were developed by Konstantin Belousov 10 * under sponsorship from the FreeBSD Foundation. 11 * 12 * Redistribution and use in source and binary forms, with or without 13 * modification, are permitted provided that the following conditions 14 * are met: 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. 20 * 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 31 * SUCH DAMAGE. 32 */ 33 34 /* 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. 39 * 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. 43 * 44 * see man buf(9) for more info. 45 */ 46 47 #include <sys/param.h> 48 #include <sys/systm.h> 49 #include <sys/asan.h> 50 #include <sys/bio.h> 51 #include <sys/bitset.h> 52 #include <sys/boottrace.h> 53 #include <sys/buf.h> 54 #include <sys/conf.h> 55 #include <sys/counter.h> 56 #include <sys/devicestat.h> 57 #include <sys/eventhandler.h> 58 #include <sys/fail.h> 59 #include <sys/ktr.h> 60 #include <sys/limits.h> 61 #include <sys/lock.h> 62 #include <sys/malloc.h> 63 #include <sys/memdesc.h> 64 #include <sys/mount.h> 65 #include <sys/mutex.h> 66 #include <sys/kernel.h> 67 #include <sys/kthread.h> 68 #include <sys/pctrie.h> 69 #include <sys/proc.h> 70 #include <sys/racct.h> 71 #include <sys/refcount.h> 72 #include <sys/resourcevar.h> 73 #include <sys/rwlock.h> 74 #include <sys/sched.h> 75 #include <sys/smp.h> 76 #include <sys/sysctl.h> 77 #include <sys/syscallsubr.h> 78 #include <sys/vmem.h> 79 #include <sys/vmmeter.h> 80 #include <sys/vnode.h> 81 #include <sys/watchdog.h> 82 #include <geom/geom.h> 83 #include <vm/vm.h> 84 #include <vm/vm_param.h> 85 #include <vm/vm_kern.h> 86 #include <vm/vm_object.h> 87 #include <vm/vm_page.h> 88 #include <vm/vm_pageout.h> 89 #include <vm/vm_pager.h> 90 #include <vm/vm_extern.h> 91 #include <vm/vm_map.h> 92 #include <vm/swap_pager.h> 93 94 static MALLOC_DEFINE(M_BIOBUF, "biobuf", "BIO buffer"); 95 96 struct bio_ops bioops; /* I/O operation notification */ 97 98 struct buf_ops buf_ops_bio = { 99 .bop_name = "buf_ops_bio", 100 .bop_write = bufwrite, 101 .bop_strategy = bufstrategy, 102 .bop_sync = bufsync, 103 .bop_bdflush = bufbdflush, 104 }; 105 106 struct bufqueue { 107 struct mtx_padalign bq_lock; 108 TAILQ_HEAD(, buf) bq_queue; 109 uint8_t bq_index; 110 uint16_t bq_subqueue; 111 int bq_len; 112 } __aligned(CACHE_LINE_SIZE); 113 114 #define BQ_LOCKPTR(bq) (&(bq)->bq_lock) 115 #define BQ_LOCK(bq) mtx_lock(BQ_LOCKPTR((bq))) 116 #define BQ_UNLOCK(bq) mtx_unlock(BQ_LOCKPTR((bq))) 117 #define BQ_ASSERT_LOCKED(bq) mtx_assert(BQ_LOCKPTR((bq)), MA_OWNED) 118 119 struct bufdomain { 120 struct bufqueue *bd_subq; 121 struct bufqueue bd_dirtyq; 122 struct bufqueue *bd_cleanq; 123 struct mtx_padalign bd_run_lock; 124 /* Constants */ 125 long bd_maxbufspace; 126 long bd_hibufspace; 127 long bd_lobufspace; 128 long bd_bufspacethresh; 129 int bd_hifreebuffers; 130 int bd_lofreebuffers; 131 int bd_hidirtybuffers; 132 int bd_lodirtybuffers; 133 int bd_dirtybufthresh; 134 int bd_lim; 135 /* atomics */ 136 int bd_wanted; 137 bool bd_shutdown; 138 int __aligned(CACHE_LINE_SIZE) bd_numdirtybuffers; 139 int __aligned(CACHE_LINE_SIZE) bd_running; 140 long __aligned(CACHE_LINE_SIZE) bd_bufspace; 141 int __aligned(CACHE_LINE_SIZE) bd_freebuffers; 142 } __aligned(CACHE_LINE_SIZE); 143 144 #define BD_LOCKPTR(bd) (&(bd)->bd_cleanq->bq_lock) 145 #define BD_LOCK(bd) mtx_lock(BD_LOCKPTR((bd))) 146 #define BD_UNLOCK(bd) mtx_unlock(BD_LOCKPTR((bd))) 147 #define BD_ASSERT_LOCKED(bd) mtx_assert(BD_LOCKPTR((bd)), MA_OWNED) 148 #define BD_RUN_LOCKPTR(bd) (&(bd)->bd_run_lock) 149 #define BD_RUN_LOCK(bd) mtx_lock(BD_RUN_LOCKPTR((bd))) 150 #define BD_RUN_UNLOCK(bd) mtx_unlock(BD_RUN_LOCKPTR((bd))) 151 #define BD_DOMAIN(bd) (bd - bdomain) 152 153 static char *buf; /* buffer header pool */ 154 static struct buf * 155 nbufp(unsigned i) 156 { 157 return ((struct buf *)(buf + (sizeof(struct buf) + 158 sizeof(vm_page_t) * atop(maxbcachebuf)) * i)); 159 } 160 161 caddr_t __read_mostly unmapped_buf; 162 #ifdef INVARIANTS 163 caddr_t poisoned_buf = (void *)-1; 164 #endif 165 166 /* Used below and for softdep flushing threads in ufs/ffs/ffs_softdep.c */ 167 struct proc *bufdaemonproc; 168 169 static void vm_hold_free_pages(struct buf *bp, int newbsize); 170 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from, 171 vm_offset_t to); 172 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m); 173 static void vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, 174 vm_page_t m); 175 static void vfs_clean_pages_dirty_buf(struct buf *bp); 176 static void vfs_setdirty_range(struct buf *bp); 177 static void vfs_vmio_invalidate(struct buf *bp); 178 static void vfs_vmio_truncate(struct buf *bp, int npages); 179 static void vfs_vmio_extend(struct buf *bp, int npages, int size); 180 static int vfs_bio_clcheck(struct vnode *vp, int size, 181 daddr_t lblkno, daddr_t blkno); 182 static void breada(struct vnode *, daddr_t *, int *, int, struct ucred *, int, 183 void (*)(struct buf *)); 184 static int buf_flush(struct vnode *vp, struct bufdomain *, int); 185 static int flushbufqueues(struct vnode *, struct bufdomain *, int, int); 186 static void buf_daemon(void); 187 static __inline void bd_wakeup(void); 188 static int sysctl_runningspace(SYSCTL_HANDLER_ARGS); 189 static void bufkva_reclaim(vmem_t *, int); 190 static void bufkva_free(struct buf *); 191 static int buf_import(void *, void **, int, int, int); 192 static void buf_release(void *, void **, int); 193 static void maxbcachebuf_adjust(void); 194 static inline struct bufdomain *bufdomain(struct buf *); 195 static void bq_remove(struct bufqueue *bq, struct buf *bp); 196 static void bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock); 197 static int buf_recycle(struct bufdomain *, bool kva); 198 static void bq_init(struct bufqueue *bq, int qindex, int cpu, 199 const char *lockname); 200 static void bd_init(struct bufdomain *bd); 201 static int bd_flushall(struct bufdomain *bd); 202 static int sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS); 203 static int sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS); 204 205 static int sysctl_bufspace(SYSCTL_HANDLER_ARGS); 206 int vmiodirenable = TRUE; 207 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0, 208 "Use the VM system for directory writes"); 209 static long runningbufspace; 210 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0, 211 "Amount of presently outstanding async buffer io"); 212 SYSCTL_PROC(_vfs, OID_AUTO, bufspace, CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RD, 213 NULL, 0, sysctl_bufspace, "L", "Physical memory used for buffers"); 214 static counter_u64_t bufkvaspace; 215 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufkvaspace, CTLFLAG_RD, &bufkvaspace, 216 "Kernel virtual memory used for buffers"); 217 static long maxbufspace; 218 SYSCTL_PROC(_vfs, OID_AUTO, maxbufspace, 219 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &maxbufspace, 220 __offsetof(struct bufdomain, bd_maxbufspace), sysctl_bufdomain_long, "L", 221 "Maximum allowed value of bufspace (including metadata)"); 222 static long bufmallocspace; 223 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0, 224 "Amount of malloced memory for buffers"); 225 static long maxbufmallocspace; 226 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 227 0, "Maximum amount of malloced memory for buffers"); 228 static long lobufspace; 229 SYSCTL_PROC(_vfs, OID_AUTO, lobufspace, 230 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &lobufspace, 231 __offsetof(struct bufdomain, bd_lobufspace), sysctl_bufdomain_long, "L", 232 "Minimum amount of buffers we want to have"); 233 long hibufspace; 234 SYSCTL_PROC(_vfs, OID_AUTO, hibufspace, 235 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &hibufspace, 236 __offsetof(struct bufdomain, bd_hibufspace), sysctl_bufdomain_long, "L", 237 "Maximum allowed value of bufspace (excluding metadata)"); 238 long bufspacethresh; 239 SYSCTL_PROC(_vfs, OID_AUTO, bufspacethresh, 240 CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &bufspacethresh, 241 __offsetof(struct bufdomain, bd_bufspacethresh), sysctl_bufdomain_long, "L", 242 "Bufspace consumed before waking the daemon to free some"); 243 static counter_u64_t buffreekvacnt; 244 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 245 "Number of times we have freed the KVA space from some buffer"); 246 static counter_u64_t bufdefragcnt; 247 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 248 "Number of times we have had to repeat buffer allocation to defragment"); 249 static long lorunningspace; 250 SYSCTL_PROC(_vfs, OID_AUTO, lorunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE | 251 CTLFLAG_RW, &lorunningspace, 0, sysctl_runningspace, "L", 252 "Minimum preferred space used for in-progress I/O"); 253 static long hirunningspace; 254 SYSCTL_PROC(_vfs, OID_AUTO, hirunningspace, CTLTYPE_LONG | CTLFLAG_MPSAFE | 255 CTLFLAG_RW, &hirunningspace, 0, sysctl_runningspace, "L", 256 "Maximum amount of space to use for in-progress I/O"); 257 int dirtybufferflushes; 258 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes, 259 0, "Number of bdwrite to bawrite conversions to limit dirty buffers"); 260 int bdwriteskip; 261 SYSCTL_INT(_vfs, OID_AUTO, bdwriteskip, CTLFLAG_RW, &bdwriteskip, 262 0, "Number of buffers supplied to bdwrite with snapshot deadlock risk"); 263 int altbufferflushes; 264 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW | CTLFLAG_STATS, 265 &altbufferflushes, 0, "Number of fsync flushes to limit dirty buffers"); 266 static int recursiveflushes; 267 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW | CTLFLAG_STATS, 268 &recursiveflushes, 0, "Number of flushes skipped due to being recursive"); 269 static int sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS); 270 SYSCTL_PROC(_vfs, OID_AUTO, numdirtybuffers, 271 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RD, NULL, 0, sysctl_numdirtybuffers, "I", 272 "Number of buffers that are dirty (has unwritten changes) at the moment"); 273 static int lodirtybuffers; 274 SYSCTL_PROC(_vfs, OID_AUTO, lodirtybuffers, 275 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lodirtybuffers, 276 __offsetof(struct bufdomain, bd_lodirtybuffers), sysctl_bufdomain_int, "I", 277 "How many buffers we want to have free before bufdaemon can sleep"); 278 static int hidirtybuffers; 279 SYSCTL_PROC(_vfs, OID_AUTO, hidirtybuffers, 280 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hidirtybuffers, 281 __offsetof(struct bufdomain, bd_hidirtybuffers), sysctl_bufdomain_int, "I", 282 "When the number of dirty buffers is considered severe"); 283 int dirtybufthresh; 284 SYSCTL_PROC(_vfs, OID_AUTO, dirtybufthresh, 285 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &dirtybufthresh, 286 __offsetof(struct bufdomain, bd_dirtybufthresh), sysctl_bufdomain_int, "I", 287 "Number of bdwrite to bawrite conversions to clear dirty buffers"); 288 static int numfreebuffers; 289 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0, 290 "Number of free buffers"); 291 static int lofreebuffers; 292 SYSCTL_PROC(_vfs, OID_AUTO, lofreebuffers, 293 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &lofreebuffers, 294 __offsetof(struct bufdomain, bd_lofreebuffers), sysctl_bufdomain_int, "I", 295 "Target number of free buffers"); 296 static int hifreebuffers; 297 SYSCTL_PROC(_vfs, OID_AUTO, hifreebuffers, 298 CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &hifreebuffers, 299 __offsetof(struct bufdomain, bd_hifreebuffers), sysctl_bufdomain_int, "I", 300 "Threshold for clean buffer recycling"); 301 static counter_u64_t getnewbufcalls; 302 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, 303 &getnewbufcalls, "Number of calls to getnewbuf"); 304 static counter_u64_t getnewbufrestarts; 305 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, 306 &getnewbufrestarts, 307 "Number of times getnewbuf has had to restart a buffer acquisition"); 308 static counter_u64_t mappingrestarts; 309 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, mappingrestarts, CTLFLAG_RD, 310 &mappingrestarts, 311 "Number of times getblk has had to restart a buffer mapping for " 312 "unmapped buffer"); 313 static counter_u64_t numbufallocfails; 314 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, numbufallocfails, CTLFLAG_RW, 315 &numbufallocfails, "Number of times buffer allocations failed"); 316 static int flushbufqtarget = 100; 317 SYSCTL_INT(_vfs, OID_AUTO, flushbufqtarget, CTLFLAG_RW, &flushbufqtarget, 0, 318 "Amount of work to do in flushbufqueues when helping bufdaemon"); 319 static counter_u64_t notbufdflushes; 320 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, notbufdflushes, CTLFLAG_RD, ¬bufdflushes, 321 "Number of dirty buffer flushes done by the bufdaemon helpers"); 322 static long barrierwrites; 323 SYSCTL_LONG(_vfs, OID_AUTO, barrierwrites, CTLFLAG_RW | CTLFLAG_STATS, 324 &barrierwrites, 0, "Number of barrier writes"); 325 SYSCTL_INT(_vfs, OID_AUTO, unmapped_buf_allowed, 326 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, 327 &unmapped_buf_allowed, 0, 328 "Permit the use of the unmapped i/o"); 329 int maxbcachebuf = MAXBCACHEBUF; 330 SYSCTL_INT(_vfs, OID_AUTO, maxbcachebuf, CTLFLAG_RDTUN, &maxbcachebuf, 0, 331 "Maximum size of a buffer cache block"); 332 333 /* 334 * This lock synchronizes access to bd_request. 335 */ 336 static struct mtx_padalign __exclusive_cache_line bdlock; 337 338 /* 339 * This lock protects the runningbufreq and synchronizes runningbufwakeup and 340 * waitrunningbufspace(). 341 */ 342 static struct mtx_padalign __exclusive_cache_line rbreqlock; 343 344 /* 345 * Lock that protects bdirtywait. 346 */ 347 static struct mtx_padalign __exclusive_cache_line bdirtylock; 348 349 /* 350 * bufdaemon shutdown request and sleep channel. 351 */ 352 static bool bd_shutdown; 353 354 /* 355 * Wakeup point for bufdaemon, as well as indicator of whether it is already 356 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it 357 * is idling. 358 */ 359 static int bd_request; 360 361 /* 362 * Request for the buf daemon to write more buffers than is indicated by 363 * lodirtybuf. This may be necessary to push out excess dependencies or 364 * defragment the address space where a simple count of the number of dirty 365 * buffers is insufficient to characterize the demand for flushing them. 366 */ 367 static int bd_speedupreq; 368 369 /* 370 * Synchronization (sleep/wakeup) variable for active buffer space requests. 371 * Set when wait starts, cleared prior to wakeup(). 372 * Used in runningbufwakeup() and waitrunningbufspace(). 373 */ 374 static int runningbufreq; 375 376 /* 377 * Synchronization for bwillwrite() waiters. 378 */ 379 static int bdirtywait; 380 381 /* 382 * Definitions for the buffer free lists. 383 */ 384 #define QUEUE_NONE 0 /* on no queue */ 385 #define QUEUE_EMPTY 1 /* empty buffer headers */ 386 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */ 387 #define QUEUE_CLEAN 3 /* non-B_DELWRI buffers */ 388 #define QUEUE_SENTINEL 4 /* not an queue index, but mark for sentinel */ 389 390 /* Maximum number of buffer domains. */ 391 #define BUF_DOMAINS 8 392 393 struct bufdomainset bdlodirty; /* Domains > lodirty */ 394 struct bufdomainset bdhidirty; /* Domains > hidirty */ 395 396 /* Configured number of clean queues. */ 397 static int __read_mostly buf_domains; 398 399 BITSET_DEFINE(bufdomainset, BUF_DOMAINS); 400 struct bufdomain __exclusive_cache_line bdomain[BUF_DOMAINS]; 401 struct bufqueue __exclusive_cache_line bqempty; 402 403 /* 404 * per-cpu empty buffer cache. 405 */ 406 uma_zone_t buf_zone; 407 408 static int 409 sysctl_runningspace(SYSCTL_HANDLER_ARGS) 410 { 411 long value; 412 int error; 413 414 value = *(long *)arg1; 415 error = sysctl_handle_long(oidp, &value, 0, req); 416 if (error != 0 || req->newptr == NULL) 417 return (error); 418 mtx_lock(&rbreqlock); 419 if (arg1 == &hirunningspace) { 420 if (value < lorunningspace) 421 error = EINVAL; 422 else 423 hirunningspace = value; 424 } else { 425 KASSERT(arg1 == &lorunningspace, 426 ("%s: unknown arg1", __func__)); 427 if (value > hirunningspace) 428 error = EINVAL; 429 else 430 lorunningspace = value; 431 } 432 mtx_unlock(&rbreqlock); 433 return (error); 434 } 435 436 static int 437 sysctl_bufdomain_int(SYSCTL_HANDLER_ARGS) 438 { 439 int error; 440 int value; 441 int i; 442 443 value = *(int *)arg1; 444 error = sysctl_handle_int(oidp, &value, 0, req); 445 if (error != 0 || req->newptr == NULL) 446 return (error); 447 *(int *)arg1 = value; 448 for (i = 0; i < buf_domains; i++) 449 *(int *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) = 450 value / buf_domains; 451 452 return (error); 453 } 454 455 static int 456 sysctl_bufdomain_long(SYSCTL_HANDLER_ARGS) 457 { 458 long value; 459 int error; 460 int i; 461 462 value = *(long *)arg1; 463 error = sysctl_handle_long(oidp, &value, 0, req); 464 if (error != 0 || req->newptr == NULL) 465 return (error); 466 *(long *)arg1 = value; 467 for (i = 0; i < buf_domains; i++) 468 *(long *)(uintptr_t)(((uintptr_t)&bdomain[i]) + arg2) = 469 value / buf_domains; 470 471 return (error); 472 } 473 474 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \ 475 defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7) 476 static int 477 sysctl_bufspace(SYSCTL_HANDLER_ARGS) 478 { 479 long lvalue; 480 int ivalue; 481 int i; 482 483 lvalue = 0; 484 for (i = 0; i < buf_domains; i++) 485 lvalue += bdomain[i].bd_bufspace; 486 if (sizeof(int) == sizeof(long) || req->oldlen >= sizeof(long)) 487 return (sysctl_handle_long(oidp, &lvalue, 0, req)); 488 if (lvalue > INT_MAX) 489 /* On overflow, still write out a long to trigger ENOMEM. */ 490 return (sysctl_handle_long(oidp, &lvalue, 0, req)); 491 ivalue = lvalue; 492 return (sysctl_handle_int(oidp, &ivalue, 0, req)); 493 } 494 #else 495 static int 496 sysctl_bufspace(SYSCTL_HANDLER_ARGS) 497 { 498 long lvalue; 499 int i; 500 501 lvalue = 0; 502 for (i = 0; i < buf_domains; i++) 503 lvalue += bdomain[i].bd_bufspace; 504 return (sysctl_handle_long(oidp, &lvalue, 0, req)); 505 } 506 #endif 507 508 static int 509 sysctl_numdirtybuffers(SYSCTL_HANDLER_ARGS) 510 { 511 int value; 512 int i; 513 514 value = 0; 515 for (i = 0; i < buf_domains; i++) 516 value += bdomain[i].bd_numdirtybuffers; 517 return (sysctl_handle_int(oidp, &value, 0, req)); 518 } 519 520 /* 521 * bdirtywakeup: 522 * 523 * Wakeup any bwillwrite() waiters. 524 */ 525 static void 526 bdirtywakeup(void) 527 { 528 mtx_lock(&bdirtylock); 529 if (bdirtywait) { 530 bdirtywait = 0; 531 wakeup(&bdirtywait); 532 } 533 mtx_unlock(&bdirtylock); 534 } 535 536 /* 537 * bd_clear: 538 * 539 * Clear a domain from the appropriate bitsets when dirtybuffers 540 * is decremented. 541 */ 542 static void 543 bd_clear(struct bufdomain *bd) 544 { 545 546 mtx_lock(&bdirtylock); 547 if (bd->bd_numdirtybuffers <= bd->bd_lodirtybuffers) 548 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty); 549 if (bd->bd_numdirtybuffers <= bd->bd_hidirtybuffers) 550 BIT_CLR(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty); 551 mtx_unlock(&bdirtylock); 552 } 553 554 /* 555 * bd_set: 556 * 557 * Set a domain in the appropriate bitsets when dirtybuffers 558 * is incremented. 559 */ 560 static void 561 bd_set(struct bufdomain *bd) 562 { 563 564 mtx_lock(&bdirtylock); 565 if (bd->bd_numdirtybuffers > bd->bd_lodirtybuffers) 566 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdlodirty); 567 if (bd->bd_numdirtybuffers > bd->bd_hidirtybuffers) 568 BIT_SET(BUF_DOMAINS, BD_DOMAIN(bd), &bdhidirty); 569 mtx_unlock(&bdirtylock); 570 } 571 572 /* 573 * bdirtysub: 574 * 575 * Decrement the numdirtybuffers count by one and wakeup any 576 * threads blocked in bwillwrite(). 577 */ 578 static void 579 bdirtysub(struct buf *bp) 580 { 581 struct bufdomain *bd; 582 int num; 583 584 bd = bufdomain(bp); 585 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, -1); 586 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2) 587 bdirtywakeup(); 588 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers) 589 bd_clear(bd); 590 } 591 592 /* 593 * bdirtyadd: 594 * 595 * Increment the numdirtybuffers count by one and wakeup the buf 596 * daemon if needed. 597 */ 598 static void 599 bdirtyadd(struct buf *bp) 600 { 601 struct bufdomain *bd; 602 int num; 603 604 /* 605 * Only do the wakeup once as we cross the boundary. The 606 * buf daemon will keep running until the condition clears. 607 */ 608 bd = bufdomain(bp); 609 num = atomic_fetchadd_int(&bd->bd_numdirtybuffers, 1); 610 if (num == (bd->bd_lodirtybuffers + bd->bd_hidirtybuffers) / 2) 611 bd_wakeup(); 612 if (num == bd->bd_lodirtybuffers || num == bd->bd_hidirtybuffers) 613 bd_set(bd); 614 } 615 616 /* 617 * bufspace_daemon_wakeup: 618 * 619 * Wakeup the daemons responsible for freeing clean bufs. 620 */ 621 static void 622 bufspace_daemon_wakeup(struct bufdomain *bd) 623 { 624 625 /* 626 * avoid the lock if the daemon is running. 627 */ 628 if (atomic_fetchadd_int(&bd->bd_running, 1) == 0) { 629 BD_RUN_LOCK(bd); 630 atomic_store_int(&bd->bd_running, 1); 631 wakeup(&bd->bd_running); 632 BD_RUN_UNLOCK(bd); 633 } 634 } 635 636 /* 637 * bufspace_adjust: 638 * 639 * Adjust the reported bufspace for a KVA managed buffer, possibly 640 * waking any waiters. 641 */ 642 static void 643 bufspace_adjust(struct buf *bp, int bufsize) 644 { 645 struct bufdomain *bd; 646 long space; 647 int diff; 648 649 KASSERT((bp->b_flags & B_MALLOC) == 0, 650 ("bufspace_adjust: malloc buf %p", bp)); 651 bd = bufdomain(bp); 652 diff = bufsize - bp->b_bufsize; 653 if (diff < 0) { 654 atomic_subtract_long(&bd->bd_bufspace, -diff); 655 } else if (diff > 0) { 656 space = atomic_fetchadd_long(&bd->bd_bufspace, diff); 657 /* Wake up the daemon on the transition. */ 658 if (space < bd->bd_bufspacethresh && 659 space + diff >= bd->bd_bufspacethresh) 660 bufspace_daemon_wakeup(bd); 661 } 662 bp->b_bufsize = bufsize; 663 } 664 665 /* 666 * bufspace_reserve: 667 * 668 * Reserve bufspace before calling allocbuf(). metadata has a 669 * different space limit than data. 670 */ 671 static int 672 bufspace_reserve(struct bufdomain *bd, int size, bool metadata) 673 { 674 long limit, new; 675 long space; 676 677 if (metadata) 678 limit = bd->bd_maxbufspace; 679 else 680 limit = bd->bd_hibufspace; 681 space = atomic_fetchadd_long(&bd->bd_bufspace, size); 682 new = space + size; 683 if (new > limit) { 684 atomic_subtract_long(&bd->bd_bufspace, size); 685 return (ENOSPC); 686 } 687 688 /* Wake up the daemon on the transition. */ 689 if (space < bd->bd_bufspacethresh && new >= bd->bd_bufspacethresh) 690 bufspace_daemon_wakeup(bd); 691 692 return (0); 693 } 694 695 /* 696 * bufspace_release: 697 * 698 * Release reserved bufspace after bufspace_adjust() has consumed it. 699 */ 700 static void 701 bufspace_release(struct bufdomain *bd, int size) 702 { 703 704 atomic_subtract_long(&bd->bd_bufspace, size); 705 } 706 707 /* 708 * bufspace_wait: 709 * 710 * Wait for bufspace, acting as the buf daemon if a locked vnode is 711 * supplied. bd_wanted must be set prior to polling for space. The 712 * operation must be re-tried on return. 713 */ 714 static void 715 bufspace_wait(struct bufdomain *bd, struct vnode *vp, int gbflags, 716 int slpflag, int slptimeo) 717 { 718 struct thread *td; 719 int error, fl, norunbuf; 720 721 if ((gbflags & GB_NOWAIT_BD) != 0) 722 return; 723 724 td = curthread; 725 BD_LOCK(bd); 726 while (bd->bd_wanted) { 727 if (vp != NULL && vp->v_type != VCHR && 728 (td->td_pflags & TDP_BUFNEED) == 0) { 729 BD_UNLOCK(bd); 730 /* 731 * getblk() is called with a vnode locked, and 732 * some majority of the dirty buffers may as 733 * well belong to the vnode. Flushing the 734 * buffers there would make a progress that 735 * cannot be achieved by the buf_daemon, that 736 * cannot lock the vnode. 737 */ 738 norunbuf = ~(TDP_BUFNEED | TDP_NORUNNINGBUF) | 739 (td->td_pflags & TDP_NORUNNINGBUF); 740 741 /* 742 * Play bufdaemon. The getnewbuf() function 743 * may be called while the thread owns lock 744 * for another dirty buffer for the same 745 * vnode, which makes it impossible to use 746 * VOP_FSYNC() there, due to the buffer lock 747 * recursion. 748 */ 749 td->td_pflags |= TDP_BUFNEED | TDP_NORUNNINGBUF; 750 fl = buf_flush(vp, bd, flushbufqtarget); 751 td->td_pflags &= norunbuf; 752 BD_LOCK(bd); 753 if (fl != 0) 754 continue; 755 if (bd->bd_wanted == 0) 756 break; 757 } 758 error = msleep(&bd->bd_wanted, BD_LOCKPTR(bd), 759 (PRIBIO + 4) | slpflag, "newbuf", slptimeo); 760 if (error != 0) 761 break; 762 } 763 BD_UNLOCK(bd); 764 } 765 766 static void 767 bufspace_daemon_shutdown(void *arg, int howto __unused) 768 { 769 struct bufdomain *bd = arg; 770 int error; 771 772 if (KERNEL_PANICKED()) 773 return; 774 775 BD_RUN_LOCK(bd); 776 bd->bd_shutdown = true; 777 wakeup(&bd->bd_running); 778 error = msleep(&bd->bd_shutdown, BD_RUN_LOCKPTR(bd), 0, 779 "bufspace_shutdown", 60 * hz); 780 BD_RUN_UNLOCK(bd); 781 if (error != 0) 782 printf("bufspacedaemon wait error: %d\n", error); 783 } 784 785 /* 786 * bufspace_daemon: 787 * 788 * buffer space management daemon. Tries to maintain some marginal 789 * amount of free buffer space so that requesting processes neither 790 * block nor work to reclaim buffers. 791 */ 792 static void 793 bufspace_daemon(void *arg) 794 { 795 struct bufdomain *bd = arg; 796 797 EVENTHANDLER_REGISTER(shutdown_pre_sync, bufspace_daemon_shutdown, bd, 798 SHUTDOWN_PRI_LAST + 100); 799 800 BD_RUN_LOCK(bd); 801 while (!bd->bd_shutdown) { 802 BD_RUN_UNLOCK(bd); 803 804 /* 805 * Free buffers from the clean queue until we meet our 806 * targets. 807 * 808 * Theory of operation: The buffer cache is most efficient 809 * when some free buffer headers and space are always 810 * available to getnewbuf(). This daemon attempts to prevent 811 * the excessive blocking and synchronization associated 812 * with shortfall. It goes through three phases according 813 * demand: 814 * 815 * 1) The daemon wakes up voluntarily once per-second 816 * during idle periods when the counters are below 817 * the wakeup thresholds (bufspacethresh, lofreebuffers). 818 * 819 * 2) The daemon wakes up as we cross the thresholds 820 * ahead of any potential blocking. This may bounce 821 * slightly according to the rate of consumption and 822 * release. 823 * 824 * 3) The daemon and consumers are starved for working 825 * clean buffers. This is the 'bufspace' sleep below 826 * which will inefficiently trade bufs with bqrelse 827 * until we return to condition 2. 828 */ 829 while (bd->bd_bufspace > bd->bd_lobufspace || 830 bd->bd_freebuffers < bd->bd_hifreebuffers) { 831 if (buf_recycle(bd, false) != 0) { 832 if (bd_flushall(bd)) 833 continue; 834 /* 835 * Speedup dirty if we've run out of clean 836 * buffers. This is possible in particular 837 * because softdep may held many bufs locked 838 * pending writes to other bufs which are 839 * marked for delayed write, exhausting 840 * clean space until they are written. 841 */ 842 bd_speedup(); 843 BD_LOCK(bd); 844 if (bd->bd_wanted) { 845 msleep(&bd->bd_wanted, BD_LOCKPTR(bd), 846 PRIBIO|PDROP, "bufspace", hz/10); 847 } else 848 BD_UNLOCK(bd); 849 } 850 maybe_yield(); 851 } 852 853 /* 854 * Re-check our limits and sleep. bd_running must be 855 * cleared prior to checking the limits to avoid missed 856 * wakeups. The waker will adjust one of bufspace or 857 * freebuffers prior to checking bd_running. 858 */ 859 BD_RUN_LOCK(bd); 860 if (bd->bd_shutdown) 861 break; 862 atomic_store_int(&bd->bd_running, 0); 863 if (bd->bd_bufspace < bd->bd_bufspacethresh && 864 bd->bd_freebuffers > bd->bd_lofreebuffers) { 865 msleep(&bd->bd_running, BD_RUN_LOCKPTR(bd), 866 PRIBIO, "-", hz); 867 } else { 868 /* Avoid spurious wakeups while running. */ 869 atomic_store_int(&bd->bd_running, 1); 870 } 871 } 872 wakeup(&bd->bd_shutdown); 873 BD_RUN_UNLOCK(bd); 874 kthread_exit(); 875 } 876 877 /* 878 * bufmallocadjust: 879 * 880 * Adjust the reported bufspace for a malloc managed buffer, possibly 881 * waking any waiters. 882 */ 883 static void 884 bufmallocadjust(struct buf *bp, int bufsize) 885 { 886 int diff; 887 888 KASSERT((bp->b_flags & B_MALLOC) != 0, 889 ("bufmallocadjust: non-malloc buf %p", bp)); 890 diff = bufsize - bp->b_bufsize; 891 if (diff < 0) 892 atomic_subtract_long(&bufmallocspace, -diff); 893 else 894 atomic_add_long(&bufmallocspace, diff); 895 bp->b_bufsize = bufsize; 896 } 897 898 /* 899 * runningwakeup: 900 * 901 * Wake up processes that are waiting on asynchronous writes to fall 902 * below lorunningspace. 903 */ 904 static void 905 runningwakeup(void) 906 { 907 908 mtx_lock(&rbreqlock); 909 if (runningbufreq) { 910 runningbufreq = 0; 911 wakeup(&runningbufreq); 912 } 913 mtx_unlock(&rbreqlock); 914 } 915 916 /* 917 * runningbufwakeup: 918 * 919 * Decrement the outstanding write count according. 920 */ 921 void 922 runningbufwakeup(struct buf *bp) 923 { 924 long space, bspace; 925 926 bspace = bp->b_runningbufspace; 927 if (bspace == 0) 928 return; 929 space = atomic_fetchadd_long(&runningbufspace, -bspace); 930 KASSERT(space >= bspace, ("runningbufspace underflow %ld %ld", 931 space, bspace)); 932 bp->b_runningbufspace = 0; 933 /* 934 * Only acquire the lock and wakeup on the transition from exceeding 935 * the threshold to falling below it. 936 */ 937 if (space < lorunningspace) 938 return; 939 if (space - bspace > lorunningspace) 940 return; 941 runningwakeup(); 942 } 943 944 long 945 runningbufclaim(struct buf *bp, int space) 946 { 947 long old; 948 949 old = atomic_fetchadd_long(&runningbufspace, space); 950 bp->b_runningbufspace = space; 951 return (old); 952 } 953 954 /* 955 * waitrunningbufspace() 956 * 957 * runningbufspace is a measure of the amount of I/O currently 958 * running. This routine is used in async-write situations to 959 * prevent creating huge backups of pending writes to a device. 960 * Only asynchronous writes are governed by this function. 961 * 962 * This does NOT turn an async write into a sync write. It waits 963 * for earlier writes to complete and generally returns before the 964 * caller's write has reached the device. 965 */ 966 void 967 waitrunningbufspace(void) 968 { 969 970 mtx_lock(&rbreqlock); 971 while (runningbufspace > hirunningspace) { 972 runningbufreq = 1; 973 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0); 974 } 975 mtx_unlock(&rbreqlock); 976 } 977 978 /* 979 * vfs_buf_test_cache: 980 * 981 * Called when a buffer is extended. This function clears the B_CACHE 982 * bit if the newly extended portion of the buffer does not contain 983 * valid data. 984 */ 985 static __inline void 986 vfs_buf_test_cache(struct buf *bp, vm_ooffset_t foff, vm_offset_t off, 987 vm_offset_t size, vm_page_t m) 988 { 989 990 /* 991 * This function and its results are protected by higher level 992 * synchronization requiring vnode and buf locks to page in and 993 * validate pages. 994 */ 995 if (bp->b_flags & B_CACHE) { 996 int base = (foff + off) & PAGE_MASK; 997 if (vm_page_is_valid(m, base, size) == 0) 998 bp->b_flags &= ~B_CACHE; 999 } 1000 } 1001 1002 /* Wake up the buffer daemon if necessary */ 1003 static void 1004 bd_wakeup(void) 1005 { 1006 1007 mtx_lock(&bdlock); 1008 if (bd_request == 0) { 1009 bd_request = 1; 1010 wakeup(&bd_request); 1011 } 1012 mtx_unlock(&bdlock); 1013 } 1014 1015 /* 1016 * Adjust the maxbcachbuf tunable. 1017 */ 1018 static void 1019 maxbcachebuf_adjust(void) 1020 { 1021 int i; 1022 1023 /* 1024 * maxbcachebuf must be a power of 2 >= MAXBSIZE. 1025 */ 1026 i = 2; 1027 while (i * 2 <= maxbcachebuf) 1028 i *= 2; 1029 maxbcachebuf = i; 1030 if (maxbcachebuf < MAXBSIZE) 1031 maxbcachebuf = MAXBSIZE; 1032 if (maxbcachebuf > maxphys) 1033 maxbcachebuf = maxphys; 1034 if (bootverbose != 0 && maxbcachebuf != MAXBCACHEBUF) 1035 printf("maxbcachebuf=%d\n", maxbcachebuf); 1036 } 1037 1038 /* 1039 * bd_speedup - speedup the buffer cache flushing code 1040 */ 1041 void 1042 bd_speedup(void) 1043 { 1044 int needwake; 1045 1046 mtx_lock(&bdlock); 1047 needwake = 0; 1048 if (bd_speedupreq == 0 || bd_request == 0) 1049 needwake = 1; 1050 bd_speedupreq = 1; 1051 bd_request = 1; 1052 if (needwake) 1053 wakeup(&bd_request); 1054 mtx_unlock(&bdlock); 1055 } 1056 1057 #ifdef __i386__ 1058 #define TRANSIENT_DENOM 5 1059 #else 1060 #define TRANSIENT_DENOM 10 1061 #endif 1062 1063 /* 1064 * Calculating buffer cache scaling values and reserve space for buffer 1065 * headers. This is called during low level kernel initialization and 1066 * may be called more then once. We CANNOT write to the memory area 1067 * being reserved at this time. 1068 */ 1069 caddr_t 1070 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est) 1071 { 1072 int tuned_nbuf; 1073 long maxbuf, maxbuf_sz, buf_sz, biotmap_sz; 1074 1075 /* 1076 * With KASAN or KMSAN enabled, the kernel map is shadowed. Account for 1077 * this when sizing maps based on the amount of physical memory 1078 * available. 1079 */ 1080 #if defined(KASAN) 1081 physmem_est = (physmem_est * KASAN_SHADOW_SCALE) / 1082 (KASAN_SHADOW_SCALE + 1); 1083 #elif defined(KMSAN) 1084 physmem_est /= 3; 1085 1086 /* 1087 * KMSAN cannot reliably determine whether buffer data is initialized 1088 * unless it is updated through a KVA mapping. 1089 */ 1090 unmapped_buf_allowed = 0; 1091 #endif 1092 1093 /* 1094 * physmem_est is in pages. Convert it to kilobytes (assumes 1095 * PAGE_SIZE is >= 1K) 1096 */ 1097 physmem_est = physmem_est * (PAGE_SIZE / 1024); 1098 1099 maxbcachebuf_adjust(); 1100 /* 1101 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE. 1102 * For the first 64MB of ram nominally allocate sufficient buffers to 1103 * cover 1/4 of our ram. Beyond the first 64MB allocate additional 1104 * buffers to cover 1/10 of our ram over 64MB. When auto-sizing 1105 * the buffer cache we limit the eventual kva reservation to 1106 * maxbcache bytes. 1107 * 1108 * factor represents the 1/4 x ram conversion. 1109 */ 1110 if (nbuf == 0) { 1111 int factor = 4 * BKVASIZE / 1024; 1112 1113 nbuf = 50; 1114 if (physmem_est > 4096) 1115 nbuf += min((physmem_est - 4096) / factor, 1116 65536 / factor); 1117 if (physmem_est > 65536) 1118 nbuf += min((physmem_est - 65536) * 2 / (factor * 5), 1119 32 * 1024 * 1024 / (factor * 5)); 1120 1121 if (maxbcache && nbuf > maxbcache / BKVASIZE) 1122 nbuf = maxbcache / BKVASIZE; 1123 tuned_nbuf = 1; 1124 } else 1125 tuned_nbuf = 0; 1126 1127 /* XXX Avoid unsigned long overflows later on with maxbufspace. */ 1128 maxbuf = (LONG_MAX / 3) / BKVASIZE; 1129 if (nbuf > maxbuf) { 1130 if (!tuned_nbuf) 1131 printf("Warning: nbufs lowered from %d to %ld\n", nbuf, 1132 maxbuf); 1133 nbuf = maxbuf; 1134 } 1135 1136 /* 1137 * Ideal allocation size for the transient bio submap is 10% 1138 * of the maximal space buffer map. This roughly corresponds 1139 * to the amount of the buffer mapped for typical UFS load. 1140 * 1141 * Clip the buffer map to reserve space for the transient 1142 * BIOs, if its extent is bigger than 90% (80% on i386) of the 1143 * maximum buffer map extent on the platform. 1144 * 1145 * The fall-back to the maxbuf in case of maxbcache unset, 1146 * allows to not trim the buffer KVA for the architectures 1147 * with ample KVA space. 1148 */ 1149 if (bio_transient_maxcnt == 0 && unmapped_buf_allowed) { 1150 maxbuf_sz = maxbcache != 0 ? maxbcache : maxbuf * BKVASIZE; 1151 buf_sz = (long)nbuf * BKVASIZE; 1152 if (buf_sz < maxbuf_sz / TRANSIENT_DENOM * 1153 (TRANSIENT_DENOM - 1)) { 1154 /* 1155 * There is more KVA than memory. Do not 1156 * adjust buffer map size, and assign the rest 1157 * of maxbuf to transient map. 1158 */ 1159 biotmap_sz = maxbuf_sz - buf_sz; 1160 } else { 1161 /* 1162 * Buffer map spans all KVA we could afford on 1163 * this platform. Give 10% (20% on i386) of 1164 * the buffer map to the transient bio map. 1165 */ 1166 biotmap_sz = buf_sz / TRANSIENT_DENOM; 1167 buf_sz -= biotmap_sz; 1168 } 1169 if (biotmap_sz / INT_MAX > maxphys) 1170 bio_transient_maxcnt = INT_MAX; 1171 else 1172 bio_transient_maxcnt = biotmap_sz / maxphys; 1173 /* 1174 * Artificially limit to 1024 simultaneous in-flight I/Os 1175 * using the transient mapping. 1176 */ 1177 if (bio_transient_maxcnt > 1024) 1178 bio_transient_maxcnt = 1024; 1179 if (tuned_nbuf) 1180 nbuf = buf_sz / BKVASIZE; 1181 } 1182 1183 if (nswbuf == 0) { 1184 /* 1185 * Pager buffers are allocated for short periods, so scale the 1186 * number of reserved buffers based on the number of CPUs rather 1187 * than amount of memory. 1188 */ 1189 nswbuf = min(nbuf / 4, 32 * mp_ncpus); 1190 if (nswbuf < NSWBUF_MIN) 1191 nswbuf = NSWBUF_MIN; 1192 } 1193 1194 /* 1195 * Reserve space for the buffer cache buffers 1196 */ 1197 buf = (char *)v; 1198 v = (caddr_t)buf + (sizeof(struct buf) + sizeof(vm_page_t) * 1199 atop(maxbcachebuf)) * nbuf; 1200 1201 return (v); 1202 } 1203 1204 /* 1205 * Single global constant for BUF_WMESG, to avoid getting multiple 1206 * references. 1207 */ 1208 static const char buf_wmesg[] = "bufwait"; 1209 1210 /* Initialize the buffer subsystem. Called before use of any buffers. */ 1211 void 1212 bufinit(void) 1213 { 1214 struct buf *bp; 1215 int i; 1216 1217 TSENTER(); 1218 KASSERT(maxbcachebuf >= MAXBSIZE, 1219 ("maxbcachebuf (%d) must be >= MAXBSIZE (%d)\n", maxbcachebuf, 1220 MAXBSIZE)); 1221 bq_init(&bqempty, QUEUE_EMPTY, -1, "bufq empty lock"); 1222 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF); 1223 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF); 1224 mtx_init(&bdirtylock, "dirty buf lock", NULL, MTX_DEF); 1225 1226 unmapped_buf = (caddr_t)kva_alloc(maxphys); 1227 #ifdef INVARIANTS 1228 poisoned_buf = unmapped_buf; 1229 #endif 1230 1231 /* finally, initialize each buffer header and stick on empty q */ 1232 for (i = 0; i < nbuf; i++) { 1233 bp = nbufp(i); 1234 bzero(bp, sizeof(*bp) + sizeof(vm_page_t) * atop(maxbcachebuf)); 1235 bp->b_flags = B_INVAL; 1236 bp->b_rcred = NOCRED; 1237 bp->b_wcred = NOCRED; 1238 bp->b_qindex = QUEUE_NONE; 1239 bp->b_domain = -1; 1240 bp->b_subqueue = mp_maxid + 1; 1241 bp->b_xflags = 0; 1242 bp->b_data = bp->b_kvabase = unmapped_buf; 1243 LIST_INIT(&bp->b_dep); 1244 BUF_LOCKINIT(bp, buf_wmesg); 1245 bq_insert(&bqempty, bp, false); 1246 } 1247 1248 /* 1249 * maxbufspace is the absolute maximum amount of buffer space we are 1250 * allowed to reserve in KVM and in real terms. The absolute maximum 1251 * is nominally used by metadata. hibufspace is the nominal maximum 1252 * used by most other requests. The differential is required to 1253 * ensure that metadata deadlocks don't occur. 1254 * 1255 * maxbufspace is based on BKVASIZE. Allocating buffers larger then 1256 * this may result in KVM fragmentation which is not handled optimally 1257 * by the system. XXX This is less true with vmem. We could use 1258 * PAGE_SIZE. 1259 */ 1260 maxbufspace = (long)nbuf * BKVASIZE; 1261 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - maxbcachebuf * 10); 1262 lobufspace = (hibufspace / 20) * 19; /* 95% */ 1263 bufspacethresh = lobufspace + (hibufspace - lobufspace) / 2; 1264 1265 /* 1266 * Note: The upper limit for hirunningspace was chosen arbitrarily and 1267 * may need further tuning. It corresponds to 128 outstanding write IO 1268 * requests, which fits with many RAID controllers' tagged queuing 1269 * limits. 1270 * 1271 * The lower 1 MiB limit is the historical upper limit for 1272 * hirunningspace. 1273 */ 1274 hirunningspace = lmax(lmin(roundup(hibufspace / 64, maxbcachebuf), 1275 128 * maxphys), 1024 * 1024); 1276 lorunningspace = roundup((hirunningspace * 2) / 3, maxbcachebuf); 1277 1278 /* 1279 * Limit the amount of malloc memory since it is wired permanently into 1280 * the kernel space. Even though this is accounted for in the buffer 1281 * allocation, we don't want the malloced region to grow uncontrolled. 1282 * The malloc scheme improves memory utilization significantly on 1283 * average (small) directories. 1284 */ 1285 maxbufmallocspace = hibufspace / 20; 1286 1287 /* 1288 * Reduce the chance of a deadlock occurring by limiting the number 1289 * of delayed-write dirty buffers we allow to stack up. 1290 */ 1291 hidirtybuffers = nbuf / 4 + 20; 1292 dirtybufthresh = hidirtybuffers * 9 / 10; 1293 /* 1294 * To support extreme low-memory systems, make sure hidirtybuffers 1295 * cannot eat up all available buffer space. This occurs when our 1296 * minimum cannot be met. We try to size hidirtybuffers to 3/4 our 1297 * buffer space assuming BKVASIZE'd buffers. 1298 */ 1299 while ((long)hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) { 1300 hidirtybuffers >>= 1; 1301 } 1302 lodirtybuffers = hidirtybuffers / 2; 1303 1304 /* 1305 * lofreebuffers should be sufficient to avoid stalling waiting on 1306 * buf headers under heavy utilization. The bufs in per-cpu caches 1307 * are counted as free but will be unavailable to threads executing 1308 * on other cpus. 1309 * 1310 * hifreebuffers is the free target for the bufspace daemon. This 1311 * should be set appropriately to limit work per-iteration. 1312 */ 1313 lofreebuffers = MIN((nbuf / 25) + (20 * mp_ncpus), 128 * mp_ncpus); 1314 hifreebuffers = (3 * lofreebuffers) / 2; 1315 numfreebuffers = nbuf; 1316 1317 /* Setup the kva and free list allocators. */ 1318 vmem_set_reclaim(buffer_arena, bufkva_reclaim); 1319 buf_zone = uma_zcache_create("buf free cache", 1320 sizeof(struct buf) + sizeof(vm_page_t) * atop(maxbcachebuf), 1321 NULL, NULL, NULL, NULL, buf_import, buf_release, NULL, 0); 1322 1323 /* 1324 * Size the clean queue according to the amount of buffer space. 1325 * One queue per-256mb up to the max. More queues gives better 1326 * concurrency but less accurate LRU. 1327 */ 1328 buf_domains = MIN(howmany(maxbufspace, 256*1024*1024), BUF_DOMAINS); 1329 for (i = 0 ; i < buf_domains; i++) { 1330 struct bufdomain *bd; 1331 1332 bd = &bdomain[i]; 1333 bd_init(bd); 1334 bd->bd_freebuffers = nbuf / buf_domains; 1335 bd->bd_hifreebuffers = hifreebuffers / buf_domains; 1336 bd->bd_lofreebuffers = lofreebuffers / buf_domains; 1337 bd->bd_bufspace = 0; 1338 bd->bd_maxbufspace = maxbufspace / buf_domains; 1339 bd->bd_hibufspace = hibufspace / buf_domains; 1340 bd->bd_lobufspace = lobufspace / buf_domains; 1341 bd->bd_bufspacethresh = bufspacethresh / buf_domains; 1342 bd->bd_numdirtybuffers = 0; 1343 bd->bd_hidirtybuffers = hidirtybuffers / buf_domains; 1344 bd->bd_lodirtybuffers = lodirtybuffers / buf_domains; 1345 bd->bd_dirtybufthresh = dirtybufthresh / buf_domains; 1346 /* Don't allow more than 2% of bufs in the per-cpu caches. */ 1347 bd->bd_lim = nbuf / buf_domains / 50 / mp_ncpus; 1348 } 1349 getnewbufcalls = counter_u64_alloc(M_WAITOK); 1350 getnewbufrestarts = counter_u64_alloc(M_WAITOK); 1351 mappingrestarts = counter_u64_alloc(M_WAITOK); 1352 numbufallocfails = counter_u64_alloc(M_WAITOK); 1353 notbufdflushes = counter_u64_alloc(M_WAITOK); 1354 buffreekvacnt = counter_u64_alloc(M_WAITOK); 1355 bufdefragcnt = counter_u64_alloc(M_WAITOK); 1356 bufkvaspace = counter_u64_alloc(M_WAITOK); 1357 TSEXIT(); 1358 } 1359 1360 #ifdef INVARIANTS 1361 static inline void 1362 vfs_buf_check_mapped(struct buf *bp) 1363 { 1364 1365 KASSERT(bp->b_kvabase != unmapped_buf, 1366 ("mapped buf: b_kvabase was not updated %p", bp)); 1367 KASSERT(bp->b_data != unmapped_buf, 1368 ("mapped buf: b_data was not updated %p", bp)); 1369 KASSERT(bp->b_data < unmapped_buf || bp->b_data >= unmapped_buf + 1370 maxphys, ("b_data + b_offset unmapped %p", bp)); 1371 } 1372 1373 static inline void 1374 vfs_buf_check_unmapped(struct buf *bp) 1375 { 1376 1377 KASSERT(bp->b_data == unmapped_buf, 1378 ("unmapped buf: corrupted b_data %p", bp)); 1379 } 1380 1381 #define BUF_CHECK_MAPPED(bp) vfs_buf_check_mapped(bp) 1382 #define BUF_CHECK_UNMAPPED(bp) vfs_buf_check_unmapped(bp) 1383 #else 1384 #define BUF_CHECK_MAPPED(bp) do {} while (0) 1385 #define BUF_CHECK_UNMAPPED(bp) do {} while (0) 1386 #endif 1387 1388 static int 1389 isbufbusy(struct buf *bp) 1390 { 1391 if (((bp->b_flags & B_INVAL) == 0 && BUF_ISLOCKED(bp)) || 1392 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI)) 1393 return (1); 1394 return (0); 1395 } 1396 1397 /* 1398 * Shutdown the system cleanly to prepare for reboot, halt, or power off. 1399 */ 1400 void 1401 bufshutdown(int show_busybufs) 1402 { 1403 static int first_buf_printf = 1; 1404 struct buf *bp; 1405 int i, iter, nbusy, pbusy; 1406 #ifndef PREEMPTION 1407 int subiter; 1408 #endif 1409 1410 /* 1411 * Sync filesystems for shutdown 1412 */ 1413 wdog_kern_pat(WD_LASTVAL); 1414 kern_sync(curthread); 1415 1416 /* 1417 * With soft updates, some buffers that are 1418 * written will be remarked as dirty until other 1419 * buffers are written. 1420 */ 1421 for (iter = pbusy = 0; iter < 20; iter++) { 1422 nbusy = 0; 1423 for (i = nbuf - 1; i >= 0; i--) { 1424 bp = nbufp(i); 1425 if (isbufbusy(bp)) 1426 nbusy++; 1427 } 1428 if (nbusy == 0) { 1429 if (first_buf_printf) 1430 printf("All buffers synced."); 1431 break; 1432 } 1433 if (first_buf_printf) { 1434 printf("Syncing disks, buffers remaining... "); 1435 first_buf_printf = 0; 1436 } 1437 printf("%d ", nbusy); 1438 if (nbusy < pbusy) 1439 iter = 0; 1440 pbusy = nbusy; 1441 1442 wdog_kern_pat(WD_LASTVAL); 1443 kern_sync(curthread); 1444 1445 #ifdef PREEMPTION 1446 /* 1447 * Spin for a while to allow interrupt threads to run. 1448 */ 1449 DELAY(50000 * iter); 1450 #else 1451 /* 1452 * Context switch several times to allow interrupt 1453 * threads to run. 1454 */ 1455 for (subiter = 0; subiter < 50 * iter; subiter++) { 1456 sched_relinquish(curthread); 1457 DELAY(1000); 1458 } 1459 #endif 1460 } 1461 printf("\n"); 1462 /* 1463 * Count only busy local buffers to prevent forcing 1464 * a fsck if we're just a client of a wedged NFS server 1465 */ 1466 nbusy = 0; 1467 for (i = nbuf - 1; i >= 0; i--) { 1468 bp = nbufp(i); 1469 if (isbufbusy(bp)) { 1470 #if 0 1471 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */ 1472 if (bp->b_dev == NULL) { 1473 TAILQ_REMOVE(&mountlist, 1474 bp->b_vp->v_mount, mnt_list); 1475 continue; 1476 } 1477 #endif 1478 nbusy++; 1479 if (show_busybufs > 0) { 1480 printf( 1481 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:", 1482 nbusy, bp, bp->b_vp, bp->b_flags, 1483 (intmax_t)bp->b_blkno, 1484 (intmax_t)bp->b_lblkno); 1485 BUF_LOCKPRINTINFO(bp); 1486 if (show_busybufs > 1) 1487 vn_printf(bp->b_vp, 1488 "vnode content: "); 1489 } 1490 } 1491 } 1492 if (nbusy) { 1493 /* 1494 * Failed to sync all blocks. Indicate this and don't 1495 * unmount filesystems (thus forcing an fsck on reboot). 1496 */ 1497 BOOTTRACE("shutdown failed to sync buffers"); 1498 printf("Giving up on %d buffers\n", nbusy); 1499 DELAY(5000000); /* 5 seconds */ 1500 swapoff_all(); 1501 } else { 1502 BOOTTRACE("shutdown sync complete"); 1503 if (!first_buf_printf) 1504 printf("Final sync complete\n"); 1505 1506 /* 1507 * Unmount filesystems and perform swapoff, to quiesce 1508 * the system as much as possible. In particular, no 1509 * I/O should be initiated from top levels since it 1510 * might be abruptly terminated by reset, or otherwise 1511 * erronously handled because other parts of the 1512 * system are disabled. 1513 * 1514 * Swapoff before unmount, because file-backed swap is 1515 * non-operational after unmount of the underlying 1516 * filesystem. 1517 */ 1518 if (!KERNEL_PANICKED()) { 1519 swapoff_all(); 1520 vfs_unmountall(); 1521 } 1522 BOOTTRACE("shutdown unmounted all filesystems"); 1523 } 1524 DELAY(100000); /* wait for console output to finish */ 1525 } 1526 1527 static void 1528 bpmap_qenter(struct buf *bp) 1529 { 1530 1531 BUF_CHECK_MAPPED(bp); 1532 1533 /* 1534 * bp->b_data is relative to bp->b_offset, but 1535 * bp->b_offset may be offset into the first page. 1536 */ 1537 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data); 1538 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages); 1539 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 1540 (vm_offset_t)(bp->b_offset & PAGE_MASK)); 1541 } 1542 1543 static inline struct bufdomain * 1544 bufdomain(struct buf *bp) 1545 { 1546 1547 return (&bdomain[bp->b_domain]); 1548 } 1549 1550 static struct bufqueue * 1551 bufqueue(struct buf *bp) 1552 { 1553 1554 switch (bp->b_qindex) { 1555 case QUEUE_NONE: 1556 /* FALLTHROUGH */ 1557 case QUEUE_SENTINEL: 1558 return (NULL); 1559 case QUEUE_EMPTY: 1560 return (&bqempty); 1561 case QUEUE_DIRTY: 1562 return (&bufdomain(bp)->bd_dirtyq); 1563 case QUEUE_CLEAN: 1564 return (&bufdomain(bp)->bd_subq[bp->b_subqueue]); 1565 default: 1566 break; 1567 } 1568 panic("bufqueue(%p): Unhandled type %d\n", bp, bp->b_qindex); 1569 } 1570 1571 /* 1572 * Return the locked bufqueue that bp is a member of. 1573 */ 1574 static struct bufqueue * 1575 bufqueue_acquire(struct buf *bp) 1576 { 1577 struct bufqueue *bq, *nbq; 1578 1579 /* 1580 * bp can be pushed from a per-cpu queue to the 1581 * cleanq while we're waiting on the lock. Retry 1582 * if the queues don't match. 1583 */ 1584 bq = bufqueue(bp); 1585 BQ_LOCK(bq); 1586 for (;;) { 1587 nbq = bufqueue(bp); 1588 if (bq == nbq) 1589 break; 1590 BQ_UNLOCK(bq); 1591 BQ_LOCK(nbq); 1592 bq = nbq; 1593 } 1594 return (bq); 1595 } 1596 1597 /* 1598 * binsfree: 1599 * 1600 * Insert the buffer into the appropriate free list. Requires a 1601 * locked buffer on entry and buffer is unlocked before return. 1602 */ 1603 static void 1604 binsfree(struct buf *bp, int qindex) 1605 { 1606 struct bufdomain *bd; 1607 struct bufqueue *bq; 1608 1609 KASSERT(qindex == QUEUE_CLEAN || qindex == QUEUE_DIRTY, 1610 ("binsfree: Invalid qindex %d", qindex)); 1611 BUF_ASSERT_XLOCKED(bp); 1612 1613 /* 1614 * Handle delayed bremfree() processing. 1615 */ 1616 if (bp->b_flags & B_REMFREE) { 1617 if (bp->b_qindex == qindex) { 1618 bp->b_flags |= B_REUSE; 1619 bp->b_flags &= ~B_REMFREE; 1620 BUF_UNLOCK(bp); 1621 return; 1622 } 1623 bq = bufqueue_acquire(bp); 1624 bq_remove(bq, bp); 1625 BQ_UNLOCK(bq); 1626 } 1627 bd = bufdomain(bp); 1628 if (qindex == QUEUE_CLEAN) { 1629 if (bd->bd_lim != 0) 1630 bq = &bd->bd_subq[PCPU_GET(cpuid)]; 1631 else 1632 bq = bd->bd_cleanq; 1633 } else 1634 bq = &bd->bd_dirtyq; 1635 bq_insert(bq, bp, true); 1636 } 1637 1638 /* 1639 * buf_free: 1640 * 1641 * Free a buffer to the buf zone once it no longer has valid contents. 1642 */ 1643 static void 1644 buf_free(struct buf *bp) 1645 { 1646 1647 if (bp->b_flags & B_REMFREE) 1648 bremfreef(bp); 1649 if (bp->b_vflags & BV_BKGRDINPROG) 1650 panic("losing buffer 1"); 1651 if (bp->b_rcred != NOCRED) { 1652 crfree(bp->b_rcred); 1653 bp->b_rcred = NOCRED; 1654 } 1655 if (bp->b_wcred != NOCRED) { 1656 crfree(bp->b_wcred); 1657 bp->b_wcred = NOCRED; 1658 } 1659 if (!LIST_EMPTY(&bp->b_dep)) 1660 buf_deallocate(bp); 1661 bufkva_free(bp); 1662 atomic_add_int(&bufdomain(bp)->bd_freebuffers, 1); 1663 MPASS((bp->b_flags & B_MAXPHYS) == 0); 1664 BUF_UNLOCK(bp); 1665 uma_zfree(buf_zone, bp); 1666 } 1667 1668 /* 1669 * buf_import: 1670 * 1671 * Import bufs into the uma cache from the buf list. The system still 1672 * expects a static array of bufs and much of the synchronization 1673 * around bufs assumes type stable storage. As a result, UMA is used 1674 * only as a per-cpu cache of bufs still maintained on a global list. 1675 */ 1676 static int 1677 buf_import(void *arg, void **store, int cnt, int domain, int flags) 1678 { 1679 struct buf *bp; 1680 int i; 1681 1682 BQ_LOCK(&bqempty); 1683 for (i = 0; i < cnt; i++) { 1684 bp = TAILQ_FIRST(&bqempty.bq_queue); 1685 if (bp == NULL) 1686 break; 1687 bq_remove(&bqempty, bp); 1688 store[i] = bp; 1689 } 1690 BQ_UNLOCK(&bqempty); 1691 1692 return (i); 1693 } 1694 1695 /* 1696 * buf_release: 1697 * 1698 * Release bufs from the uma cache back to the buffer queues. 1699 */ 1700 static void 1701 buf_release(void *arg, void **store, int cnt) 1702 { 1703 struct bufqueue *bq; 1704 struct buf *bp; 1705 int i; 1706 1707 bq = &bqempty; 1708 BQ_LOCK(bq); 1709 for (i = 0; i < cnt; i++) { 1710 bp = store[i]; 1711 /* Inline bq_insert() to batch locking. */ 1712 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist); 1713 bp->b_flags &= ~(B_AGE | B_REUSE); 1714 bq->bq_len++; 1715 bp->b_qindex = bq->bq_index; 1716 } 1717 BQ_UNLOCK(bq); 1718 } 1719 1720 /* 1721 * buf_alloc: 1722 * 1723 * Allocate an empty buffer header. 1724 */ 1725 static struct buf * 1726 buf_alloc(struct bufdomain *bd) 1727 { 1728 struct buf *bp; 1729 int freebufs, error; 1730 1731 /* 1732 * We can only run out of bufs in the buf zone if the average buf 1733 * is less than BKVASIZE. In this case the actual wait/block will 1734 * come from buf_reycle() failing to flush one of these small bufs. 1735 */ 1736 bp = NULL; 1737 freebufs = atomic_fetchadd_int(&bd->bd_freebuffers, -1); 1738 if (freebufs > 0) 1739 bp = uma_zalloc(buf_zone, M_NOWAIT); 1740 if (bp == NULL) { 1741 atomic_add_int(&bd->bd_freebuffers, 1); 1742 bufspace_daemon_wakeup(bd); 1743 counter_u64_add(numbufallocfails, 1); 1744 return (NULL); 1745 } 1746 /* 1747 * Wake-up the bufspace daemon on transition below threshold. 1748 */ 1749 if (freebufs == bd->bd_lofreebuffers) 1750 bufspace_daemon_wakeup(bd); 1751 1752 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWITNESS, NULL); 1753 KASSERT(error == 0, ("%s: BUF_LOCK on free buf %p: %d.", __func__, bp, 1754 error)); 1755 (void)error; 1756 1757 KASSERT(bp->b_vp == NULL, 1758 ("bp: %p still has vnode %p.", bp, bp->b_vp)); 1759 KASSERT((bp->b_flags & (B_DELWRI | B_NOREUSE)) == 0, 1760 ("invalid buffer %p flags %#x", bp, bp->b_flags)); 1761 KASSERT((bp->b_xflags & (BX_VNCLEAN|BX_VNDIRTY)) == 0, 1762 ("bp: %p still on a buffer list. xflags %X", bp, bp->b_xflags)); 1763 KASSERT(bp->b_npages == 0, 1764 ("bp: %p still has %d vm pages\n", bp, bp->b_npages)); 1765 KASSERT(bp->b_kvasize == 0, ("bp: %p still has kva\n", bp)); 1766 KASSERT(bp->b_bufsize == 0, ("bp: %p still has bufspace\n", bp)); 1767 MPASS((bp->b_flags & B_MAXPHYS) == 0); 1768 1769 bp->b_domain = BD_DOMAIN(bd); 1770 bp->b_flags = 0; 1771 bp->b_ioflags = 0; 1772 bp->b_xflags = 0; 1773 bp->b_vflags = 0; 1774 bp->b_vp = NULL; 1775 bp->b_blkno = bp->b_lblkno = 0; 1776 bp->b_offset = NOOFFSET; 1777 bp->b_iodone = 0; 1778 bp->b_error = 0; 1779 bp->b_resid = 0; 1780 bp->b_bcount = 0; 1781 bp->b_npages = 0; 1782 bp->b_dirtyoff = bp->b_dirtyend = 0; 1783 bp->b_bufobj = NULL; 1784 bp->b_data = bp->b_kvabase = unmapped_buf; 1785 bp->b_fsprivate1 = NULL; 1786 bp->b_fsprivate2 = NULL; 1787 bp->b_fsprivate3 = NULL; 1788 LIST_INIT(&bp->b_dep); 1789 1790 return (bp); 1791 } 1792 1793 /* 1794 * buf_recycle: 1795 * 1796 * Free a buffer from the given bufqueue. kva controls whether the 1797 * freed buf must own some kva resources. This is used for 1798 * defragmenting. 1799 */ 1800 static int 1801 buf_recycle(struct bufdomain *bd, bool kva) 1802 { 1803 struct bufqueue *bq; 1804 struct buf *bp, *nbp; 1805 1806 if (kva) 1807 counter_u64_add(bufdefragcnt, 1); 1808 nbp = NULL; 1809 bq = bd->bd_cleanq; 1810 BQ_LOCK(bq); 1811 KASSERT(BQ_LOCKPTR(bq) == BD_LOCKPTR(bd), 1812 ("buf_recycle: Locks don't match")); 1813 nbp = TAILQ_FIRST(&bq->bq_queue); 1814 1815 /* 1816 * Run scan, possibly freeing data and/or kva mappings on the fly 1817 * depending. 1818 */ 1819 while ((bp = nbp) != NULL) { 1820 /* 1821 * Calculate next bp (we can only use it if we do not 1822 * release the bqlock). 1823 */ 1824 nbp = TAILQ_NEXT(bp, b_freelist); 1825 1826 /* 1827 * If we are defragging then we need a buffer with 1828 * some kva to reclaim. 1829 */ 1830 if (kva && bp->b_kvasize == 0) 1831 continue; 1832 1833 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) 1834 continue; 1835 1836 /* 1837 * Implement a second chance algorithm for frequently 1838 * accessed buffers. 1839 */ 1840 if ((bp->b_flags & B_REUSE) != 0) { 1841 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist); 1842 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist); 1843 bp->b_flags &= ~B_REUSE; 1844 BUF_UNLOCK(bp); 1845 continue; 1846 } 1847 1848 /* 1849 * Skip buffers with background writes in progress. 1850 */ 1851 if ((bp->b_vflags & BV_BKGRDINPROG) != 0) { 1852 BUF_UNLOCK(bp); 1853 continue; 1854 } 1855 1856 KASSERT(bp->b_qindex == QUEUE_CLEAN, 1857 ("buf_recycle: inconsistent queue %d bp %p", 1858 bp->b_qindex, bp)); 1859 KASSERT(bp->b_domain == BD_DOMAIN(bd), 1860 ("getnewbuf: queue domain %d doesn't match request %d", 1861 bp->b_domain, (int)BD_DOMAIN(bd))); 1862 /* 1863 * NOTE: nbp is now entirely invalid. We can only restart 1864 * the scan from this point on. 1865 */ 1866 bq_remove(bq, bp); 1867 BQ_UNLOCK(bq); 1868 1869 /* 1870 * Requeue the background write buffer with error and 1871 * restart the scan. 1872 */ 1873 if ((bp->b_vflags & BV_BKGRDERR) != 0) { 1874 bqrelse(bp); 1875 BQ_LOCK(bq); 1876 nbp = TAILQ_FIRST(&bq->bq_queue); 1877 continue; 1878 } 1879 bp->b_flags |= B_INVAL; 1880 brelse(bp); 1881 return (0); 1882 } 1883 bd->bd_wanted = 1; 1884 BQ_UNLOCK(bq); 1885 1886 return (ENOBUFS); 1887 } 1888 1889 /* 1890 * bremfree: 1891 * 1892 * Mark the buffer for removal from the appropriate free list. 1893 * 1894 */ 1895 void 1896 bremfree(struct buf *bp) 1897 { 1898 1899 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 1900 KASSERT((bp->b_flags & B_REMFREE) == 0, 1901 ("bremfree: buffer %p already marked for delayed removal.", bp)); 1902 KASSERT(bp->b_qindex != QUEUE_NONE, 1903 ("bremfree: buffer %p not on a queue.", bp)); 1904 BUF_ASSERT_XLOCKED(bp); 1905 1906 bp->b_flags |= B_REMFREE; 1907 } 1908 1909 /* 1910 * bremfreef: 1911 * 1912 * Force an immediate removal from a free list. Used only in nfs when 1913 * it abuses the b_freelist pointer. 1914 */ 1915 void 1916 bremfreef(struct buf *bp) 1917 { 1918 struct bufqueue *bq; 1919 1920 bq = bufqueue_acquire(bp); 1921 bq_remove(bq, bp); 1922 BQ_UNLOCK(bq); 1923 } 1924 1925 static void 1926 bq_init(struct bufqueue *bq, int qindex, int subqueue, const char *lockname) 1927 { 1928 1929 mtx_init(&bq->bq_lock, lockname, NULL, MTX_DEF); 1930 TAILQ_INIT(&bq->bq_queue); 1931 bq->bq_len = 0; 1932 bq->bq_index = qindex; 1933 bq->bq_subqueue = subqueue; 1934 } 1935 1936 static void 1937 bd_init(struct bufdomain *bd) 1938 { 1939 int i; 1940 1941 /* Per-CPU clean buf queues, plus one global queue. */ 1942 bd->bd_subq = mallocarray(mp_maxid + 2, sizeof(struct bufqueue), 1943 M_BIOBUF, M_WAITOK | M_ZERO); 1944 bd->bd_cleanq = &bd->bd_subq[mp_maxid + 1]; 1945 bq_init(bd->bd_cleanq, QUEUE_CLEAN, mp_maxid + 1, "bufq clean lock"); 1946 bq_init(&bd->bd_dirtyq, QUEUE_DIRTY, -1, "bufq dirty lock"); 1947 for (i = 0; i <= mp_maxid; i++) 1948 bq_init(&bd->bd_subq[i], QUEUE_CLEAN, i, 1949 "bufq clean subqueue lock"); 1950 mtx_init(&bd->bd_run_lock, "bufspace daemon run lock", NULL, MTX_DEF); 1951 } 1952 1953 /* 1954 * bq_remove: 1955 * 1956 * Removes a buffer from the free list, must be called with the 1957 * correct qlock held. 1958 */ 1959 static void 1960 bq_remove(struct bufqueue *bq, struct buf *bp) 1961 { 1962 1963 CTR3(KTR_BUF, "bq_remove(%p) vp %p flags %X", 1964 bp, bp->b_vp, bp->b_flags); 1965 KASSERT(bp->b_qindex != QUEUE_NONE, 1966 ("bq_remove: buffer %p not on a queue.", bp)); 1967 KASSERT(bufqueue(bp) == bq, 1968 ("bq_remove: Remove buffer %p from wrong queue.", bp)); 1969 1970 BQ_ASSERT_LOCKED(bq); 1971 if (bp->b_qindex != QUEUE_EMPTY) { 1972 BUF_ASSERT_XLOCKED(bp); 1973 } 1974 KASSERT(bq->bq_len >= 1, 1975 ("queue %d underflow", bp->b_qindex)); 1976 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist); 1977 bq->bq_len--; 1978 bp->b_qindex = QUEUE_NONE; 1979 bp->b_flags &= ~(B_REMFREE | B_REUSE); 1980 } 1981 1982 static void 1983 bd_flush(struct bufdomain *bd, struct bufqueue *bq) 1984 { 1985 struct buf *bp; 1986 1987 BQ_ASSERT_LOCKED(bq); 1988 if (bq != bd->bd_cleanq) { 1989 BD_LOCK(bd); 1990 while ((bp = TAILQ_FIRST(&bq->bq_queue)) != NULL) { 1991 TAILQ_REMOVE(&bq->bq_queue, bp, b_freelist); 1992 TAILQ_INSERT_TAIL(&bd->bd_cleanq->bq_queue, bp, 1993 b_freelist); 1994 bp->b_subqueue = bd->bd_cleanq->bq_subqueue; 1995 } 1996 bd->bd_cleanq->bq_len += bq->bq_len; 1997 bq->bq_len = 0; 1998 } 1999 if (bd->bd_wanted) { 2000 bd->bd_wanted = 0; 2001 wakeup(&bd->bd_wanted); 2002 } 2003 if (bq != bd->bd_cleanq) 2004 BD_UNLOCK(bd); 2005 } 2006 2007 static int 2008 bd_flushall(struct bufdomain *bd) 2009 { 2010 struct bufqueue *bq; 2011 int flushed; 2012 int i; 2013 2014 if (bd->bd_lim == 0) 2015 return (0); 2016 flushed = 0; 2017 for (i = 0; i <= mp_maxid; i++) { 2018 bq = &bd->bd_subq[i]; 2019 if (bq->bq_len == 0) 2020 continue; 2021 BQ_LOCK(bq); 2022 bd_flush(bd, bq); 2023 BQ_UNLOCK(bq); 2024 flushed++; 2025 } 2026 2027 return (flushed); 2028 } 2029 2030 static void 2031 bq_insert(struct bufqueue *bq, struct buf *bp, bool unlock) 2032 { 2033 struct bufdomain *bd; 2034 2035 if (bp->b_qindex != QUEUE_NONE) 2036 panic("bq_insert: free buffer %p onto another queue?", bp); 2037 2038 bd = bufdomain(bp); 2039 if (bp->b_flags & B_AGE) { 2040 /* Place this buf directly on the real queue. */ 2041 if (bq->bq_index == QUEUE_CLEAN) 2042 bq = bd->bd_cleanq; 2043 BQ_LOCK(bq); 2044 TAILQ_INSERT_HEAD(&bq->bq_queue, bp, b_freelist); 2045 } else { 2046 BQ_LOCK(bq); 2047 TAILQ_INSERT_TAIL(&bq->bq_queue, bp, b_freelist); 2048 } 2049 bp->b_flags &= ~(B_AGE | B_REUSE); 2050 bq->bq_len++; 2051 bp->b_qindex = bq->bq_index; 2052 bp->b_subqueue = bq->bq_subqueue; 2053 2054 /* 2055 * Unlock before we notify so that we don't wakeup a waiter that 2056 * fails a trylock on the buf and sleeps again. 2057 */ 2058 if (unlock) 2059 BUF_UNLOCK(bp); 2060 2061 if (bp->b_qindex == QUEUE_CLEAN) { 2062 /* 2063 * Flush the per-cpu queue and notify any waiters. 2064 */ 2065 if (bd->bd_wanted || (bq != bd->bd_cleanq && 2066 bq->bq_len >= bd->bd_lim)) 2067 bd_flush(bd, bq); 2068 } 2069 BQ_UNLOCK(bq); 2070 } 2071 2072 /* 2073 * bufkva_free: 2074 * 2075 * Free the kva allocation for a buffer. 2076 * 2077 */ 2078 static void 2079 bufkva_free(struct buf *bp) 2080 { 2081 2082 #ifdef INVARIANTS 2083 if (bp->b_kvasize == 0) { 2084 KASSERT(bp->b_kvabase == unmapped_buf && 2085 bp->b_data == unmapped_buf, 2086 ("Leaked KVA space on %p", bp)); 2087 } else if (buf_mapped(bp)) 2088 BUF_CHECK_MAPPED(bp); 2089 else 2090 BUF_CHECK_UNMAPPED(bp); 2091 #endif 2092 if (bp->b_kvasize == 0) 2093 return; 2094 2095 vmem_free(buffer_arena, (vm_offset_t)bp->b_kvabase, bp->b_kvasize); 2096 counter_u64_add(bufkvaspace, -bp->b_kvasize); 2097 counter_u64_add(buffreekvacnt, 1); 2098 bp->b_data = bp->b_kvabase = unmapped_buf; 2099 bp->b_kvasize = 0; 2100 } 2101 2102 /* 2103 * bufkva_alloc: 2104 * 2105 * Allocate the buffer KVA and set b_kvasize and b_kvabase. 2106 */ 2107 static int 2108 bufkva_alloc(struct buf *bp, int maxsize, int gbflags) 2109 { 2110 vm_offset_t addr; 2111 int error; 2112 2113 KASSERT((gbflags & GB_UNMAPPED) == 0 || (gbflags & GB_KVAALLOC) != 0, 2114 ("Invalid gbflags 0x%x in %s", gbflags, __func__)); 2115 MPASS((bp->b_flags & B_MAXPHYS) == 0); 2116 KASSERT(maxsize <= maxbcachebuf, 2117 ("bufkva_alloc kva too large %d %u", maxsize, maxbcachebuf)); 2118 2119 bufkva_free(bp); 2120 2121 addr = 0; 2122 error = vmem_alloc(buffer_arena, maxsize, M_BESTFIT | M_NOWAIT, &addr); 2123 if (error != 0) { 2124 /* 2125 * Buffer map is too fragmented. Request the caller 2126 * to defragment the map. 2127 */ 2128 return (error); 2129 } 2130 bp->b_kvabase = (caddr_t)addr; 2131 bp->b_kvasize = maxsize; 2132 counter_u64_add(bufkvaspace, bp->b_kvasize); 2133 if ((gbflags & GB_UNMAPPED) != 0) { 2134 bp->b_data = unmapped_buf; 2135 BUF_CHECK_UNMAPPED(bp); 2136 } else { 2137 bp->b_data = bp->b_kvabase; 2138 BUF_CHECK_MAPPED(bp); 2139 } 2140 return (0); 2141 } 2142 2143 /* 2144 * bufkva_reclaim: 2145 * 2146 * Reclaim buffer kva by freeing buffers holding kva. This is a vmem 2147 * callback that fires to avoid returning failure. 2148 */ 2149 static void 2150 bufkva_reclaim(vmem_t *vmem, int flags) 2151 { 2152 bool done; 2153 int q; 2154 int i; 2155 2156 done = false; 2157 for (i = 0; i < 5; i++) { 2158 for (q = 0; q < buf_domains; q++) 2159 if (buf_recycle(&bdomain[q], true) != 0) 2160 done = true; 2161 if (done) 2162 break; 2163 } 2164 return; 2165 } 2166 2167 /* 2168 * Attempt to initiate asynchronous I/O on read-ahead blocks. We must 2169 * clear BIO_ERROR and B_INVAL prior to initiating I/O . If B_CACHE is set, 2170 * the buffer is valid and we do not have to do anything. 2171 */ 2172 static void 2173 breada(struct vnode * vp, daddr_t * rablkno, int * rabsize, int cnt, 2174 struct ucred * cred, int flags, void (*ckhashfunc)(struct buf *)) 2175 { 2176 struct buf *rabp; 2177 struct thread *td; 2178 int i; 2179 2180 td = curthread; 2181 2182 for (i = 0; i < cnt; i++, rablkno++, rabsize++) { 2183 if (inmem(vp, *rablkno)) 2184 continue; 2185 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0); 2186 if ((rabp->b_flags & B_CACHE) != 0) { 2187 brelse(rabp); 2188 continue; 2189 } 2190 #ifdef RACCT 2191 if (racct_enable) { 2192 PROC_LOCK(curproc); 2193 racct_add_buf(curproc, rabp, 0); 2194 PROC_UNLOCK(curproc); 2195 } 2196 #endif /* RACCT */ 2197 td->td_ru.ru_inblock++; 2198 rabp->b_flags |= B_ASYNC; 2199 rabp->b_flags &= ~B_INVAL; 2200 if ((flags & GB_CKHASH) != 0) { 2201 rabp->b_flags |= B_CKHASH; 2202 rabp->b_ckhashcalc = ckhashfunc; 2203 } 2204 rabp->b_ioflags &= ~BIO_ERROR; 2205 rabp->b_iocmd = BIO_READ; 2206 if (rabp->b_rcred == NOCRED && cred != NOCRED) 2207 rabp->b_rcred = crhold(cred); 2208 vfs_busy_pages(rabp, 0); 2209 BUF_KERNPROC(rabp); 2210 rabp->b_iooffset = dbtob(rabp->b_blkno); 2211 bstrategy(rabp); 2212 } 2213 } 2214 2215 /* 2216 * Entry point for bread() and breadn() via #defines in sys/buf.h. 2217 * 2218 * Get a buffer with the specified data. Look in the cache first. We 2219 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE 2220 * is set, the buffer is valid and we do not have to do anything, see 2221 * getblk(). Also starts asynchronous I/O on read-ahead blocks. 2222 * 2223 * Always return a NULL buffer pointer (in bpp) when returning an error. 2224 * 2225 * The blkno parameter is the logical block being requested. Normally 2226 * the mapping of logical block number to disk block address is done 2227 * by calling VOP_BMAP(). However, if the mapping is already known, the 2228 * disk block address can be passed using the dblkno parameter. If the 2229 * disk block address is not known, then the same value should be passed 2230 * for blkno and dblkno. 2231 */ 2232 int 2233 breadn_flags(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size, 2234 daddr_t *rablkno, int *rabsize, int cnt, struct ucred *cred, int flags, 2235 void (*ckhashfunc)(struct buf *), struct buf **bpp) 2236 { 2237 struct buf *bp; 2238 struct thread *td; 2239 int error, readwait, rv; 2240 2241 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size); 2242 td = curthread; 2243 /* 2244 * Can only return NULL if GB_LOCK_NOWAIT or GB_SPARSE flags 2245 * are specified. 2246 */ 2247 error = getblkx(vp, blkno, dblkno, size, 0, 0, flags, &bp); 2248 if (error != 0) { 2249 *bpp = NULL; 2250 return (error); 2251 } 2252 KASSERT(blkno == bp->b_lblkno, 2253 ("getblkx returned buffer for blkno %jd instead of blkno %jd", 2254 (intmax_t)bp->b_lblkno, (intmax_t)blkno)); 2255 flags &= ~GB_NOSPARSE; 2256 *bpp = bp; 2257 2258 /* 2259 * If not found in cache, do some I/O 2260 */ 2261 readwait = 0; 2262 if ((bp->b_flags & B_CACHE) == 0) { 2263 #ifdef RACCT 2264 if (racct_enable) { 2265 PROC_LOCK(td->td_proc); 2266 racct_add_buf(td->td_proc, bp, 0); 2267 PROC_UNLOCK(td->td_proc); 2268 } 2269 #endif /* RACCT */ 2270 td->td_ru.ru_inblock++; 2271 bp->b_iocmd = BIO_READ; 2272 bp->b_flags &= ~B_INVAL; 2273 if ((flags & GB_CKHASH) != 0) { 2274 bp->b_flags |= B_CKHASH; 2275 bp->b_ckhashcalc = ckhashfunc; 2276 } 2277 if ((flags & GB_CVTENXIO) != 0) 2278 bp->b_xflags |= BX_CVTENXIO; 2279 bp->b_ioflags &= ~BIO_ERROR; 2280 if (bp->b_rcred == NOCRED && cred != NOCRED) 2281 bp->b_rcred = crhold(cred); 2282 vfs_busy_pages(bp, 0); 2283 bp->b_iooffset = dbtob(bp->b_blkno); 2284 bstrategy(bp); 2285 ++readwait; 2286 } 2287 2288 /* 2289 * Attempt to initiate asynchronous I/O on read-ahead blocks. 2290 */ 2291 breada(vp, rablkno, rabsize, cnt, cred, flags, ckhashfunc); 2292 2293 rv = 0; 2294 if (readwait) { 2295 rv = bufwait(bp); 2296 if (rv != 0) { 2297 brelse(bp); 2298 *bpp = NULL; 2299 } 2300 } 2301 return (rv); 2302 } 2303 2304 /* 2305 * Write, release buffer on completion. (Done by iodone 2306 * if async). Do not bother writing anything if the buffer 2307 * is invalid. 2308 * 2309 * Note that we set B_CACHE here, indicating that buffer is 2310 * fully valid and thus cacheable. This is true even of NFS 2311 * now so we set it generally. This could be set either here 2312 * or in biodone() since the I/O is synchronous. We put it 2313 * here. 2314 */ 2315 int 2316 bufwrite(struct buf *bp) 2317 { 2318 struct vnode *vp; 2319 long space; 2320 int oldflags, retval; 2321 bool vp_md; 2322 2323 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 2324 if ((bp->b_bufobj->bo_flag & BO_DEAD) != 0) { 2325 bp->b_flags |= B_INVAL | B_RELBUF; 2326 bp->b_flags &= ~B_CACHE; 2327 brelse(bp); 2328 return (ENXIO); 2329 } 2330 if ((bp->b_flags & B_INVAL) != 0) { 2331 brelse(bp); 2332 return (0); 2333 } 2334 2335 if ((bp->b_flags & B_BARRIER) != 0) 2336 atomic_add_long(&barrierwrites, 1); 2337 2338 oldflags = bp->b_flags; 2339 2340 KASSERT((bp->b_vflags & BV_BKGRDINPROG) == 0, 2341 ("FFS background buffer should not get here %p", bp)); 2342 2343 vp = bp->b_vp; 2344 vp_md = vp != NULL && (vp->v_vflag & VV_MD) != 0; 2345 2346 /* 2347 * Mark the buffer clean. Increment the bufobj write count 2348 * before bundirty() call, to prevent other thread from seeing 2349 * empty dirty list and zero counter for writes in progress, 2350 * falsely indicating that the bufobj is clean. 2351 */ 2352 bufobj_wref(bp->b_bufobj); 2353 bundirty(bp); 2354 2355 bp->b_flags &= ~B_DONE; 2356 bp->b_ioflags &= ~BIO_ERROR; 2357 bp->b_flags |= B_CACHE; 2358 bp->b_iocmd = BIO_WRITE; 2359 2360 vfs_busy_pages(bp, 1); 2361 2362 /* 2363 * Normal bwrites pipeline writes 2364 */ 2365 space = runningbufclaim(bp, bp->b_bufsize); 2366 2367 #ifdef RACCT 2368 if (racct_enable) { 2369 PROC_LOCK(curproc); 2370 racct_add_buf(curproc, bp, 1); 2371 PROC_UNLOCK(curproc); 2372 } 2373 #endif /* RACCT */ 2374 curthread->td_ru.ru_oublock++; 2375 if ((oldflags & B_ASYNC) != 0) 2376 BUF_KERNPROC(bp); 2377 bp->b_iooffset = dbtob(bp->b_blkno); 2378 buf_track(bp, __func__); 2379 bstrategy(bp); 2380 2381 if ((oldflags & B_ASYNC) == 0) { 2382 retval = bufwait(bp); 2383 brelse(bp); 2384 return (retval); 2385 } else if (space > hirunningspace) { 2386 /* 2387 * Don't allow the async write to saturate the I/O 2388 * system. We do not block here if it is the update 2389 * or syncer daemon trying to clean up as that can 2390 * lead to deadlock. 2391 */ 2392 if ((curthread->td_pflags & TDP_NORUNNINGBUF) == 0 && !vp_md) 2393 waitrunningbufspace(); 2394 } 2395 2396 return (0); 2397 } 2398 2399 void 2400 bufbdflush(struct bufobj *bo, struct buf *bp) 2401 { 2402 struct buf *nbp; 2403 struct bufdomain *bd; 2404 2405 bd = &bdomain[bo->bo_domain]; 2406 if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh + 10) { 2407 (void) VOP_FSYNC(bp->b_vp, MNT_NOWAIT, curthread); 2408 altbufferflushes++; 2409 } else if (bo->bo_dirty.bv_cnt > bd->bd_dirtybufthresh) { 2410 BO_LOCK(bo); 2411 /* 2412 * Try to find a buffer to flush. 2413 */ 2414 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) { 2415 if ((nbp->b_vflags & BV_BKGRDINPROG) || 2416 BUF_LOCK(nbp, 2417 LK_EXCLUSIVE | LK_NOWAIT, NULL)) 2418 continue; 2419 if (bp == nbp) 2420 panic("bdwrite: found ourselves"); 2421 BO_UNLOCK(bo); 2422 /* Don't countdeps with the bo lock held. */ 2423 if (buf_countdeps(nbp, 0)) { 2424 BO_LOCK(bo); 2425 BUF_UNLOCK(nbp); 2426 continue; 2427 } 2428 if (nbp->b_flags & B_CLUSTEROK) { 2429 vfs_bio_awrite(nbp); 2430 } else { 2431 bremfree(nbp); 2432 bawrite(nbp); 2433 } 2434 dirtybufferflushes++; 2435 break; 2436 } 2437 if (nbp == NULL) 2438 BO_UNLOCK(bo); 2439 } 2440 } 2441 2442 /* 2443 * Delayed write. (Buffer is marked dirty). Do not bother writing 2444 * anything if the buffer is marked invalid. 2445 * 2446 * Note that since the buffer must be completely valid, we can safely 2447 * set B_CACHE. In fact, we have to set B_CACHE here rather then in 2448 * biodone() in order to prevent getblk from writing the buffer 2449 * out synchronously. 2450 */ 2451 void 2452 bdwrite(struct buf *bp) 2453 { 2454 struct thread *td = curthread; 2455 struct vnode *vp; 2456 struct bufobj *bo; 2457 2458 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 2459 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp)); 2460 KASSERT((bp->b_flags & B_BARRIER) == 0, 2461 ("Barrier request in delayed write %p", bp)); 2462 2463 if (bp->b_flags & B_INVAL) { 2464 brelse(bp); 2465 return; 2466 } 2467 2468 /* 2469 * If we have too many dirty buffers, don't create any more. 2470 * If we are wildly over our limit, then force a complete 2471 * cleanup. Otherwise, just keep the situation from getting 2472 * out of control. Note that we have to avoid a recursive 2473 * disaster and not try to clean up after our own cleanup! 2474 */ 2475 vp = bp->b_vp; 2476 bo = bp->b_bufobj; 2477 if ((td->td_pflags & (TDP_COWINPROGRESS|TDP_INBDFLUSH)) == 0) { 2478 td->td_pflags |= TDP_INBDFLUSH; 2479 BO_BDFLUSH(bo, bp); 2480 td->td_pflags &= ~TDP_INBDFLUSH; 2481 } else 2482 recursiveflushes++; 2483 2484 bdirty(bp); 2485 /* 2486 * Set B_CACHE, indicating that the buffer is fully valid. This is 2487 * true even of NFS now. 2488 */ 2489 bp->b_flags |= B_CACHE; 2490 2491 /* 2492 * This bmap keeps the system from needing to do the bmap later, 2493 * perhaps when the system is attempting to do a sync. Since it 2494 * is likely that the indirect block -- or whatever other datastructure 2495 * that the filesystem needs is still in memory now, it is a good 2496 * thing to do this. Note also, that if the pageout daemon is 2497 * requesting a sync -- there might not be enough memory to do 2498 * the bmap then... So, this is important to do. 2499 */ 2500 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) { 2501 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL); 2502 } 2503 2504 buf_track(bp, __func__); 2505 2506 /* 2507 * Set the *dirty* buffer range based upon the VM system dirty 2508 * pages. 2509 * 2510 * Mark the buffer pages as clean. We need to do this here to 2511 * satisfy the vnode_pager and the pageout daemon, so that it 2512 * thinks that the pages have been "cleaned". Note that since 2513 * the pages are in a delayed write buffer -- the VFS layer 2514 * "will" see that the pages get written out on the next sync, 2515 * or perhaps the cluster will be completed. 2516 */ 2517 vfs_clean_pages_dirty_buf(bp); 2518 bqrelse(bp); 2519 2520 /* 2521 * note: we cannot initiate I/O from a bdwrite even if we wanted to, 2522 * due to the softdep code. 2523 */ 2524 } 2525 2526 /* 2527 * bdirty: 2528 * 2529 * Turn buffer into delayed write request. We must clear BIO_READ and 2530 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to 2531 * itself to properly update it in the dirty/clean lists. We mark it 2532 * B_DONE to ensure that any asynchronization of the buffer properly 2533 * clears B_DONE ( else a panic will occur later ). 2534 * 2535 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which 2536 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty() 2537 * should only be called if the buffer is known-good. 2538 * 2539 * Since the buffer is not on a queue, we do not update the numfreebuffers 2540 * count. 2541 * 2542 * The buffer must be on QUEUE_NONE. 2543 */ 2544 void 2545 bdirty(struct buf *bp) 2546 { 2547 2548 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X", 2549 bp, bp->b_vp, bp->b_flags); 2550 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp)); 2551 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE, 2552 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex)); 2553 bp->b_flags &= ~(B_RELBUF); 2554 bp->b_iocmd = BIO_WRITE; 2555 2556 if ((bp->b_flags & B_DELWRI) == 0) { 2557 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI; 2558 reassignbuf(bp); 2559 bdirtyadd(bp); 2560 } 2561 } 2562 2563 /* 2564 * bundirty: 2565 * 2566 * Clear B_DELWRI for buffer. 2567 * 2568 * Since the buffer is not on a queue, we do not update the numfreebuffers 2569 * count. 2570 * 2571 * The buffer must be on QUEUE_NONE. 2572 */ 2573 2574 void 2575 bundirty(struct buf *bp) 2576 { 2577 2578 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 2579 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp)); 2580 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE, 2581 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex)); 2582 2583 if (bp->b_flags & B_DELWRI) { 2584 bp->b_flags &= ~B_DELWRI; 2585 reassignbuf(bp); 2586 bdirtysub(bp); 2587 } 2588 /* 2589 * Since it is now being written, we can clear its deferred write flag. 2590 */ 2591 bp->b_flags &= ~B_DEFERRED; 2592 } 2593 2594 /* 2595 * bawrite: 2596 * 2597 * Asynchronous write. Start output on a buffer, but do not wait for 2598 * it to complete. The buffer is released when the output completes. 2599 * 2600 * bwrite() ( or the VOP routine anyway ) is responsible for handling 2601 * B_INVAL buffers. Not us. 2602 */ 2603 void 2604 bawrite(struct buf *bp) 2605 { 2606 2607 bp->b_flags |= B_ASYNC; 2608 (void) bwrite(bp); 2609 } 2610 2611 /* 2612 * babarrierwrite: 2613 * 2614 * Asynchronous barrier write. Start output on a buffer, but do not 2615 * wait for it to complete. Place a write barrier after this write so 2616 * that this buffer and all buffers written before it are committed to 2617 * the disk before any buffers written after this write are committed 2618 * to the disk. The buffer is released when the output completes. 2619 */ 2620 void 2621 babarrierwrite(struct buf *bp) 2622 { 2623 2624 bp->b_flags |= B_ASYNC | B_BARRIER; 2625 (void) bwrite(bp); 2626 } 2627 2628 /* 2629 * bbarrierwrite: 2630 * 2631 * Synchronous barrier write. Start output on a buffer and wait for 2632 * it to complete. Place a write barrier after this write so that 2633 * this buffer and all buffers written before it are committed to 2634 * the disk before any buffers written after this write are committed 2635 * to the disk. The buffer is released when the output completes. 2636 */ 2637 int 2638 bbarrierwrite(struct buf *bp) 2639 { 2640 2641 bp->b_flags |= B_BARRIER; 2642 return (bwrite(bp)); 2643 } 2644 2645 /* 2646 * bwillwrite: 2647 * 2648 * Called prior to the locking of any vnodes when we are expecting to 2649 * write. We do not want to starve the buffer cache with too many 2650 * dirty buffers so we block here. By blocking prior to the locking 2651 * of any vnodes we attempt to avoid the situation where a locked vnode 2652 * prevents the various system daemons from flushing related buffers. 2653 */ 2654 void 2655 bwillwrite(void) 2656 { 2657 2658 if (buf_dirty_count_severe()) { 2659 mtx_lock(&bdirtylock); 2660 while (buf_dirty_count_severe()) { 2661 bdirtywait = 1; 2662 msleep(&bdirtywait, &bdirtylock, (PRIBIO + 4), 2663 "flswai", 0); 2664 } 2665 mtx_unlock(&bdirtylock); 2666 } 2667 } 2668 2669 /* 2670 * Return true if we have too many dirty buffers. 2671 */ 2672 int 2673 buf_dirty_count_severe(void) 2674 { 2675 2676 return (!BIT_EMPTY(BUF_DOMAINS, &bdhidirty)); 2677 } 2678 2679 /* 2680 * brelse: 2681 * 2682 * Release a busy buffer and, if requested, free its resources. The 2683 * buffer will be stashed in the appropriate bufqueue[] allowing it 2684 * to be accessed later as a cache entity or reused for other purposes. 2685 */ 2686 void 2687 brelse(struct buf *bp) 2688 { 2689 struct mount *v_mnt; 2690 int qindex; 2691 2692 /* 2693 * Many functions erroneously call brelse with a NULL bp under rare 2694 * error conditions. Simply return when called with a NULL bp. 2695 */ 2696 if (bp == NULL) 2697 return; 2698 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X", 2699 bp, bp->b_vp, bp->b_flags); 2700 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), 2701 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp)); 2702 KASSERT((bp->b_flags & B_VMIO) != 0 || (bp->b_flags & B_NOREUSE) == 0, 2703 ("brelse: non-VMIO buffer marked NOREUSE")); 2704 2705 if (BUF_LOCKRECURSED(bp)) { 2706 /* 2707 * Do not process, in particular, do not handle the 2708 * B_INVAL/B_RELBUF and do not release to free list. 2709 */ 2710 BUF_UNLOCK(bp); 2711 return; 2712 } 2713 2714 if (bp->b_flags & B_MANAGED) { 2715 bqrelse(bp); 2716 return; 2717 } 2718 2719 if (LIST_EMPTY(&bp->b_dep)) { 2720 bp->b_flags &= ~B_IOSTARTED; 2721 } else { 2722 KASSERT((bp->b_flags & B_IOSTARTED) == 0, 2723 ("brelse: SU io not finished bp %p", bp)); 2724 } 2725 2726 if ((bp->b_vflags & (BV_BKGRDINPROG | BV_BKGRDERR)) == BV_BKGRDERR) { 2727 BO_LOCK(bp->b_bufobj); 2728 bp->b_vflags &= ~BV_BKGRDERR; 2729 BO_UNLOCK(bp->b_bufobj); 2730 bdirty(bp); 2731 } 2732 2733 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) && 2734 (bp->b_flags & B_INVALONERR)) { 2735 /* 2736 * Forced invalidation of dirty buffer contents, to be used 2737 * after a failed write in the rare case that the loss of the 2738 * contents is acceptable. The buffer is invalidated and 2739 * freed. 2740 */ 2741 bp->b_flags |= B_INVAL | B_RELBUF | B_NOCACHE; 2742 bp->b_flags &= ~(B_ASYNC | B_CACHE); 2743 } 2744 2745 if (bp->b_iocmd == BIO_WRITE && (bp->b_ioflags & BIO_ERROR) && 2746 (bp->b_error != ENXIO || !LIST_EMPTY(&bp->b_dep)) && 2747 !(bp->b_flags & B_INVAL)) { 2748 /* 2749 * Failed write, redirty. All errors except ENXIO (which 2750 * means the device is gone) are treated as being 2751 * transient. 2752 * 2753 * XXX Treating EIO as transient is not correct; the 2754 * contract with the local storage device drivers is that 2755 * they will only return EIO once the I/O is no longer 2756 * retriable. Network I/O also respects this through the 2757 * guarantees of TCP and/or the internal retries of NFS. 2758 * ENOMEM might be transient, but we also have no way of 2759 * knowing when its ok to retry/reschedule. In general, 2760 * this entire case should be made obsolete through better 2761 * error handling/recovery and resource scheduling. 2762 * 2763 * Do this also for buffers that failed with ENXIO, but have 2764 * non-empty dependencies - the soft updates code might need 2765 * to access the buffer to untangle them. 2766 * 2767 * Must clear BIO_ERROR to prevent pages from being scrapped. 2768 */ 2769 bp->b_ioflags &= ~BIO_ERROR; 2770 bdirty(bp); 2771 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) || 2772 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) { 2773 /* 2774 * Either a failed read I/O, or we were asked to free or not 2775 * cache the buffer, or we failed to write to a device that's 2776 * no longer present. 2777 */ 2778 bp->b_flags |= B_INVAL; 2779 if (!LIST_EMPTY(&bp->b_dep)) 2780 buf_deallocate(bp); 2781 if (bp->b_flags & B_DELWRI) 2782 bdirtysub(bp); 2783 bp->b_flags &= ~(B_DELWRI | B_CACHE); 2784 if ((bp->b_flags & B_VMIO) == 0) { 2785 allocbuf(bp, 0); 2786 if (bp->b_vp) 2787 brelvp(bp); 2788 } 2789 } 2790 2791 /* 2792 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_truncate() 2793 * is called with B_DELWRI set, the underlying pages may wind up 2794 * getting freed causing a previous write (bdwrite()) to get 'lost' 2795 * because pages associated with a B_DELWRI bp are marked clean. 2796 * 2797 * We still allow the B_INVAL case to call vfs_vmio_truncate(), even 2798 * if B_DELWRI is set. 2799 */ 2800 if (bp->b_flags & B_DELWRI) 2801 bp->b_flags &= ~B_RELBUF; 2802 2803 /* 2804 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer 2805 * constituted, not even NFS buffers now. Two flags effect this. If 2806 * B_INVAL, the struct buf is invalidated but the VM object is kept 2807 * around ( i.e. so it is trivial to reconstitute the buffer later ). 2808 * 2809 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be 2810 * invalidated. BIO_ERROR cannot be set for a failed write unless the 2811 * buffer is also B_INVAL because it hits the re-dirtying code above. 2812 * 2813 * Normally we can do this whether a buffer is B_DELWRI or not. If 2814 * the buffer is an NFS buffer, it is tracking piecemeal writes or 2815 * the commit state and we cannot afford to lose the buffer. If the 2816 * buffer has a background write in progress, we need to keep it 2817 * around to prevent it from being reconstituted and starting a second 2818 * background write. 2819 */ 2820 2821 v_mnt = bp->b_vp != NULL ? bp->b_vp->v_mount : NULL; 2822 2823 if ((bp->b_flags & B_VMIO) && (bp->b_flags & B_NOCACHE || 2824 (bp->b_ioflags & BIO_ERROR && bp->b_iocmd == BIO_READ)) && 2825 (v_mnt == NULL || (v_mnt->mnt_vfc->vfc_flags & VFCF_NETWORK) == 0 || 2826 vn_isdisk(bp->b_vp) || (bp->b_flags & B_DELWRI) == 0)) { 2827 vfs_vmio_invalidate(bp); 2828 allocbuf(bp, 0); 2829 } 2830 2831 if ((bp->b_flags & (B_INVAL | B_RELBUF)) != 0 || 2832 (bp->b_flags & (B_DELWRI | B_NOREUSE)) == B_NOREUSE) { 2833 allocbuf(bp, 0); 2834 bp->b_flags &= ~B_NOREUSE; 2835 if (bp->b_vp != NULL) 2836 brelvp(bp); 2837 } 2838 2839 /* 2840 * If the buffer has junk contents signal it and eventually 2841 * clean up B_DELWRI and diassociate the vnode so that gbincore() 2842 * doesn't find it. 2843 */ 2844 if (bp->b_bufsize == 0 || (bp->b_ioflags & BIO_ERROR) != 0 || 2845 (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) != 0) 2846 bp->b_flags |= B_INVAL; 2847 if (bp->b_flags & B_INVAL) { 2848 if (bp->b_flags & B_DELWRI) 2849 bundirty(bp); 2850 if (bp->b_vp) 2851 brelvp(bp); 2852 } 2853 2854 buf_track(bp, __func__); 2855 2856 /* buffers with no memory */ 2857 if (bp->b_bufsize == 0) { 2858 buf_free(bp); 2859 return; 2860 } 2861 /* buffers with junk contents */ 2862 if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) || 2863 (bp->b_ioflags & BIO_ERROR)) { 2864 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA); 2865 if (bp->b_vflags & BV_BKGRDINPROG) 2866 panic("losing buffer 2"); 2867 qindex = QUEUE_CLEAN; 2868 bp->b_flags |= B_AGE; 2869 /* remaining buffers */ 2870 } else if (bp->b_flags & B_DELWRI) 2871 qindex = QUEUE_DIRTY; 2872 else 2873 qindex = QUEUE_CLEAN; 2874 2875 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY)) 2876 panic("brelse: not dirty"); 2877 2878 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT); 2879 bp->b_xflags &= ~(BX_CVTENXIO); 2880 /* binsfree unlocks bp. */ 2881 binsfree(bp, qindex); 2882 } 2883 2884 /* 2885 * Release a buffer back to the appropriate queue but do not try to free 2886 * it. The buffer is expected to be used again soon. 2887 * 2888 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by 2889 * biodone() to requeue an async I/O on completion. It is also used when 2890 * known good buffers need to be requeued but we think we may need the data 2891 * again soon. 2892 * 2893 * XXX we should be able to leave the B_RELBUF hint set on completion. 2894 */ 2895 void 2896 bqrelse(struct buf *bp) 2897 { 2898 int qindex; 2899 2900 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 2901 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), 2902 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp)); 2903 2904 qindex = QUEUE_NONE; 2905 if (BUF_LOCKRECURSED(bp)) { 2906 /* do not release to free list */ 2907 BUF_UNLOCK(bp); 2908 return; 2909 } 2910 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF); 2911 bp->b_xflags &= ~(BX_CVTENXIO); 2912 2913 if (LIST_EMPTY(&bp->b_dep)) { 2914 bp->b_flags &= ~B_IOSTARTED; 2915 } else { 2916 KASSERT((bp->b_flags & B_IOSTARTED) == 0, 2917 ("bqrelse: SU io not finished bp %p", bp)); 2918 } 2919 2920 if (bp->b_flags & B_MANAGED) { 2921 if (bp->b_flags & B_REMFREE) 2922 bremfreef(bp); 2923 goto out; 2924 } 2925 2926 /* buffers with stale but valid contents */ 2927 if ((bp->b_flags & B_DELWRI) != 0 || (bp->b_vflags & (BV_BKGRDINPROG | 2928 BV_BKGRDERR)) == BV_BKGRDERR) { 2929 BO_LOCK(bp->b_bufobj); 2930 bp->b_vflags &= ~BV_BKGRDERR; 2931 BO_UNLOCK(bp->b_bufobj); 2932 qindex = QUEUE_DIRTY; 2933 } else { 2934 if ((bp->b_flags & B_DELWRI) == 0 && 2935 (bp->b_xflags & BX_VNDIRTY)) 2936 panic("bqrelse: not dirty"); 2937 if ((bp->b_flags & B_NOREUSE) != 0) { 2938 brelse(bp); 2939 return; 2940 } 2941 qindex = QUEUE_CLEAN; 2942 } 2943 buf_track(bp, __func__); 2944 /* binsfree unlocks bp. */ 2945 binsfree(bp, qindex); 2946 return; 2947 2948 out: 2949 buf_track(bp, __func__); 2950 /* unlock */ 2951 BUF_UNLOCK(bp); 2952 } 2953 2954 /* 2955 * Complete I/O to a VMIO backed page. Validate the pages as appropriate, 2956 * restore bogus pages. 2957 */ 2958 static void 2959 vfs_vmio_iodone(struct buf *bp) 2960 { 2961 vm_ooffset_t foff; 2962 vm_page_t m; 2963 vm_object_t obj; 2964 struct vnode *vp __unused; 2965 int i, iosize, resid; 2966 bool bogus; 2967 2968 obj = bp->b_bufobj->bo_object; 2969 KASSERT(blockcount_read(&obj->paging_in_progress) >= bp->b_npages, 2970 ("vfs_vmio_iodone: paging in progress(%d) < b_npages(%d)", 2971 blockcount_read(&obj->paging_in_progress), bp->b_npages)); 2972 2973 vp = bp->b_vp; 2974 VNPASS(vp->v_holdcnt > 0, vp); 2975 VNPASS(vp->v_object != NULL, vp); 2976 2977 foff = bp->b_offset; 2978 KASSERT(bp->b_offset != NOOFFSET, 2979 ("vfs_vmio_iodone: bp %p has no buffer offset", bp)); 2980 2981 bogus = false; 2982 iosize = bp->b_bcount - bp->b_resid; 2983 for (i = 0; i < bp->b_npages; i++) { 2984 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff; 2985 if (resid > iosize) 2986 resid = iosize; 2987 2988 /* 2989 * cleanup bogus pages, restoring the originals 2990 */ 2991 m = bp->b_pages[i]; 2992 if (m == bogus_page) { 2993 bogus = true; 2994 m = vm_page_relookup(obj, OFF_TO_IDX(foff)); 2995 if (m == NULL) 2996 panic("biodone: page disappeared!"); 2997 bp->b_pages[i] = m; 2998 } else if ((bp->b_iocmd == BIO_READ) && resid > 0) { 2999 /* 3000 * In the write case, the valid and clean bits are 3001 * already changed correctly ( see bdwrite() ), so we 3002 * only need to do this here in the read case. 3003 */ 3004 KASSERT((m->dirty & vm_page_bits(foff & PAGE_MASK, 3005 resid)) == 0, ("vfs_vmio_iodone: page %p " 3006 "has unexpected dirty bits", m)); 3007 vfs_page_set_valid(bp, foff, m); 3008 } 3009 KASSERT(OFF_TO_IDX(foff) == m->pindex, 3010 ("vfs_vmio_iodone: foff(%jd)/pindex(%ju) mismatch", 3011 (intmax_t)foff, (uintmax_t)m->pindex)); 3012 3013 vm_page_sunbusy(m); 3014 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 3015 iosize -= resid; 3016 } 3017 vm_object_pip_wakeupn(obj, bp->b_npages); 3018 if (bogus && buf_mapped(bp)) { 3019 BUF_CHECK_MAPPED(bp); 3020 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 3021 bp->b_pages, bp->b_npages); 3022 } 3023 } 3024 3025 /* 3026 * Perform page invalidation when a buffer is released. The fully invalid 3027 * pages will be reclaimed later in vfs_vmio_truncate(). 3028 */ 3029 static void 3030 vfs_vmio_invalidate(struct buf *bp) 3031 { 3032 vm_object_t obj; 3033 vm_page_t m; 3034 int flags, i, resid, poffset, presid; 3035 3036 if (buf_mapped(bp)) { 3037 BUF_CHECK_MAPPED(bp); 3038 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), bp->b_npages); 3039 } else 3040 BUF_CHECK_UNMAPPED(bp); 3041 /* 3042 * Get the base offset and length of the buffer. Note that 3043 * in the VMIO case if the buffer block size is not 3044 * page-aligned then b_data pointer may not be page-aligned. 3045 * But our b_pages[] array *IS* page aligned. 3046 * 3047 * block sizes less then DEV_BSIZE (usually 512) are not 3048 * supported due to the page granularity bits (m->valid, 3049 * m->dirty, etc...). 3050 * 3051 * See man buf(9) for more information 3052 */ 3053 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0; 3054 obj = bp->b_bufobj->bo_object; 3055 resid = bp->b_bufsize; 3056 poffset = bp->b_offset & PAGE_MASK; 3057 VM_OBJECT_WLOCK(obj); 3058 for (i = 0; i < bp->b_npages; i++) { 3059 m = bp->b_pages[i]; 3060 if (m == bogus_page) 3061 panic("vfs_vmio_invalidate: Unexpected bogus page."); 3062 bp->b_pages[i] = NULL; 3063 3064 presid = resid > (PAGE_SIZE - poffset) ? 3065 (PAGE_SIZE - poffset) : resid; 3066 KASSERT(presid >= 0, ("brelse: extra page")); 3067 vm_page_busy_acquire(m, VM_ALLOC_SBUSY); 3068 if (pmap_page_wired_mappings(m) == 0) 3069 vm_page_set_invalid(m, poffset, presid); 3070 vm_page_sunbusy(m); 3071 vm_page_release_locked(m, flags); 3072 resid -= presid; 3073 poffset = 0; 3074 } 3075 VM_OBJECT_WUNLOCK(obj); 3076 bp->b_npages = 0; 3077 } 3078 3079 /* 3080 * Page-granular truncation of an existing VMIO buffer. 3081 */ 3082 static void 3083 vfs_vmio_truncate(struct buf *bp, int desiredpages) 3084 { 3085 vm_object_t obj; 3086 vm_page_t m; 3087 int flags, i; 3088 3089 if (bp->b_npages == desiredpages) 3090 return; 3091 3092 if (buf_mapped(bp)) { 3093 BUF_CHECK_MAPPED(bp); 3094 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) + 3095 (desiredpages << PAGE_SHIFT), bp->b_npages - desiredpages); 3096 } else 3097 BUF_CHECK_UNMAPPED(bp); 3098 3099 /* 3100 * The object lock is needed only if we will attempt to free pages. 3101 */ 3102 flags = (bp->b_flags & B_NOREUSE) != 0 ? VPR_NOREUSE : 0; 3103 if ((bp->b_flags & B_DIRECT) != 0) { 3104 flags |= VPR_TRYFREE; 3105 obj = bp->b_bufobj->bo_object; 3106 VM_OBJECT_WLOCK(obj); 3107 } else { 3108 obj = NULL; 3109 } 3110 for (i = desiredpages; i < bp->b_npages; i++) { 3111 m = bp->b_pages[i]; 3112 KASSERT(m != bogus_page, ("allocbuf: bogus page found")); 3113 bp->b_pages[i] = NULL; 3114 if (obj != NULL) 3115 vm_page_release_locked(m, flags); 3116 else 3117 vm_page_release(m, flags); 3118 } 3119 if (obj != NULL) 3120 VM_OBJECT_WUNLOCK(obj); 3121 bp->b_npages = desiredpages; 3122 } 3123 3124 /* 3125 * Byte granular extension of VMIO buffers. 3126 */ 3127 static void 3128 vfs_vmio_extend(struct buf *bp, int desiredpages, int size) 3129 { 3130 /* 3131 * We are growing the buffer, possibly in a 3132 * byte-granular fashion. 3133 */ 3134 vm_object_t obj; 3135 vm_offset_t toff; 3136 vm_offset_t tinc; 3137 vm_page_t m; 3138 3139 /* 3140 * Step 1, bring in the VM pages from the object, allocating 3141 * them if necessary. We must clear B_CACHE if these pages 3142 * are not valid for the range covered by the buffer. 3143 */ 3144 obj = bp->b_bufobj->bo_object; 3145 if (bp->b_npages < desiredpages) { 3146 KASSERT(desiredpages <= atop(maxbcachebuf), 3147 ("vfs_vmio_extend past maxbcachebuf %p %d %u", 3148 bp, desiredpages, maxbcachebuf)); 3149 3150 /* 3151 * We must allocate system pages since blocking 3152 * here could interfere with paging I/O, no 3153 * matter which process we are. 3154 * 3155 * Only exclusive busy can be tested here. 3156 * Blocking on shared busy might lead to 3157 * deadlocks once allocbuf() is called after 3158 * pages are vfs_busy_pages(). 3159 */ 3160 (void)vm_page_grab_pages_unlocked(obj, 3161 OFF_TO_IDX(bp->b_offset) + bp->b_npages, 3162 VM_ALLOC_SYSTEM | VM_ALLOC_IGN_SBUSY | 3163 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED, 3164 &bp->b_pages[bp->b_npages], desiredpages - bp->b_npages); 3165 bp->b_npages = desiredpages; 3166 } 3167 3168 /* 3169 * Step 2. We've loaded the pages into the buffer, 3170 * we have to figure out if we can still have B_CACHE 3171 * set. Note that B_CACHE is set according to the 3172 * byte-granular range ( bcount and size ), not the 3173 * aligned range ( newbsize ). 3174 * 3175 * The VM test is against m->valid, which is DEV_BSIZE 3176 * aligned. Needless to say, the validity of the data 3177 * needs to also be DEV_BSIZE aligned. Note that this 3178 * fails with NFS if the server or some other client 3179 * extends the file's EOF. If our buffer is resized, 3180 * B_CACHE may remain set! XXX 3181 */ 3182 toff = bp->b_bcount; 3183 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK); 3184 while ((bp->b_flags & B_CACHE) && toff < size) { 3185 vm_pindex_t pi; 3186 3187 if (tinc > (size - toff)) 3188 tinc = size - toff; 3189 pi = ((bp->b_offset & PAGE_MASK) + toff) >> PAGE_SHIFT; 3190 m = bp->b_pages[pi]; 3191 vfs_buf_test_cache(bp, bp->b_offset, toff, tinc, m); 3192 toff += tinc; 3193 tinc = PAGE_SIZE; 3194 } 3195 3196 /* 3197 * Step 3, fixup the KVA pmap. 3198 */ 3199 if (buf_mapped(bp)) 3200 bpmap_qenter(bp); 3201 else 3202 BUF_CHECK_UNMAPPED(bp); 3203 } 3204 3205 /* 3206 * Check to see if a block at a particular lbn is available for a clustered 3207 * write. 3208 */ 3209 static int 3210 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno) 3211 { 3212 struct buf *bpa; 3213 int match; 3214 3215 match = 0; 3216 3217 /* If the buf isn't in core skip it */ 3218 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL) 3219 return (0); 3220 3221 /* If the buf is busy we don't want to wait for it */ 3222 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) 3223 return (0); 3224 3225 /* Only cluster with valid clusterable delayed write buffers */ 3226 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) != 3227 (B_DELWRI | B_CLUSTEROK)) 3228 goto done; 3229 3230 if (bpa->b_bufsize != size) 3231 goto done; 3232 3233 /* 3234 * Check to see if it is in the expected place on disk and that the 3235 * block has been mapped. 3236 */ 3237 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno)) 3238 match = 1; 3239 done: 3240 BUF_UNLOCK(bpa); 3241 return (match); 3242 } 3243 3244 /* 3245 * vfs_bio_awrite: 3246 * 3247 * Implement clustered async writes for clearing out B_DELWRI buffers. 3248 * This is much better then the old way of writing only one buffer at 3249 * a time. Note that we may not be presented with the buffers in the 3250 * correct order, so we search for the cluster in both directions. 3251 */ 3252 int 3253 vfs_bio_awrite(struct buf *bp) 3254 { 3255 struct bufobj *bo; 3256 int i; 3257 int j; 3258 daddr_t lblkno = bp->b_lblkno; 3259 struct vnode *vp = bp->b_vp; 3260 int ncl; 3261 int nwritten; 3262 int size; 3263 int maxcl; 3264 int gbflags; 3265 3266 bo = &vp->v_bufobj; 3267 gbflags = (bp->b_data == unmapped_buf) ? GB_UNMAPPED : 0; 3268 /* 3269 * right now we support clustered writing only to regular files. If 3270 * we find a clusterable block we could be in the middle of a cluster 3271 * rather then at the beginning. 3272 */ 3273 if ((vp->v_type == VREG) && 3274 (vp->v_mount != 0) && /* Only on nodes that have the size info */ 3275 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) { 3276 size = vp->v_mount->mnt_stat.f_iosize; 3277 maxcl = maxphys / size; 3278 3279 BO_RLOCK(bo); 3280 for (i = 1; i < maxcl; i++) 3281 if (vfs_bio_clcheck(vp, size, lblkno + i, 3282 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0) 3283 break; 3284 3285 for (j = 1; i + j <= maxcl && j <= lblkno; j++) 3286 if (vfs_bio_clcheck(vp, size, lblkno - j, 3287 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0) 3288 break; 3289 BO_RUNLOCK(bo); 3290 --j; 3291 ncl = i + j; 3292 /* 3293 * this is a possible cluster write 3294 */ 3295 if (ncl != 1) { 3296 BUF_UNLOCK(bp); 3297 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl, 3298 gbflags); 3299 return (nwritten); 3300 } 3301 } 3302 bremfree(bp); 3303 bp->b_flags |= B_ASYNC; 3304 /* 3305 * default (old) behavior, writing out only one block 3306 * 3307 * XXX returns b_bufsize instead of b_bcount for nwritten? 3308 */ 3309 nwritten = bp->b_bufsize; 3310 (void) bwrite(bp); 3311 3312 return (nwritten); 3313 } 3314 3315 /* 3316 * getnewbuf_kva: 3317 * 3318 * Allocate KVA for an empty buf header according to gbflags. 3319 */ 3320 static int 3321 getnewbuf_kva(struct buf *bp, int gbflags, int maxsize) 3322 { 3323 3324 if ((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_UNMAPPED) { 3325 /* 3326 * In order to keep fragmentation sane we only allocate kva 3327 * in BKVASIZE chunks. XXX with vmem we can do page size. 3328 */ 3329 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK; 3330 3331 if (maxsize != bp->b_kvasize && 3332 bufkva_alloc(bp, maxsize, gbflags)) 3333 return (ENOSPC); 3334 } 3335 return (0); 3336 } 3337 3338 /* 3339 * getnewbuf: 3340 * 3341 * Find and initialize a new buffer header, freeing up existing buffers 3342 * in the bufqueues as necessary. The new buffer is returned locked. 3343 * 3344 * We block if: 3345 * We have insufficient buffer headers 3346 * We have insufficient buffer space 3347 * buffer_arena is too fragmented ( space reservation fails ) 3348 * If we have to flush dirty buffers ( but we try to avoid this ) 3349 * 3350 * The caller is responsible for releasing the reserved bufspace after 3351 * allocbuf() is called. 3352 */ 3353 static struct buf * 3354 getnewbuf(struct vnode *vp, int slpflag, int slptimeo, int maxsize, int gbflags) 3355 { 3356 struct bufdomain *bd; 3357 struct buf *bp; 3358 bool metadata, reserved; 3359 3360 bp = NULL; 3361 KASSERT((gbflags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC, 3362 ("GB_KVAALLOC only makes sense with GB_UNMAPPED")); 3363 if (!unmapped_buf_allowed) 3364 gbflags &= ~(GB_UNMAPPED | GB_KVAALLOC); 3365 3366 if (vp == NULL || (vp->v_vflag & (VV_MD | VV_SYSTEM)) != 0 || 3367 vp->v_type == VCHR) 3368 metadata = true; 3369 else 3370 metadata = false; 3371 if (vp == NULL) 3372 bd = &bdomain[0]; 3373 else 3374 bd = &bdomain[vp->v_bufobj.bo_domain]; 3375 3376 counter_u64_add(getnewbufcalls, 1); 3377 reserved = false; 3378 do { 3379 if (reserved == false && 3380 bufspace_reserve(bd, maxsize, metadata) != 0) { 3381 counter_u64_add(getnewbufrestarts, 1); 3382 continue; 3383 } 3384 reserved = true; 3385 if ((bp = buf_alloc(bd)) == NULL) { 3386 counter_u64_add(getnewbufrestarts, 1); 3387 continue; 3388 } 3389 if (getnewbuf_kva(bp, gbflags, maxsize) == 0) 3390 return (bp); 3391 break; 3392 } while (buf_recycle(bd, false) == 0); 3393 3394 if (reserved) 3395 bufspace_release(bd, maxsize); 3396 if (bp != NULL) { 3397 bp->b_flags |= B_INVAL; 3398 brelse(bp); 3399 } 3400 bufspace_wait(bd, vp, gbflags, slpflag, slptimeo); 3401 3402 return (NULL); 3403 } 3404 3405 /* 3406 * buf_daemon: 3407 * 3408 * buffer flushing daemon. Buffers are normally flushed by the 3409 * update daemon but if it cannot keep up this process starts to 3410 * take the load in an attempt to prevent getnewbuf() from blocking. 3411 */ 3412 static struct kproc_desc buf_kp = { 3413 "bufdaemon", 3414 buf_daemon, 3415 &bufdaemonproc 3416 }; 3417 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp); 3418 3419 static int 3420 buf_flush(struct vnode *vp, struct bufdomain *bd, int target) 3421 { 3422 int flushed; 3423 3424 flushed = flushbufqueues(vp, bd, target, 0); 3425 if (flushed == 0) { 3426 /* 3427 * Could not find any buffers without rollback 3428 * dependencies, so just write the first one 3429 * in the hopes of eventually making progress. 3430 */ 3431 if (vp != NULL && target > 2) 3432 target /= 2; 3433 flushbufqueues(vp, bd, target, 1); 3434 } 3435 return (flushed); 3436 } 3437 3438 static void 3439 buf_daemon_shutdown(void *arg __unused, int howto __unused) 3440 { 3441 int error; 3442 3443 if (KERNEL_PANICKED()) 3444 return; 3445 3446 mtx_lock(&bdlock); 3447 bd_shutdown = true; 3448 wakeup(&bd_request); 3449 error = msleep(&bd_shutdown, &bdlock, 0, "buf_daemon_shutdown", 3450 60 * hz); 3451 mtx_unlock(&bdlock); 3452 if (error != 0) 3453 printf("bufdaemon wait error: %d\n", error); 3454 } 3455 3456 static void 3457 buf_daemon(void) 3458 { 3459 struct bufdomain *bd; 3460 int speedupreq; 3461 int lodirty; 3462 int i; 3463 3464 /* 3465 * This process needs to be suspended prior to shutdown sync. 3466 */ 3467 EVENTHANDLER_REGISTER(shutdown_pre_sync, buf_daemon_shutdown, NULL, 3468 SHUTDOWN_PRI_LAST + 100); 3469 3470 /* 3471 * Start the buf clean daemons as children threads. 3472 */ 3473 for (i = 0 ; i < buf_domains; i++) { 3474 int error; 3475 3476 error = kthread_add((void (*)(void *))bufspace_daemon, 3477 &bdomain[i], curproc, NULL, 0, 0, "bufspacedaemon-%d", i); 3478 if (error) 3479 panic("error %d spawning bufspace daemon", error); 3480 } 3481 3482 /* 3483 * This process is allowed to take the buffer cache to the limit 3484 */ 3485 curthread->td_pflags |= TDP_NORUNNINGBUF | TDP_BUFNEED; 3486 mtx_lock(&bdlock); 3487 while (!bd_shutdown) { 3488 bd_request = 0; 3489 mtx_unlock(&bdlock); 3490 3491 /* 3492 * Save speedupreq for this pass and reset to capture new 3493 * requests. 3494 */ 3495 speedupreq = bd_speedupreq; 3496 bd_speedupreq = 0; 3497 3498 /* 3499 * Flush each domain sequentially according to its level and 3500 * the speedup request. 3501 */ 3502 for (i = 0; i < buf_domains; i++) { 3503 bd = &bdomain[i]; 3504 if (speedupreq) 3505 lodirty = bd->bd_numdirtybuffers / 2; 3506 else 3507 lodirty = bd->bd_lodirtybuffers; 3508 while (bd->bd_numdirtybuffers > lodirty) { 3509 if (buf_flush(NULL, bd, 3510 bd->bd_numdirtybuffers - lodirty) == 0) 3511 break; 3512 kern_yield(PRI_USER); 3513 } 3514 } 3515 3516 /* 3517 * Only clear bd_request if we have reached our low water 3518 * mark. The buf_daemon normally waits 1 second and 3519 * then incrementally flushes any dirty buffers that have 3520 * built up, within reason. 3521 * 3522 * If we were unable to hit our low water mark and couldn't 3523 * find any flushable buffers, we sleep for a short period 3524 * to avoid endless loops on unlockable buffers. 3525 */ 3526 mtx_lock(&bdlock); 3527 if (bd_shutdown) 3528 break; 3529 if (BIT_EMPTY(BUF_DOMAINS, &bdlodirty)) { 3530 /* 3531 * We reached our low water mark, reset the 3532 * request and sleep until we are needed again. 3533 * The sleep is just so the suspend code works. 3534 */ 3535 bd_request = 0; 3536 /* 3537 * Do an extra wakeup in case dirty threshold 3538 * changed via sysctl and the explicit transition 3539 * out of shortfall was missed. 3540 */ 3541 bdirtywakeup(); 3542 if (runningbufspace <= lorunningspace) 3543 runningwakeup(); 3544 msleep(&bd_request, &bdlock, PVM, "psleep", hz); 3545 } else { 3546 /* 3547 * We couldn't find any flushable dirty buffers but 3548 * still have too many dirty buffers, we 3549 * have to sleep and try again. (rare) 3550 */ 3551 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10); 3552 } 3553 } 3554 wakeup(&bd_shutdown); 3555 mtx_unlock(&bdlock); 3556 kthread_exit(); 3557 } 3558 3559 /* 3560 * flushbufqueues: 3561 * 3562 * Try to flush a buffer in the dirty queue. We must be careful to 3563 * free up B_INVAL buffers instead of write them, which NFS is 3564 * particularly sensitive to. 3565 */ 3566 static int flushwithdeps = 0; 3567 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW | CTLFLAG_STATS, 3568 &flushwithdeps, 0, 3569 "Number of buffers flushed with dependencies that require rollbacks"); 3570 3571 static int 3572 flushbufqueues(struct vnode *lvp, struct bufdomain *bd, int target, 3573 int flushdeps) 3574 { 3575 struct bufqueue *bq; 3576 struct buf *sentinel; 3577 struct vnode *vp; 3578 struct mount *mp; 3579 struct buf *bp; 3580 int hasdeps; 3581 int flushed; 3582 int error; 3583 bool unlock; 3584 3585 flushed = 0; 3586 bq = &bd->bd_dirtyq; 3587 bp = NULL; 3588 sentinel = malloc(sizeof(struct buf), M_TEMP, M_WAITOK | M_ZERO); 3589 sentinel->b_qindex = QUEUE_SENTINEL; 3590 BQ_LOCK(bq); 3591 TAILQ_INSERT_HEAD(&bq->bq_queue, sentinel, b_freelist); 3592 BQ_UNLOCK(bq); 3593 while (flushed != target) { 3594 maybe_yield(); 3595 BQ_LOCK(bq); 3596 bp = TAILQ_NEXT(sentinel, b_freelist); 3597 if (bp != NULL) { 3598 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist); 3599 TAILQ_INSERT_AFTER(&bq->bq_queue, bp, sentinel, 3600 b_freelist); 3601 } else { 3602 BQ_UNLOCK(bq); 3603 break; 3604 } 3605 /* 3606 * Skip sentinels inserted by other invocations of the 3607 * flushbufqueues(), taking care to not reorder them. 3608 * 3609 * Only flush the buffers that belong to the 3610 * vnode locked by the curthread. 3611 */ 3612 if (bp->b_qindex == QUEUE_SENTINEL || (lvp != NULL && 3613 bp->b_vp != lvp)) { 3614 BQ_UNLOCK(bq); 3615 continue; 3616 } 3617 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL); 3618 BQ_UNLOCK(bq); 3619 if (error != 0) 3620 continue; 3621 3622 /* 3623 * BKGRDINPROG can only be set with the buf and bufobj 3624 * locks both held. We tolerate a race to clear it here. 3625 */ 3626 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 || 3627 (bp->b_flags & B_DELWRI) == 0) { 3628 BUF_UNLOCK(bp); 3629 continue; 3630 } 3631 if (bp->b_flags & B_INVAL) { 3632 bremfreef(bp); 3633 brelse(bp); 3634 flushed++; 3635 continue; 3636 } 3637 3638 if (!LIST_EMPTY(&bp->b_dep) && buf_countdeps(bp, 0)) { 3639 if (flushdeps == 0) { 3640 BUF_UNLOCK(bp); 3641 continue; 3642 } 3643 hasdeps = 1; 3644 } else 3645 hasdeps = 0; 3646 /* 3647 * We must hold the lock on a vnode before writing 3648 * one of its buffers. Otherwise we may confuse, or 3649 * in the case of a snapshot vnode, deadlock the 3650 * system. 3651 * 3652 * The lock order here is the reverse of the normal 3653 * of vnode followed by buf lock. This is ok because 3654 * the NOWAIT will prevent deadlock. 3655 */ 3656 vp = bp->b_vp; 3657 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) { 3658 BUF_UNLOCK(bp); 3659 continue; 3660 } 3661 if (lvp == NULL) { 3662 unlock = true; 3663 error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT); 3664 } else { 3665 ASSERT_VOP_LOCKED(vp, "getbuf"); 3666 unlock = false; 3667 error = VOP_ISLOCKED(vp) == LK_EXCLUSIVE ? 0 : 3668 vn_lock(vp, LK_TRYUPGRADE); 3669 } 3670 if (error == 0) { 3671 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X", 3672 bp, bp->b_vp, bp->b_flags); 3673 if (curproc == bufdaemonproc) { 3674 vfs_bio_awrite(bp); 3675 } else { 3676 bremfree(bp); 3677 bwrite(bp); 3678 counter_u64_add(notbufdflushes, 1); 3679 } 3680 vn_finished_write(mp); 3681 if (unlock) 3682 VOP_UNLOCK(vp); 3683 flushwithdeps += hasdeps; 3684 flushed++; 3685 3686 /* 3687 * Sleeping on runningbufspace while holding 3688 * vnode lock leads to deadlock. 3689 */ 3690 if (curproc == bufdaemonproc && 3691 runningbufspace > hirunningspace) 3692 waitrunningbufspace(); 3693 continue; 3694 } 3695 vn_finished_write(mp); 3696 BUF_UNLOCK(bp); 3697 } 3698 BQ_LOCK(bq); 3699 TAILQ_REMOVE(&bq->bq_queue, sentinel, b_freelist); 3700 BQ_UNLOCK(bq); 3701 free(sentinel, M_TEMP); 3702 return (flushed); 3703 } 3704 3705 /* 3706 * Check to see if a block is currently memory resident. 3707 */ 3708 struct buf * 3709 incore(struct bufobj *bo, daddr_t blkno) 3710 { 3711 return (gbincore_unlocked(bo, blkno)); 3712 } 3713 3714 /* 3715 * Returns true if no I/O is needed to access the 3716 * associated VM object. This is like incore except 3717 * it also hunts around in the VM system for the data. 3718 */ 3719 bool 3720 inmem(struct vnode * vp, daddr_t blkno) 3721 { 3722 vm_object_t obj; 3723 vm_offset_t toff, tinc, size; 3724 vm_page_t m, n; 3725 vm_ooffset_t off; 3726 int valid; 3727 3728 ASSERT_VOP_LOCKED(vp, "inmem"); 3729 3730 if (incore(&vp->v_bufobj, blkno)) 3731 return (true); 3732 if (vp->v_mount == NULL) 3733 return (false); 3734 obj = vp->v_object; 3735 if (obj == NULL) 3736 return (false); 3737 3738 size = PAGE_SIZE; 3739 if (size > vp->v_mount->mnt_stat.f_iosize) 3740 size = vp->v_mount->mnt_stat.f_iosize; 3741 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize; 3742 3743 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) { 3744 m = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff)); 3745 recheck: 3746 if (m == NULL) 3747 return (false); 3748 3749 tinc = size; 3750 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK)) 3751 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK); 3752 /* 3753 * Consider page validity only if page mapping didn't change 3754 * during the check. 3755 */ 3756 valid = vm_page_is_valid(m, 3757 (vm_offset_t)((toff + off) & PAGE_MASK), tinc); 3758 n = vm_page_lookup_unlocked(obj, OFF_TO_IDX(off + toff)); 3759 if (m != n) { 3760 m = n; 3761 goto recheck; 3762 } 3763 if (!valid) 3764 return (false); 3765 } 3766 return (true); 3767 } 3768 3769 /* 3770 * Set the dirty range for a buffer based on the status of the dirty 3771 * bits in the pages comprising the buffer. The range is limited 3772 * to the size of the buffer. 3773 * 3774 * Tell the VM system that the pages associated with this buffer 3775 * are clean. This is used for delayed writes where the data is 3776 * going to go to disk eventually without additional VM intevention. 3777 * 3778 * Note that while we only really need to clean through to b_bcount, we 3779 * just go ahead and clean through to b_bufsize. 3780 */ 3781 static void 3782 vfs_clean_pages_dirty_buf(struct buf *bp) 3783 { 3784 vm_ooffset_t foff, noff, eoff; 3785 vm_page_t m; 3786 int i; 3787 3788 if ((bp->b_flags & B_VMIO) == 0 || bp->b_bufsize == 0) 3789 return; 3790 3791 foff = bp->b_offset; 3792 KASSERT(bp->b_offset != NOOFFSET, 3793 ("vfs_clean_pages_dirty_buf: no buffer offset")); 3794 3795 vfs_busy_pages_acquire(bp); 3796 vfs_setdirty_range(bp); 3797 for (i = 0; i < bp->b_npages; i++) { 3798 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 3799 eoff = noff; 3800 if (eoff > bp->b_offset + bp->b_bufsize) 3801 eoff = bp->b_offset + bp->b_bufsize; 3802 m = bp->b_pages[i]; 3803 vfs_page_set_validclean(bp, foff, m); 3804 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */ 3805 foff = noff; 3806 } 3807 vfs_busy_pages_release(bp); 3808 } 3809 3810 static void 3811 vfs_setdirty_range(struct buf *bp) 3812 { 3813 vm_offset_t boffset; 3814 vm_offset_t eoffset; 3815 int i; 3816 3817 /* 3818 * test the pages to see if they have been modified directly 3819 * by users through the VM system. 3820 */ 3821 for (i = 0; i < bp->b_npages; i++) 3822 vm_page_test_dirty(bp->b_pages[i]); 3823 3824 /* 3825 * Calculate the encompassing dirty range, boffset and eoffset, 3826 * (eoffset - boffset) bytes. 3827 */ 3828 3829 for (i = 0; i < bp->b_npages; i++) { 3830 if (bp->b_pages[i]->dirty) 3831 break; 3832 } 3833 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK); 3834 3835 for (i = bp->b_npages - 1; i >= 0; --i) { 3836 if (bp->b_pages[i]->dirty) { 3837 break; 3838 } 3839 } 3840 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK); 3841 3842 /* 3843 * Fit it to the buffer. 3844 */ 3845 3846 if (eoffset > bp->b_bcount) 3847 eoffset = bp->b_bcount; 3848 3849 /* 3850 * If we have a good dirty range, merge with the existing 3851 * dirty range. 3852 */ 3853 3854 if (boffset < eoffset) { 3855 if (bp->b_dirtyoff > boffset) 3856 bp->b_dirtyoff = boffset; 3857 if (bp->b_dirtyend < eoffset) 3858 bp->b_dirtyend = eoffset; 3859 } 3860 } 3861 3862 /* 3863 * Allocate the KVA mapping for an existing buffer. 3864 * If an unmapped buffer is provided but a mapped buffer is requested, take 3865 * also care to properly setup mappings between pages and KVA. 3866 */ 3867 static void 3868 bp_unmapped_get_kva(struct buf *bp, daddr_t blkno, int size, int gbflags) 3869 { 3870 int bsize, maxsize, need_mapping, need_kva; 3871 off_t offset; 3872 3873 need_mapping = bp->b_data == unmapped_buf && 3874 (gbflags & GB_UNMAPPED) == 0; 3875 need_kva = bp->b_kvabase == unmapped_buf && 3876 bp->b_data == unmapped_buf && 3877 (gbflags & GB_KVAALLOC) != 0; 3878 if (!need_mapping && !need_kva) 3879 return; 3880 3881 BUF_CHECK_UNMAPPED(bp); 3882 3883 if (need_mapping && bp->b_kvabase != unmapped_buf) { 3884 /* 3885 * Buffer is not mapped, but the KVA was already 3886 * reserved at the time of the instantiation. Use the 3887 * allocated space. 3888 */ 3889 goto has_addr; 3890 } 3891 3892 /* 3893 * Calculate the amount of the address space we would reserve 3894 * if the buffer was mapped. 3895 */ 3896 bsize = vn_isdisk(bp->b_vp) ? DEV_BSIZE : bp->b_bufobj->bo_bsize; 3897 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize")); 3898 offset = blkno * bsize; 3899 maxsize = size + (offset & PAGE_MASK); 3900 maxsize = imax(maxsize, bsize); 3901 3902 while (bufkva_alloc(bp, maxsize, gbflags) != 0) { 3903 if ((gbflags & GB_NOWAIT_BD) != 0) { 3904 /* 3905 * XXXKIB: defragmentation cannot 3906 * succeed, not sure what else to do. 3907 */ 3908 panic("GB_NOWAIT_BD and GB_UNMAPPED %p", bp); 3909 } 3910 counter_u64_add(mappingrestarts, 1); 3911 bufspace_wait(bufdomain(bp), bp->b_vp, gbflags, 0, 0); 3912 } 3913 has_addr: 3914 if (need_mapping) { 3915 /* b_offset is handled by bpmap_qenter. */ 3916 bp->b_data = bp->b_kvabase; 3917 BUF_CHECK_MAPPED(bp); 3918 bpmap_qenter(bp); 3919 } 3920 } 3921 3922 struct buf * 3923 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo, 3924 int flags) 3925 { 3926 struct buf *bp; 3927 int error; 3928 3929 error = getblkx(vp, blkno, blkno, size, slpflag, slptimeo, flags, &bp); 3930 if (error != 0) 3931 return (NULL); 3932 return (bp); 3933 } 3934 3935 /* 3936 * getblkx: 3937 * 3938 * Get a block given a specified block and offset into a file/device. 3939 * The buffers B_DONE bit will be cleared on return, making it almost 3940 * ready for an I/O initiation. B_INVAL may or may not be set on 3941 * return. The caller should clear B_INVAL prior to initiating a 3942 * READ. 3943 * 3944 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for 3945 * an existing buffer. 3946 * 3947 * For a VMIO buffer, B_CACHE is modified according to the backing VM. 3948 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set 3949 * and then cleared based on the backing VM. If the previous buffer is 3950 * non-0-sized but invalid, B_CACHE will be cleared. 3951 * 3952 * If getblk() must create a new buffer, the new buffer is returned with 3953 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which 3954 * case it is returned with B_INVAL clear and B_CACHE set based on the 3955 * backing VM. 3956 * 3957 * getblk() also forces a bwrite() for any B_DELWRI buffer whose 3958 * B_CACHE bit is clear. 3959 * 3960 * What this means, basically, is that the caller should use B_CACHE to 3961 * determine whether the buffer is fully valid or not and should clear 3962 * B_INVAL prior to issuing a read. If the caller intends to validate 3963 * the buffer by loading its data area with something, the caller needs 3964 * to clear B_INVAL. If the caller does this without issuing an I/O, 3965 * the caller should set B_CACHE ( as an optimization ), else the caller 3966 * should issue the I/O and biodone() will set B_CACHE if the I/O was 3967 * a write attempt or if it was a successful read. If the caller 3968 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR 3969 * prior to issuing the READ. biodone() will *not* clear B_INVAL. 3970 * 3971 * The blkno parameter is the logical block being requested. Normally 3972 * the mapping of logical block number to disk block address is done 3973 * by calling VOP_BMAP(). However, if the mapping is already known, the 3974 * disk block address can be passed using the dblkno parameter. If the 3975 * disk block address is not known, then the same value should be passed 3976 * for blkno and dblkno. 3977 */ 3978 int 3979 getblkx(struct vnode *vp, daddr_t blkno, daddr_t dblkno, int size, int slpflag, 3980 int slptimeo, int flags, struct buf **bpp) 3981 { 3982 struct buf *bp; 3983 struct bufobj *bo; 3984 daddr_t d_blkno; 3985 int bsize, error, maxsize, vmio; 3986 off_t offset; 3987 3988 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size); 3989 KASSERT((flags & (GB_UNMAPPED | GB_KVAALLOC)) != GB_KVAALLOC, 3990 ("GB_KVAALLOC only makes sense with GB_UNMAPPED")); 3991 if (vp->v_type != VCHR) 3992 ASSERT_VOP_LOCKED(vp, "getblk"); 3993 if (size > maxbcachebuf) { 3994 printf("getblkx: size(%d) > maxbcachebuf(%d)\n", size, 3995 maxbcachebuf); 3996 return (EIO); 3997 } 3998 if (!unmapped_buf_allowed) 3999 flags &= ~(GB_UNMAPPED | GB_KVAALLOC); 4000 4001 bo = &vp->v_bufobj; 4002 d_blkno = dblkno; 4003 4004 /* Attempt lockless lookup first. */ 4005 bp = gbincore_unlocked(bo, blkno); 4006 if (bp == NULL) { 4007 /* 4008 * With GB_NOCREAT we must be sure about not finding the buffer 4009 * as it may have been reassigned during unlocked lookup. 4010 * If BO_NONSTERILE is still unset, no reassign has occurred. 4011 */ 4012 if ((flags & GB_NOCREAT) != 0) { 4013 /* Ensure bo_flag is loaded after gbincore_unlocked. */ 4014 atomic_thread_fence_acq(); 4015 if ((bo->bo_flag & BO_NONSTERILE) == 0) 4016 return (EEXIST); 4017 goto loop; 4018 } 4019 goto newbuf_unlocked; 4020 } 4021 4022 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL, "getblku", 0, 4023 0); 4024 if (error != 0) { 4025 KASSERT(error == EBUSY, 4026 ("getblk: unexpected error %d from buf try-lock", error)); 4027 /* 4028 * We failed a buf try-lock. 4029 * 4030 * With GB_LOCK_NOWAIT, just return, rather than taking the 4031 * bufobj interlock and trying again, since we would probably 4032 * fail again anyway. This is okay even if the buf's identity 4033 * changed and we contended on the wrong lock, as changing 4034 * identity itself requires the buf lock, and we could have 4035 * contended on the right lock. 4036 */ 4037 if ((flags & GB_LOCK_NOWAIT) != 0) 4038 return (error); 4039 goto loop; 4040 } 4041 4042 /* Verify buf identify has not changed since lookup. */ 4043 if (bp->b_bufobj == bo && bp->b_lblkno == blkno) 4044 goto foundbuf_fastpath; 4045 4046 /* It changed, fallback to locked lookup. */ 4047 BUF_UNLOCK_RAW(bp); 4048 4049 /* As above, with GB_LOCK_NOWAIT, just return. */ 4050 if ((flags & GB_LOCK_NOWAIT) != 0) 4051 return (EBUSY); 4052 4053 loop: 4054 BO_RLOCK(bo); 4055 bp = gbincore(bo, blkno); 4056 if (bp != NULL) { 4057 int lockflags; 4058 4059 /* 4060 * Buffer is in-core. If the buffer is not busy nor managed, 4061 * it must be on a queue. 4062 */ 4063 lockflags = LK_EXCLUSIVE | LK_INTERLOCK | 4064 ((flags & GB_LOCK_NOWAIT) != 0 ? LK_NOWAIT : LK_SLEEPFAIL); 4065 #ifdef WITNESS 4066 lockflags |= (flags & GB_NOWITNESS) != 0 ? LK_NOWITNESS : 0; 4067 #endif 4068 4069 error = BUF_TIMELOCK(bp, lockflags, 4070 BO_LOCKPTR(bo), "getblk", slpflag, slptimeo); 4071 4072 /* 4073 * If we slept and got the lock we have to restart in case 4074 * the buffer changed identities. 4075 */ 4076 if (error == ENOLCK) 4077 goto loop; 4078 /* We timed out or were interrupted. */ 4079 else if (error != 0) 4080 return (error); 4081 4082 foundbuf_fastpath: 4083 /* If recursed, assume caller knows the rules. */ 4084 if (BUF_LOCKRECURSED(bp)) 4085 goto end; 4086 4087 /* 4088 * The buffer is locked. B_CACHE is cleared if the buffer is 4089 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set 4090 * and for a VMIO buffer B_CACHE is adjusted according to the 4091 * backing VM cache. 4092 */ 4093 if (bp->b_flags & B_INVAL) 4094 bp->b_flags &= ~B_CACHE; 4095 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0) 4096 bp->b_flags |= B_CACHE; 4097 if (bp->b_flags & B_MANAGED) 4098 MPASS(bp->b_qindex == QUEUE_NONE); 4099 else 4100 bremfree(bp); 4101 4102 /* 4103 * check for size inconsistencies for non-VMIO case. 4104 */ 4105 if (bp->b_bcount != size) { 4106 if ((bp->b_flags & B_VMIO) == 0 || 4107 (size > bp->b_kvasize)) { 4108 if (bp->b_flags & B_DELWRI) { 4109 bp->b_flags |= B_NOCACHE; 4110 bwrite(bp); 4111 } else { 4112 if (LIST_EMPTY(&bp->b_dep)) { 4113 bp->b_flags |= B_RELBUF; 4114 brelse(bp); 4115 } else { 4116 bp->b_flags |= B_NOCACHE; 4117 bwrite(bp); 4118 } 4119 } 4120 goto loop; 4121 } 4122 } 4123 4124 /* 4125 * Handle the case of unmapped buffer which should 4126 * become mapped, or the buffer for which KVA 4127 * reservation is requested. 4128 */ 4129 bp_unmapped_get_kva(bp, blkno, size, flags); 4130 4131 /* 4132 * If the size is inconsistent in the VMIO case, we can resize 4133 * the buffer. This might lead to B_CACHE getting set or 4134 * cleared. If the size has not changed, B_CACHE remains 4135 * unchanged from its previous state. 4136 */ 4137 allocbuf(bp, size); 4138 4139 KASSERT(bp->b_offset != NOOFFSET, 4140 ("getblk: no buffer offset")); 4141 4142 /* 4143 * A buffer with B_DELWRI set and B_CACHE clear must 4144 * be committed before we can return the buffer in 4145 * order to prevent the caller from issuing a read 4146 * ( due to B_CACHE not being set ) and overwriting 4147 * it. 4148 * 4149 * Most callers, including NFS and FFS, need this to 4150 * operate properly either because they assume they 4151 * can issue a read if B_CACHE is not set, or because 4152 * ( for example ) an uncached B_DELWRI might loop due 4153 * to softupdates re-dirtying the buffer. In the latter 4154 * case, B_CACHE is set after the first write completes, 4155 * preventing further loops. 4156 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE 4157 * above while extending the buffer, we cannot allow the 4158 * buffer to remain with B_CACHE set after the write 4159 * completes or it will represent a corrupt state. To 4160 * deal with this we set B_NOCACHE to scrap the buffer 4161 * after the write. 4162 * 4163 * We might be able to do something fancy, like setting 4164 * B_CACHE in bwrite() except if B_DELWRI is already set, 4165 * so the below call doesn't set B_CACHE, but that gets real 4166 * confusing. This is much easier. 4167 */ 4168 4169 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) { 4170 bp->b_flags |= B_NOCACHE; 4171 bwrite(bp); 4172 goto loop; 4173 } 4174 bp->b_flags &= ~B_DONE; 4175 } else { 4176 /* 4177 * Buffer is not in-core, create new buffer. The buffer 4178 * returned by getnewbuf() is locked. Note that the returned 4179 * buffer is also considered valid (not marked B_INVAL). 4180 */ 4181 BO_RUNLOCK(bo); 4182 newbuf_unlocked: 4183 /* 4184 * If the user does not want us to create the buffer, bail out 4185 * here. 4186 */ 4187 if (flags & GB_NOCREAT) 4188 return (EEXIST); 4189 4190 bsize = vn_isdisk(vp) ? DEV_BSIZE : bo->bo_bsize; 4191 KASSERT(bsize != 0, ("bsize == 0, check bo->bo_bsize")); 4192 offset = blkno * bsize; 4193 vmio = vp->v_object != NULL; 4194 if (vmio) { 4195 maxsize = size + (offset & PAGE_MASK); 4196 if (maxsize > maxbcachebuf) { 4197 printf( 4198 "getblkx: maxsize(%d) > maxbcachebuf(%d)\n", 4199 maxsize, maxbcachebuf); 4200 return (EIO); 4201 } 4202 } else { 4203 maxsize = size; 4204 /* Do not allow non-VMIO notmapped buffers. */ 4205 flags &= ~(GB_UNMAPPED | GB_KVAALLOC); 4206 } 4207 maxsize = imax(maxsize, bsize); 4208 if ((flags & GB_NOSPARSE) != 0 && vmio && 4209 !vn_isdisk(vp)) { 4210 error = VOP_BMAP(vp, blkno, NULL, &d_blkno, 0, 0); 4211 KASSERT(error != EOPNOTSUPP, 4212 ("GB_NOSPARSE from fs not supporting bmap, vp %p", 4213 vp)); 4214 if (error != 0) 4215 return (error); 4216 if (d_blkno == -1) 4217 return (EJUSTRETURN); 4218 } 4219 4220 bp = getnewbuf(vp, slpflag, slptimeo, maxsize, flags); 4221 if (bp == NULL) { 4222 if (slpflag || slptimeo) 4223 return (ETIMEDOUT); 4224 /* 4225 * XXX This is here until the sleep path is diagnosed 4226 * enough to work under very low memory conditions. 4227 * 4228 * There's an issue on low memory, 4BSD+non-preempt 4229 * systems (eg MIPS routers with 32MB RAM) where buffer 4230 * exhaustion occurs without sleeping for buffer 4231 * reclaimation. This just sticks in a loop and 4232 * constantly attempts to allocate a buffer, which 4233 * hits exhaustion and tries to wakeup bufdaemon. 4234 * This never happens because we never yield. 4235 * 4236 * The real solution is to identify and fix these cases 4237 * so we aren't effectively busy-waiting in a loop 4238 * until the reclaimation path has cycles to run. 4239 */ 4240 kern_yield(PRI_USER); 4241 goto loop; 4242 } 4243 4244 /* 4245 * 4246 * Insert the buffer into the hash, so that it can 4247 * be found by incore. 4248 * 4249 * We don't hold the bufobj interlock while allocating the new 4250 * buffer. Consequently, we can race on buffer creation. This 4251 * can be a problem whether the vnode is locked or not. If the 4252 * buffer is created out from under us, we have to throw away 4253 * the one we just created. 4254 */ 4255 bp->b_lblkno = blkno; 4256 bp->b_blkno = d_blkno; 4257 bp->b_offset = offset; 4258 error = bgetvp(vp, bp); 4259 if (error != 0) { 4260 KASSERT(error == EEXIST, 4261 ("getblk: unexpected error %d from bgetvp", 4262 error)); 4263 bp->b_flags |= B_INVAL; 4264 bufspace_release(bufdomain(bp), maxsize); 4265 brelse(bp); 4266 goto loop; 4267 } 4268 4269 /* 4270 * set B_VMIO bit. allocbuf() the buffer bigger. Since the 4271 * buffer size starts out as 0, B_CACHE will be set by 4272 * allocbuf() for the VMIO case prior to it testing the 4273 * backing store for validity. 4274 */ 4275 4276 if (vmio) { 4277 bp->b_flags |= B_VMIO; 4278 KASSERT(vp->v_object == bp->b_bufobj->bo_object, 4279 ("ARGH! different b_bufobj->bo_object %p %p %p\n", 4280 bp, vp->v_object, bp->b_bufobj->bo_object)); 4281 } else { 4282 bp->b_flags &= ~B_VMIO; 4283 KASSERT(bp->b_bufobj->bo_object == NULL, 4284 ("ARGH! has b_bufobj->bo_object %p %p\n", 4285 bp, bp->b_bufobj->bo_object)); 4286 BUF_CHECK_MAPPED(bp); 4287 } 4288 4289 allocbuf(bp, size); 4290 bufspace_release(bufdomain(bp), maxsize); 4291 bp->b_flags &= ~B_DONE; 4292 } 4293 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp); 4294 end: 4295 buf_track(bp, __func__); 4296 KASSERT(bp->b_bufobj == bo, 4297 ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo)); 4298 *bpp = bp; 4299 return (0); 4300 } 4301 4302 /* 4303 * Get an empty, disassociated buffer of given size. The buffer is initially 4304 * set to B_INVAL. 4305 */ 4306 struct buf * 4307 geteblk(int size, int flags) 4308 { 4309 struct buf *bp; 4310 int maxsize; 4311 4312 maxsize = (size + BKVAMASK) & ~BKVAMASK; 4313 while ((bp = getnewbuf(NULL, 0, 0, maxsize, flags)) == NULL) { 4314 if ((flags & GB_NOWAIT_BD) && 4315 (curthread->td_pflags & TDP_BUFNEED) != 0) 4316 return (NULL); 4317 } 4318 allocbuf(bp, size); 4319 bufspace_release(bufdomain(bp), maxsize); 4320 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */ 4321 return (bp); 4322 } 4323 4324 /* 4325 * Truncate the backing store for a non-vmio buffer. 4326 */ 4327 static void 4328 vfs_nonvmio_truncate(struct buf *bp, int newbsize) 4329 { 4330 4331 if (bp->b_flags & B_MALLOC) { 4332 /* 4333 * malloced buffers are not shrunk 4334 */ 4335 if (newbsize == 0) { 4336 bufmallocadjust(bp, 0); 4337 free(bp->b_data, M_BIOBUF); 4338 bp->b_data = bp->b_kvabase; 4339 bp->b_flags &= ~B_MALLOC; 4340 } 4341 return; 4342 } 4343 vm_hold_free_pages(bp, newbsize); 4344 bufspace_adjust(bp, newbsize); 4345 } 4346 4347 /* 4348 * Extend the backing for a non-VMIO buffer. 4349 */ 4350 static void 4351 vfs_nonvmio_extend(struct buf *bp, int newbsize) 4352 { 4353 caddr_t origbuf; 4354 int origbufsize; 4355 4356 /* 4357 * We only use malloced memory on the first allocation. 4358 * and revert to page-allocated memory when the buffer 4359 * grows. 4360 * 4361 * There is a potential smp race here that could lead 4362 * to bufmallocspace slightly passing the max. It 4363 * is probably extremely rare and not worth worrying 4364 * over. 4365 */ 4366 if (bp->b_bufsize == 0 && newbsize <= PAGE_SIZE/2 && 4367 bufmallocspace < maxbufmallocspace) { 4368 bp->b_data = malloc(newbsize, M_BIOBUF, M_WAITOK); 4369 bp->b_flags |= B_MALLOC; 4370 bufmallocadjust(bp, newbsize); 4371 return; 4372 } 4373 4374 /* 4375 * If the buffer is growing on its other-than-first 4376 * allocation then we revert to the page-allocation 4377 * scheme. 4378 */ 4379 origbuf = NULL; 4380 origbufsize = 0; 4381 if (bp->b_flags & B_MALLOC) { 4382 origbuf = bp->b_data; 4383 origbufsize = bp->b_bufsize; 4384 bp->b_data = bp->b_kvabase; 4385 bufmallocadjust(bp, 0); 4386 bp->b_flags &= ~B_MALLOC; 4387 newbsize = round_page(newbsize); 4388 } 4389 vm_hold_load_pages(bp, (vm_offset_t) bp->b_data + bp->b_bufsize, 4390 (vm_offset_t) bp->b_data + newbsize); 4391 if (origbuf != NULL) { 4392 bcopy(origbuf, bp->b_data, origbufsize); 4393 free(origbuf, M_BIOBUF); 4394 } 4395 bufspace_adjust(bp, newbsize); 4396 } 4397 4398 /* 4399 * This code constitutes the buffer memory from either anonymous system 4400 * memory (in the case of non-VMIO operations) or from an associated 4401 * VM object (in the case of VMIO operations). This code is able to 4402 * resize a buffer up or down. 4403 * 4404 * Note that this code is tricky, and has many complications to resolve 4405 * deadlock or inconsistent data situations. Tread lightly!!! 4406 * There are B_CACHE and B_DELWRI interactions that must be dealt with by 4407 * the caller. Calling this code willy nilly can result in the loss of data. 4408 * 4409 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with 4410 * B_CACHE for the non-VMIO case. 4411 */ 4412 int 4413 allocbuf(struct buf *bp, int size) 4414 { 4415 int newbsize; 4416 4417 if (bp->b_bcount == size) 4418 return (1); 4419 4420 KASSERT(bp->b_kvasize == 0 || bp->b_kvasize >= size, 4421 ("allocbuf: buffer too small %p %#x %#x", 4422 bp, bp->b_kvasize, size)); 4423 4424 newbsize = roundup2(size, DEV_BSIZE); 4425 if ((bp->b_flags & B_VMIO) == 0) { 4426 if ((bp->b_flags & B_MALLOC) == 0) 4427 newbsize = round_page(newbsize); 4428 /* 4429 * Just get anonymous memory from the kernel. Don't 4430 * mess with B_CACHE. 4431 */ 4432 if (newbsize < bp->b_bufsize) 4433 vfs_nonvmio_truncate(bp, newbsize); 4434 else if (newbsize > bp->b_bufsize) 4435 vfs_nonvmio_extend(bp, newbsize); 4436 } else { 4437 int desiredpages; 4438 4439 desiredpages = size == 0 ? 0 : 4440 num_pages((bp->b_offset & PAGE_MASK) + newbsize); 4441 4442 KASSERT((bp->b_flags & B_MALLOC) == 0, 4443 ("allocbuf: VMIO buffer can't be malloced %p", bp)); 4444 4445 /* 4446 * Set B_CACHE initially if buffer is 0 length or will become 4447 * 0-length. 4448 */ 4449 if (size == 0 || bp->b_bufsize == 0) 4450 bp->b_flags |= B_CACHE; 4451 4452 if (newbsize < bp->b_bufsize) 4453 vfs_vmio_truncate(bp, desiredpages); 4454 /* XXX This looks as if it should be newbsize > b_bufsize */ 4455 else if (size > bp->b_bcount) 4456 vfs_vmio_extend(bp, desiredpages, size); 4457 bufspace_adjust(bp, newbsize); 4458 } 4459 bp->b_bcount = size; /* requested buffer size. */ 4460 return (1); 4461 } 4462 4463 extern int inflight_transient_maps; 4464 4465 static struct bio_queue nondump_bios; 4466 4467 void 4468 biodone(struct bio *bp) 4469 { 4470 struct mtx *mtxp; 4471 void (*done)(struct bio *); 4472 vm_offset_t start, end; 4473 4474 biotrack(bp, __func__); 4475 4476 /* 4477 * Avoid completing I/O when dumping after a panic since that may 4478 * result in a deadlock in the filesystem or pager code. Note that 4479 * this doesn't affect dumps that were started manually since we aim 4480 * to keep the system usable after it has been resumed. 4481 */ 4482 if (__predict_false(dumping && SCHEDULER_STOPPED())) { 4483 TAILQ_INSERT_HEAD(&nondump_bios, bp, bio_queue); 4484 return; 4485 } 4486 if ((bp->bio_flags & BIO_TRANSIENT_MAPPING) != 0) { 4487 bp->bio_flags &= ~BIO_TRANSIENT_MAPPING; 4488 bp->bio_flags |= BIO_UNMAPPED; 4489 start = trunc_page((vm_offset_t)bp->bio_data); 4490 end = round_page((vm_offset_t)bp->bio_data + bp->bio_length); 4491 bp->bio_data = unmapped_buf; 4492 pmap_qremove(start, atop(end - start)); 4493 vmem_free(transient_arena, start, end - start); 4494 atomic_add_int(&inflight_transient_maps, -1); 4495 } 4496 done = bp->bio_done; 4497 /* 4498 * The check for done == biodone is to allow biodone to be 4499 * used as a bio_done routine. 4500 */ 4501 if (done == NULL || done == biodone) { 4502 mtxp = mtx_pool_find(mtxpool_sleep, bp); 4503 mtx_lock(mtxp); 4504 bp->bio_flags |= BIO_DONE; 4505 wakeup(bp); 4506 mtx_unlock(mtxp); 4507 } else 4508 done(bp); 4509 } 4510 4511 /* 4512 * Wait for a BIO to finish. 4513 */ 4514 int 4515 biowait(struct bio *bp, const char *wmesg) 4516 { 4517 struct mtx *mtxp; 4518 4519 mtxp = mtx_pool_find(mtxpool_sleep, bp); 4520 mtx_lock(mtxp); 4521 while ((bp->bio_flags & BIO_DONE) == 0) 4522 msleep(bp, mtxp, PRIBIO, wmesg, 0); 4523 mtx_unlock(mtxp); 4524 if (bp->bio_error != 0) 4525 return (bp->bio_error); 4526 if (!(bp->bio_flags & BIO_ERROR)) 4527 return (0); 4528 return (EIO); 4529 } 4530 4531 void 4532 biofinish(struct bio *bp, struct devstat *stat, int error) 4533 { 4534 4535 if (error) { 4536 bp->bio_error = error; 4537 bp->bio_flags |= BIO_ERROR; 4538 } 4539 if (stat != NULL) 4540 devstat_end_transaction_bio(stat, bp); 4541 biodone(bp); 4542 } 4543 4544 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING) 4545 void 4546 biotrack_buf(struct bio *bp, const char *location) 4547 { 4548 4549 buf_track(bp->bio_track_bp, location); 4550 } 4551 #endif 4552 4553 /* 4554 * bufwait: 4555 * 4556 * Wait for buffer I/O completion, returning error status. The buffer 4557 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR 4558 * error and cleared. 4559 */ 4560 int 4561 bufwait(struct buf *bp) 4562 { 4563 if (bp->b_iocmd == BIO_READ) 4564 bwait(bp, PRIBIO, "biord"); 4565 else 4566 bwait(bp, PRIBIO, "biowr"); 4567 if (bp->b_flags & B_EINTR) { 4568 bp->b_flags &= ~B_EINTR; 4569 return (EINTR); 4570 } 4571 if (bp->b_ioflags & BIO_ERROR) { 4572 return (bp->b_error ? bp->b_error : EIO); 4573 } else { 4574 return (0); 4575 } 4576 } 4577 4578 /* 4579 * bufdone: 4580 * 4581 * Finish I/O on a buffer, optionally calling a completion function. 4582 * This is usually called from an interrupt so process blocking is 4583 * not allowed. 4584 * 4585 * biodone is also responsible for setting B_CACHE in a B_VMIO bp. 4586 * In a non-VMIO bp, B_CACHE will be set on the next getblk() 4587 * assuming B_INVAL is clear. 4588 * 4589 * For the VMIO case, we set B_CACHE if the op was a read and no 4590 * read error occurred, or if the op was a write. B_CACHE is never 4591 * set if the buffer is invalid or otherwise uncacheable. 4592 * 4593 * bufdone does not mess with B_INVAL, allowing the I/O routine or the 4594 * initiator to leave B_INVAL set to brelse the buffer out of existence 4595 * in the biodone routine. 4596 */ 4597 void 4598 bufdone(struct buf *bp) 4599 { 4600 struct bufobj *dropobj; 4601 void (*biodone)(struct buf *); 4602 4603 buf_track(bp, __func__); 4604 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 4605 dropobj = NULL; 4606 4607 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp)); 4608 4609 runningbufwakeup(bp); 4610 if (bp->b_iocmd == BIO_WRITE) 4611 dropobj = bp->b_bufobj; 4612 /* call optional completion function if requested */ 4613 if (bp->b_iodone != NULL) { 4614 biodone = bp->b_iodone; 4615 bp->b_iodone = NULL; 4616 (*biodone) (bp); 4617 if (dropobj) 4618 bufobj_wdrop(dropobj); 4619 return; 4620 } 4621 if (bp->b_flags & B_VMIO) { 4622 /* 4623 * Set B_CACHE if the op was a normal read and no error 4624 * occurred. B_CACHE is set for writes in the b*write() 4625 * routines. 4626 */ 4627 if (bp->b_iocmd == BIO_READ && 4628 !(bp->b_flags & (B_INVAL|B_NOCACHE)) && 4629 !(bp->b_ioflags & BIO_ERROR)) 4630 bp->b_flags |= B_CACHE; 4631 vfs_vmio_iodone(bp); 4632 } 4633 if (!LIST_EMPTY(&bp->b_dep)) 4634 buf_complete(bp); 4635 if ((bp->b_flags & B_CKHASH) != 0) { 4636 KASSERT(bp->b_iocmd == BIO_READ, 4637 ("bufdone: b_iocmd %d not BIO_READ", bp->b_iocmd)); 4638 KASSERT(buf_mapped(bp), ("bufdone: bp %p not mapped", bp)); 4639 (*bp->b_ckhashcalc)(bp); 4640 } 4641 /* 4642 * For asynchronous completions, release the buffer now. The brelse 4643 * will do a wakeup there if necessary - so no need to do a wakeup 4644 * here in the async case. The sync case always needs to do a wakeup. 4645 */ 4646 if (bp->b_flags & B_ASYNC) { 4647 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || 4648 (bp->b_ioflags & BIO_ERROR)) 4649 brelse(bp); 4650 else 4651 bqrelse(bp); 4652 } else 4653 bdone(bp); 4654 if (dropobj) 4655 bufobj_wdrop(dropobj); 4656 } 4657 4658 /* 4659 * This routine is called in lieu of iodone in the case of 4660 * incomplete I/O. This keeps the busy status for pages 4661 * consistent. 4662 */ 4663 void 4664 vfs_unbusy_pages(struct buf *bp) 4665 { 4666 int i; 4667 vm_object_t obj; 4668 vm_page_t m; 4669 4670 runningbufwakeup(bp); 4671 if (!(bp->b_flags & B_VMIO)) 4672 return; 4673 4674 obj = bp->b_bufobj->bo_object; 4675 for (i = 0; i < bp->b_npages; i++) { 4676 m = bp->b_pages[i]; 4677 if (m == bogus_page) { 4678 m = vm_page_relookup(obj, OFF_TO_IDX(bp->b_offset) + i); 4679 if (!m) 4680 panic("vfs_unbusy_pages: page missing\n"); 4681 bp->b_pages[i] = m; 4682 if (buf_mapped(bp)) { 4683 BUF_CHECK_MAPPED(bp); 4684 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 4685 bp->b_pages, bp->b_npages); 4686 } else 4687 BUF_CHECK_UNMAPPED(bp); 4688 } 4689 vm_page_sunbusy(m); 4690 } 4691 vm_object_pip_wakeupn(obj, bp->b_npages); 4692 } 4693 4694 /* 4695 * vfs_page_set_valid: 4696 * 4697 * Set the valid bits in a page based on the supplied offset. The 4698 * range is restricted to the buffer's size. 4699 * 4700 * This routine is typically called after a read completes. 4701 */ 4702 static void 4703 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, vm_page_t m) 4704 { 4705 vm_ooffset_t eoff; 4706 4707 /* 4708 * Compute the end offset, eoff, such that [off, eoff) does not span a 4709 * page boundary and eoff is not greater than the end of the buffer. 4710 * The end of the buffer, in this case, is our file EOF, not the 4711 * allocation size of the buffer. 4712 */ 4713 eoff = (off + PAGE_SIZE) & ~(vm_ooffset_t)PAGE_MASK; 4714 if (eoff > bp->b_offset + bp->b_bcount) 4715 eoff = bp->b_offset + bp->b_bcount; 4716 4717 /* 4718 * Set valid range. This is typically the entire buffer and thus the 4719 * entire page. 4720 */ 4721 if (eoff > off) 4722 vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off); 4723 } 4724 4725 /* 4726 * vfs_page_set_validclean: 4727 * 4728 * Set the valid bits and clear the dirty bits in a page based on the 4729 * supplied offset. The range is restricted to the buffer's size. 4730 */ 4731 static void 4732 vfs_page_set_validclean(struct buf *bp, vm_ooffset_t off, vm_page_t m) 4733 { 4734 vm_ooffset_t soff, eoff; 4735 4736 /* 4737 * Start and end offsets in buffer. eoff - soff may not cross a 4738 * page boundary or cross the end of the buffer. The end of the 4739 * buffer, in this case, is our file EOF, not the allocation size 4740 * of the buffer. 4741 */ 4742 soff = off; 4743 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK; 4744 if (eoff > bp->b_offset + bp->b_bcount) 4745 eoff = bp->b_offset + bp->b_bcount; 4746 4747 /* 4748 * Set valid range. This is typically the entire buffer and thus the 4749 * entire page. 4750 */ 4751 if (eoff > soff) { 4752 vm_page_set_validclean( 4753 m, 4754 (vm_offset_t) (soff & PAGE_MASK), 4755 (vm_offset_t) (eoff - soff) 4756 ); 4757 } 4758 } 4759 4760 /* 4761 * Acquire a shared busy on all pages in the buf. 4762 */ 4763 void 4764 vfs_busy_pages_acquire(struct buf *bp) 4765 { 4766 int i; 4767 4768 for (i = 0; i < bp->b_npages; i++) 4769 vm_page_busy_acquire(bp->b_pages[i], VM_ALLOC_SBUSY); 4770 } 4771 4772 void 4773 vfs_busy_pages_release(struct buf *bp) 4774 { 4775 int i; 4776 4777 for (i = 0; i < bp->b_npages; i++) 4778 vm_page_sunbusy(bp->b_pages[i]); 4779 } 4780 4781 /* 4782 * This routine is called before a device strategy routine. 4783 * It is used to tell the VM system that paging I/O is in 4784 * progress, and treat the pages associated with the buffer 4785 * almost as being exclusive busy. Also the object paging_in_progress 4786 * flag is handled to make sure that the object doesn't become 4787 * inconsistent. 4788 * 4789 * Since I/O has not been initiated yet, certain buffer flags 4790 * such as BIO_ERROR or B_INVAL may be in an inconsistent state 4791 * and should be ignored. 4792 */ 4793 void 4794 vfs_busy_pages(struct buf *bp, int clear_modify) 4795 { 4796 vm_object_t obj; 4797 vm_ooffset_t foff; 4798 vm_page_t m; 4799 int i; 4800 bool bogus; 4801 4802 if (!(bp->b_flags & B_VMIO)) 4803 return; 4804 4805 obj = bp->b_bufobj->bo_object; 4806 foff = bp->b_offset; 4807 KASSERT(bp->b_offset != NOOFFSET, 4808 ("vfs_busy_pages: no buffer offset")); 4809 if ((bp->b_flags & B_CLUSTER) == 0) { 4810 vm_object_pip_add(obj, bp->b_npages); 4811 vfs_busy_pages_acquire(bp); 4812 } 4813 if (bp->b_bufsize != 0) 4814 vfs_setdirty_range(bp); 4815 bogus = false; 4816 for (i = 0; i < bp->b_npages; i++) { 4817 m = bp->b_pages[i]; 4818 vm_page_assert_sbusied(m); 4819 4820 /* 4821 * When readying a buffer for a read ( i.e 4822 * clear_modify == 0 ), it is important to do 4823 * bogus_page replacement for valid pages in 4824 * partially instantiated buffers. Partially 4825 * instantiated buffers can, in turn, occur when 4826 * reconstituting a buffer from its VM backing store 4827 * base. We only have to do this if B_CACHE is 4828 * clear ( which causes the I/O to occur in the 4829 * first place ). The replacement prevents the read 4830 * I/O from overwriting potentially dirty VM-backed 4831 * pages. XXX bogus page replacement is, uh, bogus. 4832 * It may not work properly with small-block devices. 4833 * We need to find a better way. 4834 */ 4835 if (clear_modify) { 4836 pmap_remove_write(m); 4837 vfs_page_set_validclean(bp, foff, m); 4838 } else if (vm_page_all_valid(m) && 4839 (bp->b_flags & B_CACHE) == 0) { 4840 bp->b_pages[i] = bogus_page; 4841 bogus = true; 4842 } 4843 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 4844 } 4845 if (bogus && buf_mapped(bp)) { 4846 BUF_CHECK_MAPPED(bp); 4847 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 4848 bp->b_pages, bp->b_npages); 4849 } 4850 } 4851 4852 /* 4853 * vfs_bio_set_valid: 4854 * 4855 * Set the range within the buffer to valid. The range is 4856 * relative to the beginning of the buffer, b_offset. Note that 4857 * b_offset itself may be offset from the beginning of the first 4858 * page. 4859 */ 4860 void 4861 vfs_bio_set_valid(struct buf *bp, int base, int size) 4862 { 4863 int i, n; 4864 vm_page_t m; 4865 4866 if (!(bp->b_flags & B_VMIO)) 4867 return; 4868 4869 /* 4870 * Fixup base to be relative to beginning of first page. 4871 * Set initial n to be the maximum number of bytes in the 4872 * first page that can be validated. 4873 */ 4874 base += (bp->b_offset & PAGE_MASK); 4875 n = PAGE_SIZE - (base & PAGE_MASK); 4876 4877 /* 4878 * Busy may not be strictly necessary here because the pages are 4879 * unlikely to be fully valid and the vnode lock will synchronize 4880 * their access via getpages. It is grabbed for consistency with 4881 * other page validation. 4882 */ 4883 vfs_busy_pages_acquire(bp); 4884 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) { 4885 m = bp->b_pages[i]; 4886 if (n > size) 4887 n = size; 4888 vm_page_set_valid_range(m, base & PAGE_MASK, n); 4889 base += n; 4890 size -= n; 4891 n = PAGE_SIZE; 4892 } 4893 vfs_busy_pages_release(bp); 4894 } 4895 4896 /* 4897 * vfs_bio_clrbuf: 4898 * 4899 * If the specified buffer is a non-VMIO buffer, clear the entire 4900 * buffer. If the specified buffer is a VMIO buffer, clear and 4901 * validate only the previously invalid portions of the buffer. 4902 * This routine essentially fakes an I/O, so we need to clear 4903 * BIO_ERROR and B_INVAL. 4904 * 4905 * Note that while we only theoretically need to clear through b_bcount, 4906 * we go ahead and clear through b_bufsize. 4907 */ 4908 void 4909 vfs_bio_clrbuf(struct buf *bp) 4910 { 4911 int i, j, sa, ea, slide, zbits; 4912 vm_page_bits_t mask; 4913 4914 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) { 4915 clrbuf(bp); 4916 return; 4917 } 4918 bp->b_flags &= ~B_INVAL; 4919 bp->b_ioflags &= ~BIO_ERROR; 4920 vfs_busy_pages_acquire(bp); 4921 sa = bp->b_offset & PAGE_MASK; 4922 slide = 0; 4923 for (i = 0; i < bp->b_npages; i++, sa = 0) { 4924 slide = imin(slide + PAGE_SIZE, bp->b_offset + bp->b_bufsize); 4925 ea = slide & PAGE_MASK; 4926 if (ea == 0) 4927 ea = PAGE_SIZE; 4928 if (bp->b_pages[i] == bogus_page) 4929 continue; 4930 j = sa / DEV_BSIZE; 4931 zbits = (sizeof(vm_page_bits_t) * NBBY) - 4932 (ea - sa) / DEV_BSIZE; 4933 mask = (VM_PAGE_BITS_ALL >> zbits) << j; 4934 if ((bp->b_pages[i]->valid & mask) == mask) 4935 continue; 4936 if ((bp->b_pages[i]->valid & mask) == 0) 4937 pmap_zero_page_area(bp->b_pages[i], sa, ea - sa); 4938 else { 4939 for (; sa < ea; sa += DEV_BSIZE, j++) { 4940 if ((bp->b_pages[i]->valid & (1 << j)) == 0) { 4941 pmap_zero_page_area(bp->b_pages[i], 4942 sa, DEV_BSIZE); 4943 } 4944 } 4945 } 4946 vm_page_set_valid_range(bp->b_pages[i], j * DEV_BSIZE, 4947 roundup2(ea - sa, DEV_BSIZE)); 4948 } 4949 vfs_busy_pages_release(bp); 4950 bp->b_resid = 0; 4951 } 4952 4953 void 4954 vfs_bio_bzero_buf(struct buf *bp, int base, int size) 4955 { 4956 vm_page_t m; 4957 int i, n; 4958 4959 if (buf_mapped(bp)) { 4960 BUF_CHECK_MAPPED(bp); 4961 bzero(bp->b_data + base, size); 4962 } else { 4963 BUF_CHECK_UNMAPPED(bp); 4964 n = PAGE_SIZE - (base & PAGE_MASK); 4965 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) { 4966 m = bp->b_pages[i]; 4967 if (n > size) 4968 n = size; 4969 pmap_zero_page_area(m, base & PAGE_MASK, n); 4970 base += n; 4971 size -= n; 4972 n = PAGE_SIZE; 4973 } 4974 } 4975 } 4976 4977 /* 4978 * Update buffer flags based on I/O request parameters, optionally releasing the 4979 * buffer. If it's VMIO or direct I/O, the buffer pages are released to the VM, 4980 * where they may be placed on a page queue (VMIO) or freed immediately (direct 4981 * I/O). Otherwise the buffer is released to the cache. 4982 */ 4983 static void 4984 b_io_dismiss(struct buf *bp, int ioflag, bool release) 4985 { 4986 4987 KASSERT((ioflag & IO_NOREUSE) == 0 || (ioflag & IO_VMIO) != 0, 4988 ("buf %p non-VMIO noreuse", bp)); 4989 4990 if ((ioflag & IO_DIRECT) != 0) 4991 bp->b_flags |= B_DIRECT; 4992 if ((ioflag & IO_EXT) != 0) 4993 bp->b_xflags |= BX_ALTDATA; 4994 if ((ioflag & (IO_VMIO | IO_DIRECT)) != 0 && LIST_EMPTY(&bp->b_dep)) { 4995 bp->b_flags |= B_RELBUF; 4996 if ((ioflag & IO_NOREUSE) != 0) 4997 bp->b_flags |= B_NOREUSE; 4998 if (release) 4999 brelse(bp); 5000 } else if (release) 5001 bqrelse(bp); 5002 } 5003 5004 void 5005 vfs_bio_brelse(struct buf *bp, int ioflag) 5006 { 5007 5008 b_io_dismiss(bp, ioflag, true); 5009 } 5010 5011 void 5012 vfs_bio_set_flags(struct buf *bp, int ioflag) 5013 { 5014 5015 b_io_dismiss(bp, ioflag, false); 5016 } 5017 5018 /* 5019 * vm_hold_load_pages and vm_hold_free_pages get pages into 5020 * a buffers address space. The pages are anonymous and are 5021 * not associated with a file object. 5022 */ 5023 static void 5024 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to) 5025 { 5026 vm_offset_t pg; 5027 vm_page_t p; 5028 int index; 5029 5030 BUF_CHECK_MAPPED(bp); 5031 5032 to = round_page(to); 5033 from = round_page(from); 5034 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT; 5035 MPASS((bp->b_flags & B_MAXPHYS) == 0); 5036 KASSERT(to - from <= maxbcachebuf, 5037 ("vm_hold_load_pages too large %p %#jx %#jx %u", 5038 bp, (uintmax_t)from, (uintmax_t)to, maxbcachebuf)); 5039 5040 for (pg = from; pg < to; pg += PAGE_SIZE, index++) { 5041 /* 5042 * note: must allocate system pages since blocking here 5043 * could interfere with paging I/O, no matter which 5044 * process we are. 5045 */ 5046 p = vm_page_alloc_noobj(VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | 5047 VM_ALLOC_COUNT((to - pg) >> PAGE_SHIFT) | VM_ALLOC_WAITOK); 5048 pmap_qenter(pg, &p, 1); 5049 bp->b_pages[index] = p; 5050 } 5051 bp->b_npages = index; 5052 } 5053 5054 /* Return pages associated with this buf to the vm system */ 5055 static void 5056 vm_hold_free_pages(struct buf *bp, int newbsize) 5057 { 5058 vm_offset_t from; 5059 vm_page_t p; 5060 int index, newnpages; 5061 5062 BUF_CHECK_MAPPED(bp); 5063 5064 from = round_page((vm_offset_t)bp->b_data + newbsize); 5065 newnpages = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT; 5066 if (bp->b_npages > newnpages) 5067 pmap_qremove(from, bp->b_npages - newnpages); 5068 for (index = newnpages; index < bp->b_npages; index++) { 5069 p = bp->b_pages[index]; 5070 bp->b_pages[index] = NULL; 5071 vm_page_unwire_noq(p); 5072 vm_page_free(p); 5073 } 5074 bp->b_npages = newnpages; 5075 } 5076 5077 /* 5078 * Map an IO request into kernel virtual address space. 5079 * 5080 * All requests are (re)mapped into kernel VA space. 5081 * Notice that we use b_bufsize for the size of the buffer 5082 * to be mapped. b_bcount might be modified by the driver. 5083 * 5084 * Note that even if the caller determines that the address space should 5085 * be valid, a race or a smaller-file mapped into a larger space may 5086 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST 5087 * check the return value. 5088 * 5089 * This function only works with pager buffers. 5090 */ 5091 int 5092 vmapbuf(struct buf *bp, void *uaddr, size_t len, int mapbuf) 5093 { 5094 vm_prot_t prot; 5095 int pidx; 5096 5097 MPASS((bp->b_flags & B_MAXPHYS) != 0); 5098 prot = VM_PROT_READ; 5099 if (bp->b_iocmd == BIO_READ) 5100 prot |= VM_PROT_WRITE; /* Less backwards than it looks */ 5101 pidx = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map, 5102 (vm_offset_t)uaddr, len, prot, bp->b_pages, PBUF_PAGES); 5103 if (pidx < 0) 5104 return (-1); 5105 bp->b_bufsize = len; 5106 bp->b_npages = pidx; 5107 bp->b_offset = ((vm_offset_t)uaddr) & PAGE_MASK; 5108 if (mapbuf || !unmapped_buf_allowed) { 5109 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_pages, pidx); 5110 bp->b_data = bp->b_kvabase + bp->b_offset; 5111 } else 5112 bp->b_data = unmapped_buf; 5113 return (0); 5114 } 5115 5116 /* 5117 * Free the io map PTEs associated with this IO operation. 5118 * We also invalidate the TLB entries and restore the original b_addr. 5119 * 5120 * This function only works with pager buffers. 5121 */ 5122 void 5123 vunmapbuf(struct buf *bp) 5124 { 5125 int npages; 5126 5127 npages = bp->b_npages; 5128 if (buf_mapped(bp)) 5129 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages); 5130 vm_page_unhold_pages(bp->b_pages, npages); 5131 5132 bp->b_data = unmapped_buf; 5133 } 5134 5135 void 5136 bdone(struct buf *bp) 5137 { 5138 struct mtx *mtxp; 5139 5140 mtxp = mtx_pool_find(mtxpool_sleep, bp); 5141 mtx_lock(mtxp); 5142 bp->b_flags |= B_DONE; 5143 wakeup(bp); 5144 mtx_unlock(mtxp); 5145 } 5146 5147 void 5148 bwait(struct buf *bp, u_char pri, const char *wchan) 5149 { 5150 struct mtx *mtxp; 5151 5152 mtxp = mtx_pool_find(mtxpool_sleep, bp); 5153 mtx_lock(mtxp); 5154 while ((bp->b_flags & B_DONE) == 0) 5155 msleep(bp, mtxp, pri, wchan, 0); 5156 mtx_unlock(mtxp); 5157 } 5158 5159 int 5160 bufsync(struct bufobj *bo, int waitfor) 5161 { 5162 5163 return (VOP_FSYNC(bo2vnode(bo), waitfor, curthread)); 5164 } 5165 5166 void 5167 bufstrategy(struct bufobj *bo, struct buf *bp) 5168 { 5169 int i __unused; 5170 struct vnode *vp; 5171 5172 vp = bp->b_vp; 5173 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy")); 5174 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK, 5175 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp)); 5176 i = VOP_STRATEGY(vp, bp); 5177 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp)); 5178 } 5179 5180 /* 5181 * Initialize a struct bufobj before use. Memory is assumed zero filled. 5182 */ 5183 void 5184 bufobj_init(struct bufobj *bo, void *private) 5185 { 5186 static volatile int bufobj_cleanq; 5187 5188 bo->bo_domain = 5189 atomic_fetchadd_int(&bufobj_cleanq, 1) % buf_domains; 5190 rw_init(BO_LOCKPTR(bo), "bufobj interlock"); 5191 bo->bo_private = private; 5192 TAILQ_INIT(&bo->bo_clean.bv_hd); 5193 pctrie_init(&bo->bo_clean.bv_root); 5194 TAILQ_INIT(&bo->bo_dirty.bv_hd); 5195 pctrie_init(&bo->bo_dirty.bv_root); 5196 } 5197 5198 void 5199 bufobj_wrefl(struct bufobj *bo) 5200 { 5201 5202 KASSERT(bo != NULL, ("NULL bo in bufobj_wref")); 5203 ASSERT_BO_WLOCKED(bo); 5204 bo->bo_numoutput++; 5205 } 5206 5207 void 5208 bufobj_wref(struct bufobj *bo) 5209 { 5210 5211 KASSERT(bo != NULL, ("NULL bo in bufobj_wref")); 5212 BO_LOCK(bo); 5213 bo->bo_numoutput++; 5214 BO_UNLOCK(bo); 5215 } 5216 5217 void 5218 bufobj_wdrop(struct bufobj *bo) 5219 { 5220 5221 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop")); 5222 BO_LOCK(bo); 5223 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count")); 5224 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) { 5225 bo->bo_flag &= ~BO_WWAIT; 5226 wakeup(&bo->bo_numoutput); 5227 } 5228 BO_UNLOCK(bo); 5229 } 5230 5231 int 5232 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo) 5233 { 5234 int error; 5235 5236 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait")); 5237 ASSERT_BO_WLOCKED(bo); 5238 error = 0; 5239 while (bo->bo_numoutput) { 5240 bo->bo_flag |= BO_WWAIT; 5241 error = msleep(&bo->bo_numoutput, BO_LOCKPTR(bo), 5242 slpflag | (PRIBIO + 1), "bo_wwait", timeo); 5243 if (error) 5244 break; 5245 } 5246 return (error); 5247 } 5248 5249 /* 5250 * Set bio_data or bio_ma for struct bio from the struct buf. 5251 */ 5252 void 5253 bdata2bio(struct buf *bp, struct bio *bip) 5254 { 5255 5256 if (!buf_mapped(bp)) { 5257 KASSERT(unmapped_buf_allowed, ("unmapped")); 5258 bip->bio_ma = bp->b_pages; 5259 bip->bio_ma_n = bp->b_npages; 5260 bip->bio_data = unmapped_buf; 5261 bip->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK; 5262 bip->bio_flags |= BIO_UNMAPPED; 5263 KASSERT(round_page(bip->bio_ma_offset + bip->bio_length) / 5264 PAGE_SIZE == bp->b_npages, 5265 ("Buffer %p too short: %d %lld %d", bp, bip->bio_ma_offset, 5266 (long long)bip->bio_length, bip->bio_ma_n)); 5267 } else { 5268 bip->bio_data = bp->b_data; 5269 bip->bio_ma = NULL; 5270 } 5271 } 5272 5273 struct memdesc 5274 memdesc_bio(struct bio *bio) 5275 { 5276 if ((bio->bio_flags & BIO_VLIST) != 0) 5277 return (memdesc_vlist((struct bus_dma_segment *)bio->bio_data, 5278 bio->bio_ma_n)); 5279 5280 if ((bio->bio_flags & BIO_UNMAPPED) != 0) 5281 return (memdesc_vmpages(bio->bio_ma, bio->bio_bcount, 5282 bio->bio_ma_offset)); 5283 5284 return (memdesc_vaddr(bio->bio_data, bio->bio_bcount)); 5285 } 5286 5287 static int buf_pager_relbuf; 5288 SYSCTL_INT(_vfs, OID_AUTO, buf_pager_relbuf, CTLFLAG_RWTUN, 5289 &buf_pager_relbuf, 0, 5290 "Make buffer pager release buffers after reading"); 5291 5292 /* 5293 * The buffer pager. It uses buffer reads to validate pages. 5294 * 5295 * In contrast to the generic local pager from vm/vnode_pager.c, this 5296 * pager correctly and easily handles volumes where the underlying 5297 * device block size is greater than the machine page size. The 5298 * buffer cache transparently extends the requested page run to be 5299 * aligned at the block boundary, and does the necessary bogus page 5300 * replacements in the addends to avoid obliterating already valid 5301 * pages. 5302 * 5303 * The only non-trivial issue is that the exclusive busy state for 5304 * pages, which is assumed by the vm_pager_getpages() interface, is 5305 * incompatible with the VMIO buffer cache's desire to share-busy the 5306 * pages. This function performs a trivial downgrade of the pages' 5307 * state before reading buffers, and a less trivial upgrade from the 5308 * shared-busy to excl-busy state after the read. 5309 */ 5310 int 5311 vfs_bio_getpages(struct vnode *vp, vm_page_t *ma, int count, 5312 int *rbehind, int *rahead, vbg_get_lblkno_t get_lblkno, 5313 vbg_get_blksize_t get_blksize) 5314 { 5315 vm_page_t m; 5316 vm_object_t object; 5317 struct buf *bp; 5318 struct mount *mp; 5319 daddr_t lbn, lbnp; 5320 vm_ooffset_t la, lb, poff, poffe; 5321 long bo_bs, bsize; 5322 int br_flags, error, i, pgsin, pgsin_a, pgsin_b; 5323 bool redo, lpart; 5324 5325 object = vp->v_object; 5326 mp = vp->v_mount; 5327 error = 0; 5328 la = IDX_TO_OFF(ma[count - 1]->pindex); 5329 if (la >= object->un_pager.vnp.vnp_size) 5330 return (VM_PAGER_BAD); 5331 5332 /* 5333 * Change the meaning of la from where the last requested page starts 5334 * to where it ends, because that's the end of the requested region 5335 * and the start of the potential read-ahead region. 5336 */ 5337 la += PAGE_SIZE; 5338 lpart = la > object->un_pager.vnp.vnp_size; 5339 error = get_blksize(vp, get_lblkno(vp, IDX_TO_OFF(ma[0]->pindex)), 5340 &bo_bs); 5341 if (error != 0) 5342 return (VM_PAGER_ERROR); 5343 5344 /* 5345 * Calculate read-ahead, behind and total pages. 5346 */ 5347 pgsin = count; 5348 lb = IDX_TO_OFF(ma[0]->pindex); 5349 pgsin_b = OFF_TO_IDX(lb - rounddown2(lb, bo_bs)); 5350 pgsin += pgsin_b; 5351 if (rbehind != NULL) 5352 *rbehind = pgsin_b; 5353 pgsin_a = OFF_TO_IDX(roundup2(la, bo_bs) - la); 5354 if (la + IDX_TO_OFF(pgsin_a) >= object->un_pager.vnp.vnp_size) 5355 pgsin_a = OFF_TO_IDX(roundup2(object->un_pager.vnp.vnp_size, 5356 PAGE_SIZE) - la); 5357 pgsin += pgsin_a; 5358 if (rahead != NULL) 5359 *rahead = pgsin_a; 5360 VM_CNT_INC(v_vnodein); 5361 VM_CNT_ADD(v_vnodepgsin, pgsin); 5362 5363 br_flags = (mp != NULL && (mp->mnt_kern_flag & MNTK_UNMAPPED_BUFS) 5364 != 0) ? GB_UNMAPPED : 0; 5365 again: 5366 for (i = 0; i < count; i++) { 5367 if (ma[i] != bogus_page) 5368 vm_page_busy_downgrade(ma[i]); 5369 } 5370 5371 lbnp = -1; 5372 for (i = 0; i < count; i++) { 5373 m = ma[i]; 5374 if (m == bogus_page) 5375 continue; 5376 5377 /* 5378 * Pages are shared busy and the object lock is not 5379 * owned, which together allow for the pages' 5380 * invalidation. The racy test for validity avoids 5381 * useless creation of the buffer for the most typical 5382 * case when invalidation is not used in redo or for 5383 * parallel read. The shared->excl upgrade loop at 5384 * the end of the function catches the race in a 5385 * reliable way (protected by the object lock). 5386 */ 5387 if (vm_page_all_valid(m)) 5388 continue; 5389 5390 poff = IDX_TO_OFF(m->pindex); 5391 poffe = MIN(poff + PAGE_SIZE, object->un_pager.vnp.vnp_size); 5392 for (; poff < poffe; poff += bsize) { 5393 lbn = get_lblkno(vp, poff); 5394 if (lbn == lbnp) 5395 goto next_page; 5396 lbnp = lbn; 5397 5398 error = get_blksize(vp, lbn, &bsize); 5399 if (error == 0) 5400 error = bread_gb(vp, lbn, bsize, 5401 curthread->td_ucred, br_flags, &bp); 5402 if (error != 0) 5403 goto end_pages; 5404 if (bp->b_rcred == curthread->td_ucred) { 5405 crfree(bp->b_rcred); 5406 bp->b_rcred = NOCRED; 5407 } 5408 if (LIST_EMPTY(&bp->b_dep)) { 5409 /* 5410 * Invalidation clears m->valid, but 5411 * may leave B_CACHE flag if the 5412 * buffer existed at the invalidation 5413 * time. In this case, recycle the 5414 * buffer to do real read on next 5415 * bread() after redo. 5416 * 5417 * Otherwise B_RELBUF is not strictly 5418 * necessary, enable to reduce buf 5419 * cache pressure. 5420 */ 5421 if (buf_pager_relbuf || 5422 !vm_page_all_valid(m)) 5423 bp->b_flags |= B_RELBUF; 5424 5425 bp->b_flags &= ~B_NOCACHE; 5426 brelse(bp); 5427 } else { 5428 bqrelse(bp); 5429 } 5430 } 5431 KASSERT(1 /* racy, enable for debugging */ || 5432 vm_page_all_valid(m) || i == count - 1, 5433 ("buf %d %p invalid", i, m)); 5434 if (i == count - 1 && lpart) { 5435 if (!vm_page_none_valid(m) && 5436 !vm_page_all_valid(m)) 5437 vm_page_zero_invalid(m, TRUE); 5438 } 5439 next_page:; 5440 } 5441 end_pages: 5442 5443 redo = false; 5444 for (i = 0; i < count; i++) { 5445 if (ma[i] == bogus_page) 5446 continue; 5447 if (vm_page_busy_tryupgrade(ma[i]) == 0) { 5448 vm_page_sunbusy(ma[i]); 5449 ma[i] = vm_page_grab_unlocked(object, ma[i]->pindex, 5450 VM_ALLOC_NORMAL); 5451 } 5452 5453 /* 5454 * Since the pages were only sbusy while neither the 5455 * buffer nor the object lock was held by us, or 5456 * reallocated while vm_page_grab() slept for busy 5457 * relinguish, they could have been invalidated. 5458 * Recheck the valid bits and re-read as needed. 5459 * 5460 * Note that the last page is made fully valid in the 5461 * read loop, and partial validity for the page at 5462 * index count - 1 could mean that the page was 5463 * invalidated or removed, so we must restart for 5464 * safety as well. 5465 */ 5466 if (!vm_page_all_valid(ma[i])) 5467 redo = true; 5468 } 5469 if (redo && error == 0) 5470 goto again; 5471 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK); 5472 } 5473 5474 #include "opt_ddb.h" 5475 #ifdef DDB 5476 #include <ddb/ddb.h> 5477 5478 /* DDB command to show buffer data */ 5479 DB_SHOW_COMMAND(buffer, db_show_buffer) 5480 { 5481 /* get args */ 5482 struct buf *bp = (struct buf *)addr; 5483 #ifdef FULL_BUF_TRACKING 5484 uint32_t i, j; 5485 #endif 5486 5487 if (!have_addr) { 5488 db_printf("usage: show buffer <addr>\n"); 5489 return; 5490 } 5491 5492 db_printf("buf at %p\n", bp); 5493 db_printf("b_flags = 0x%b, b_xflags = 0x%b\n", 5494 (u_int)bp->b_flags, PRINT_BUF_FLAGS, 5495 (u_int)bp->b_xflags, PRINT_BUF_XFLAGS); 5496 db_printf("b_vflags = 0x%b, b_ioflags = 0x%b\n", 5497 (u_int)bp->b_vflags, PRINT_BUF_VFLAGS, 5498 (u_int)bp->b_ioflags, PRINT_BIO_FLAGS); 5499 db_printf( 5500 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n" 5501 "b_bufobj = %p, b_data = %p\n" 5502 "b_blkno = %jd, b_lblkno = %jd, b_vp = %p, b_dep = %p\n", 5503 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid, 5504 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno, 5505 (intmax_t)bp->b_lblkno, bp->b_vp, bp->b_dep.lh_first); 5506 db_printf("b_kvabase = %p, b_kvasize = %d\n", 5507 bp->b_kvabase, bp->b_kvasize); 5508 if (bp->b_npages) { 5509 int i; 5510 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages); 5511 for (i = 0; i < bp->b_npages; i++) { 5512 vm_page_t m; 5513 m = bp->b_pages[i]; 5514 if (m != NULL) 5515 db_printf("(%p, 0x%lx, 0x%lx)", m->object, 5516 (u_long)m->pindex, 5517 (u_long)VM_PAGE_TO_PHYS(m)); 5518 else 5519 db_printf("( ??? )"); 5520 if ((i + 1) < bp->b_npages) 5521 db_printf(","); 5522 } 5523 db_printf("\n"); 5524 } 5525 BUF_LOCKPRINTINFO(bp); 5526 #if defined(FULL_BUF_TRACKING) 5527 db_printf("b_io_tracking: b_io_tcnt = %u\n", bp->b_io_tcnt); 5528 5529 i = bp->b_io_tcnt % BUF_TRACKING_SIZE; 5530 for (j = 1; j <= BUF_TRACKING_SIZE; j++) { 5531 if (bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)] == NULL) 5532 continue; 5533 db_printf(" %2u: %s\n", j, 5534 bp->b_io_tracking[BUF_TRACKING_ENTRY(i - j)]); 5535 } 5536 #elif defined(BUF_TRACKING) 5537 db_printf("b_io_tracking: %s\n", bp->b_io_tracking); 5538 #endif 5539 } 5540 5541 DB_SHOW_COMMAND_FLAGS(bufqueues, bufqueues, DB_CMD_MEMSAFE) 5542 { 5543 struct bufdomain *bd; 5544 struct buf *bp; 5545 long total; 5546 int i, j, cnt; 5547 5548 db_printf("bqempty: %d\n", bqempty.bq_len); 5549 5550 for (i = 0; i < buf_domains; i++) { 5551 bd = &bdomain[i]; 5552 db_printf("Buf domain %d\n", i); 5553 db_printf("\tfreebufs\t%d\n", bd->bd_freebuffers); 5554 db_printf("\tlofreebufs\t%d\n", bd->bd_lofreebuffers); 5555 db_printf("\thifreebufs\t%d\n", bd->bd_hifreebuffers); 5556 db_printf("\n"); 5557 db_printf("\tbufspace\t%ld\n", bd->bd_bufspace); 5558 db_printf("\tmaxbufspace\t%ld\n", bd->bd_maxbufspace); 5559 db_printf("\thibufspace\t%ld\n", bd->bd_hibufspace); 5560 db_printf("\tlobufspace\t%ld\n", bd->bd_lobufspace); 5561 db_printf("\tbufspacethresh\t%ld\n", bd->bd_bufspacethresh); 5562 db_printf("\n"); 5563 db_printf("\tnumdirtybuffers\t%d\n", bd->bd_numdirtybuffers); 5564 db_printf("\tlodirtybuffers\t%d\n", bd->bd_lodirtybuffers); 5565 db_printf("\thidirtybuffers\t%d\n", bd->bd_hidirtybuffers); 5566 db_printf("\tdirtybufthresh\t%d\n", bd->bd_dirtybufthresh); 5567 db_printf("\n"); 5568 total = 0; 5569 TAILQ_FOREACH(bp, &bd->bd_cleanq->bq_queue, b_freelist) 5570 total += bp->b_bufsize; 5571 db_printf("\tcleanq count\t%d (%ld)\n", 5572 bd->bd_cleanq->bq_len, total); 5573 total = 0; 5574 TAILQ_FOREACH(bp, &bd->bd_dirtyq.bq_queue, b_freelist) 5575 total += bp->b_bufsize; 5576 db_printf("\tdirtyq count\t%d (%ld)\n", 5577 bd->bd_dirtyq.bq_len, total); 5578 db_printf("\twakeup\t\t%d\n", bd->bd_wanted); 5579 db_printf("\tlim\t\t%d\n", bd->bd_lim); 5580 db_printf("\tCPU "); 5581 for (j = 0; j <= mp_maxid; j++) 5582 db_printf("%d, ", bd->bd_subq[j].bq_len); 5583 db_printf("\n"); 5584 cnt = 0; 5585 total = 0; 5586 for (j = 0; j < nbuf; j++) { 5587 bp = nbufp(j); 5588 if (bp->b_domain == i && BUF_ISLOCKED(bp)) { 5589 cnt++; 5590 total += bp->b_bufsize; 5591 } 5592 } 5593 db_printf("\tLocked buffers: %d space %ld\n", cnt, total); 5594 cnt = 0; 5595 total = 0; 5596 for (j = 0; j < nbuf; j++) { 5597 bp = nbufp(j); 5598 if (bp->b_domain == i) { 5599 cnt++; 5600 total += bp->b_bufsize; 5601 } 5602 } 5603 db_printf("\tTotal buffers: %d space %ld\n", cnt, total); 5604 } 5605 } 5606 5607 DB_SHOW_COMMAND_FLAGS(lockedbufs, lockedbufs, DB_CMD_MEMSAFE) 5608 { 5609 struct buf *bp; 5610 int i; 5611 5612 for (i = 0; i < nbuf; i++) { 5613 bp = nbufp(i); 5614 if (BUF_ISLOCKED(bp)) { 5615 db_show_buffer((uintptr_t)bp, 1, 0, NULL); 5616 db_printf("\n"); 5617 if (db_pager_quit) 5618 break; 5619 } 5620 } 5621 } 5622 5623 DB_SHOW_COMMAND(vnodebufs, db_show_vnodebufs) 5624 { 5625 struct vnode *vp; 5626 struct buf *bp; 5627 5628 if (!have_addr) { 5629 db_printf("usage: show vnodebufs <addr>\n"); 5630 return; 5631 } 5632 vp = (struct vnode *)addr; 5633 db_printf("Clean buffers:\n"); 5634 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_clean.bv_hd, b_bobufs) { 5635 db_show_buffer((uintptr_t)bp, 1, 0, NULL); 5636 db_printf("\n"); 5637 } 5638 db_printf("Dirty buffers:\n"); 5639 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) { 5640 db_show_buffer((uintptr_t)bp, 1, 0, NULL); 5641 db_printf("\n"); 5642 } 5643 } 5644 5645 DB_COMMAND_FLAGS(countfreebufs, db_coundfreebufs, DB_CMD_MEMSAFE) 5646 { 5647 struct buf *bp; 5648 int i, used = 0, nfree = 0; 5649 5650 if (have_addr) { 5651 db_printf("usage: countfreebufs\n"); 5652 return; 5653 } 5654 5655 for (i = 0; i < nbuf; i++) { 5656 bp = nbufp(i); 5657 if (bp->b_qindex == QUEUE_EMPTY) 5658 nfree++; 5659 else 5660 used++; 5661 } 5662 5663 db_printf("Counted %d free, %d used (%d tot)\n", nfree, used, 5664 nfree + used); 5665 db_printf("numfreebuffers is %d\n", numfreebuffers); 5666 } 5667 #endif /* DDB */ 5668