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