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