1 /*- 2 * Copyright (c) 2004 Poul-Henning Kamp 3 * Copyright (c) 1994,1997 John S. Dyson 4 * All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 25 * SUCH DAMAGE. 26 */ 27 28 /* 29 * this file contains a new buffer I/O scheme implementing a coherent 30 * VM object and buffer cache scheme. Pains have been taken to make 31 * sure that the performance degradation associated with schemes such 32 * as this is not realized. 33 * 34 * Author: John S. Dyson 35 * Significant help during the development and debugging phases 36 * had been provided by David Greenman, also of the FreeBSD core team. 37 * 38 * see man buf(9) for more info. 39 */ 40 41 #include <sys/cdefs.h> 42 __FBSDID("$FreeBSD$"); 43 44 #include <sys/param.h> 45 #include <sys/systm.h> 46 #include <sys/bio.h> 47 #include <sys/conf.h> 48 #include <sys/buf.h> 49 #include <sys/devicestat.h> 50 #include <sys/eventhandler.h> 51 #include <sys/lock.h> 52 #include <sys/malloc.h> 53 #include <sys/mount.h> 54 #include <sys/mutex.h> 55 #include <sys/kernel.h> 56 #include <sys/kthread.h> 57 #include <sys/proc.h> 58 #include <sys/resourcevar.h> 59 #include <sys/sysctl.h> 60 #include <sys/vmmeter.h> 61 #include <sys/vnode.h> 62 #include <geom/geom.h> 63 #include <vm/vm.h> 64 #include <vm/vm_param.h> 65 #include <vm/vm_kern.h> 66 #include <vm/vm_pageout.h> 67 #include <vm/vm_page.h> 68 #include <vm/vm_object.h> 69 #include <vm/vm_extern.h> 70 #include <vm/vm_map.h> 71 #include "opt_directio.h" 72 #include "opt_swap.h" 73 74 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer"); 75 76 struct bio_ops bioops; /* I/O operation notification */ 77 78 struct buf_ops buf_ops_bio = { 79 .bop_name = "buf_ops_bio", 80 .bop_write = bufwrite, 81 .bop_strategy = bufstrategy, 82 .bop_sync = bufsync, 83 }; 84 85 /* 86 * XXX buf is global because kern_shutdown.c and ffs_checkoverlap has 87 * carnal knowledge of buffers. This knowledge should be moved to vfs_bio.c. 88 */ 89 struct buf *buf; /* buffer header pool */ 90 91 static struct proc *bufdaemonproc; 92 93 static int inmem(struct vnode *vp, daddr_t blkno); 94 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from, 95 vm_offset_t to); 96 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from, 97 vm_offset_t to); 98 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, 99 int pageno, vm_page_t m); 100 static void vfs_clean_pages(struct buf *bp); 101 static void vfs_setdirty(struct buf *bp); 102 static void vfs_vmio_release(struct buf *bp); 103 static int vfs_bio_clcheck(struct vnode *vp, int size, 104 daddr_t lblkno, daddr_t blkno); 105 static int flushbufqueues(int flushdeps); 106 static void buf_daemon(void); 107 static void bremfreel(struct buf *bp); 108 109 int vmiodirenable = TRUE; 110 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0, 111 "Use the VM system for directory writes"); 112 int runningbufspace; 113 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0, 114 "Amount of presently outstanding async buffer io"); 115 static int bufspace; 116 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0, 117 "KVA memory used for bufs"); 118 static int maxbufspace; 119 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0, 120 "Maximum allowed value of bufspace (including buf_daemon)"); 121 static int bufmallocspace; 122 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0, 123 "Amount of malloced memory for buffers"); 124 static int maxbufmallocspace; 125 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW, &maxbufmallocspace, 0, 126 "Maximum amount of malloced memory for buffers"); 127 static int lobufspace; 128 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0, 129 "Minimum amount of buffers we want to have"); 130 static int hibufspace; 131 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0, 132 "Maximum allowed value of bufspace (excluding buf_daemon)"); 133 static int bufreusecnt; 134 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW, &bufreusecnt, 0, 135 "Number of times we have reused a buffer"); 136 static int buffreekvacnt; 137 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW, &buffreekvacnt, 0, 138 "Number of times we have freed the KVA space from some buffer"); 139 static int bufdefragcnt; 140 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW, &bufdefragcnt, 0, 141 "Number of times we have had to repeat buffer allocation to defragment"); 142 static int lorunningspace; 143 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0, 144 "Minimum preferred space used for in-progress I/O"); 145 static int hirunningspace; 146 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0, 147 "Maximum amount of space to use for in-progress I/O"); 148 static int dirtybufferflushes; 149 SYSCTL_INT(_vfs, OID_AUTO, dirtybufferflushes, CTLFLAG_RW, &dirtybufferflushes, 150 0, "Number of bdwrite to bawrite conversions to limit dirty buffers"); 151 static int altbufferflushes; 152 SYSCTL_INT(_vfs, OID_AUTO, altbufferflushes, CTLFLAG_RW, &altbufferflushes, 153 0, "Number of fsync flushes to limit dirty buffers"); 154 static int recursiveflushes; 155 SYSCTL_INT(_vfs, OID_AUTO, recursiveflushes, CTLFLAG_RW, &recursiveflushes, 156 0, "Number of flushes skipped due to being recursive"); 157 static int numdirtybuffers; 158 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0, 159 "Number of buffers that are dirty (has unwritten changes) at the moment"); 160 static int lodirtybuffers; 161 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0, 162 "How many buffers we want to have free before bufdaemon can sleep"); 163 static int hidirtybuffers; 164 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0, 165 "When the number of dirty buffers is considered severe"); 166 static int dirtybufthresh; 167 SYSCTL_INT(_vfs, OID_AUTO, dirtybufthresh, CTLFLAG_RW, &dirtybufthresh, 168 0, "Number of bdwrite to bawrite conversions to clear dirty buffers"); 169 static int numfreebuffers; 170 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0, 171 "Number of free buffers"); 172 static int lofreebuffers; 173 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0, 174 "XXX Unused"); 175 static int hifreebuffers; 176 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0, 177 "XXX Complicatedly unused"); 178 static int getnewbufcalls; 179 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW, &getnewbufcalls, 0, 180 "Number of calls to getnewbuf"); 181 static int getnewbufrestarts; 182 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW, &getnewbufrestarts, 0, 183 "Number of times getnewbuf has had to restart a buffer aquisition"); 184 185 /* 186 * Wakeup point for bufdaemon, as well as indicator of whether it is already 187 * active. Set to 1 when the bufdaemon is already "on" the queue, 0 when it 188 * is idling. 189 */ 190 static int bd_request; 191 192 /* 193 * This lock synchronizes access to bd_request. 194 */ 195 static struct mtx bdlock; 196 197 /* 198 * bogus page -- for I/O to/from partially complete buffers 199 * this is a temporary solution to the problem, but it is not 200 * really that bad. it would be better to split the buffer 201 * for input in the case of buffers partially already in memory, 202 * but the code is intricate enough already. 203 */ 204 vm_page_t bogus_page; 205 206 /* 207 * Synchronization (sleep/wakeup) variable for active buffer space requests. 208 * Set when wait starts, cleared prior to wakeup(). 209 * Used in runningbufwakeup() and waitrunningbufspace(). 210 */ 211 static int runningbufreq; 212 213 /* 214 * This lock protects the runningbufreq and synchronizes runningbufwakeup and 215 * waitrunningbufspace(). 216 */ 217 static struct mtx rbreqlock; 218 219 /* 220 * Synchronization (sleep/wakeup) variable for buffer requests. 221 * Can contain the VFS_BIO_NEED flags defined below; setting/clearing is done 222 * by and/or. 223 * Used in numdirtywakeup(), bufspacewakeup(), bufcountwakeup(), bwillwrite(), 224 * getnewbuf(), and getblk(). 225 */ 226 static int needsbuffer; 227 228 /* 229 * Lock that protects needsbuffer and the sleeps/wakeups surrounding it. 230 */ 231 static struct mtx nblock; 232 233 /* 234 * Lock that protects against bwait()/bdone()/B_DONE races. 235 */ 236 237 static struct mtx bdonelock; 238 239 /* 240 * Definitions for the buffer free lists. 241 */ 242 #define BUFFER_QUEUES 5 /* number of free buffer queues */ 243 244 #define QUEUE_NONE 0 /* on no queue */ 245 #define QUEUE_CLEAN 1 /* non-B_DELWRI buffers */ 246 #define QUEUE_DIRTY 2 /* B_DELWRI buffers */ 247 #define QUEUE_EMPTYKVA 3 /* empty buffer headers w/KVA assignment */ 248 #define QUEUE_EMPTY 4 /* empty buffer headers */ 249 250 /* Queues for free buffers with various properties */ 251 static TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES] = { { 0 } }; 252 253 /* Lock for the bufqueues */ 254 static struct mtx bqlock; 255 256 /* 257 * Single global constant for BUF_WMESG, to avoid getting multiple references. 258 * buf_wmesg is referred from macros. 259 */ 260 const char *buf_wmesg = BUF_WMESG; 261 262 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */ 263 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */ 264 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */ 265 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */ 266 267 #ifdef DIRECTIO 268 extern void ffs_rawread_setup(void); 269 #endif /* DIRECTIO */ 270 /* 271 * numdirtywakeup: 272 * 273 * If someone is blocked due to there being too many dirty buffers, 274 * and numdirtybuffers is now reasonable, wake them up. 275 */ 276 277 static __inline void 278 numdirtywakeup(int level) 279 { 280 281 if (numdirtybuffers <= level) { 282 mtx_lock(&nblock); 283 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) { 284 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH; 285 wakeup(&needsbuffer); 286 } 287 mtx_unlock(&nblock); 288 } 289 } 290 291 /* 292 * bufspacewakeup: 293 * 294 * Called when buffer space is potentially available for recovery. 295 * getnewbuf() will block on this flag when it is unable to free 296 * sufficient buffer space. Buffer space becomes recoverable when 297 * bp's get placed back in the queues. 298 */ 299 300 static __inline void 301 bufspacewakeup(void) 302 { 303 304 /* 305 * If someone is waiting for BUF space, wake them up. Even 306 * though we haven't freed the kva space yet, the waiting 307 * process will be able to now. 308 */ 309 mtx_lock(&nblock); 310 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) { 311 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE; 312 wakeup(&needsbuffer); 313 } 314 mtx_unlock(&nblock); 315 } 316 317 /* 318 * runningbufwakeup() - in-progress I/O accounting. 319 * 320 */ 321 static __inline void 322 runningbufwakeup(struct buf *bp) 323 { 324 325 if (bp->b_runningbufspace) { 326 atomic_subtract_int(&runningbufspace, bp->b_runningbufspace); 327 bp->b_runningbufspace = 0; 328 mtx_lock(&rbreqlock); 329 if (runningbufreq && runningbufspace <= lorunningspace) { 330 runningbufreq = 0; 331 wakeup(&runningbufreq); 332 } 333 mtx_unlock(&rbreqlock); 334 } 335 } 336 337 /* 338 * bufcountwakeup: 339 * 340 * Called when a buffer has been added to one of the free queues to 341 * account for the buffer and to wakeup anyone waiting for free buffers. 342 * This typically occurs when large amounts of metadata are being handled 343 * by the buffer cache ( else buffer space runs out first, usually ). 344 */ 345 346 static __inline void 347 bufcountwakeup(void) 348 { 349 350 atomic_add_int(&numfreebuffers, 1); 351 mtx_lock(&nblock); 352 if (needsbuffer) { 353 needsbuffer &= ~VFS_BIO_NEED_ANY; 354 if (numfreebuffers >= hifreebuffers) 355 needsbuffer &= ~VFS_BIO_NEED_FREE; 356 wakeup(&needsbuffer); 357 } 358 mtx_unlock(&nblock); 359 } 360 361 /* 362 * waitrunningbufspace() 363 * 364 * runningbufspace is a measure of the amount of I/O currently 365 * running. This routine is used in async-write situations to 366 * prevent creating huge backups of pending writes to a device. 367 * Only asynchronous writes are governed by this function. 368 * 369 * Reads will adjust runningbufspace, but will not block based on it. 370 * The read load has a side effect of reducing the allowed write load. 371 * 372 * This does NOT turn an async write into a sync write. It waits 373 * for earlier writes to complete and generally returns before the 374 * caller's write has reached the device. 375 */ 376 static __inline void 377 waitrunningbufspace(void) 378 { 379 380 mtx_lock(&rbreqlock); 381 while (runningbufspace > hirunningspace) { 382 ++runningbufreq; 383 msleep(&runningbufreq, &rbreqlock, PVM, "wdrain", 0); 384 } 385 mtx_unlock(&rbreqlock); 386 } 387 388 389 /* 390 * vfs_buf_test_cache: 391 * 392 * Called when a buffer is extended. This function clears the B_CACHE 393 * bit if the newly extended portion of the buffer does not contain 394 * valid data. 395 */ 396 static __inline 397 void 398 vfs_buf_test_cache(struct buf *bp, 399 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size, 400 vm_page_t m) 401 { 402 403 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED); 404 if (bp->b_flags & B_CACHE) { 405 int base = (foff + off) & PAGE_MASK; 406 if (vm_page_is_valid(m, base, size) == 0) 407 bp->b_flags &= ~B_CACHE; 408 } 409 } 410 411 /* Wake up the buffer deamon if necessary */ 412 static __inline 413 void 414 bd_wakeup(int dirtybuflevel) 415 { 416 417 mtx_lock(&bdlock); 418 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) { 419 bd_request = 1; 420 wakeup(&bd_request); 421 } 422 mtx_unlock(&bdlock); 423 } 424 425 /* 426 * bd_speedup - speedup the buffer cache flushing code 427 */ 428 429 static __inline 430 void 431 bd_speedup(void) 432 { 433 434 bd_wakeup(1); 435 } 436 437 /* 438 * Calculating buffer cache scaling values and reserve space for buffer 439 * headers. This is called during low level kernel initialization and 440 * may be called more then once. We CANNOT write to the memory area 441 * being reserved at this time. 442 */ 443 caddr_t 444 kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est) 445 { 446 447 /* 448 * physmem_est is in pages. Convert it to kilobytes (assumes 449 * PAGE_SIZE is >= 1K) 450 */ 451 physmem_est = physmem_est * (PAGE_SIZE / 1024); 452 453 /* 454 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE. 455 * For the first 64MB of ram nominally allocate sufficient buffers to 456 * cover 1/4 of our ram. Beyond the first 64MB allocate additional 457 * buffers to cover 1/20 of our ram over 64MB. When auto-sizing 458 * the buffer cache we limit the eventual kva reservation to 459 * maxbcache bytes. 460 * 461 * factor represents the 1/4 x ram conversion. 462 */ 463 if (nbuf == 0) { 464 int factor = 4 * BKVASIZE / 1024; 465 466 nbuf = 50; 467 if (physmem_est > 4096) 468 nbuf += min((physmem_est - 4096) / factor, 469 65536 / factor); 470 if (physmem_est > 65536) 471 nbuf += (physmem_est - 65536) * 2 / (factor * 5); 472 473 if (maxbcache && nbuf > maxbcache / BKVASIZE) 474 nbuf = maxbcache / BKVASIZE; 475 } 476 477 #if 0 478 /* 479 * Do not allow the buffer_map to be more then 1/2 the size of the 480 * kernel_map. 481 */ 482 if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) / 483 (BKVASIZE * 2)) { 484 nbuf = (kernel_map->max_offset - kernel_map->min_offset) / 485 (BKVASIZE * 2); 486 printf("Warning: nbufs capped at %d\n", nbuf); 487 } 488 #endif 489 490 /* 491 * swbufs are used as temporary holders for I/O, such as paging I/O. 492 * We have no less then 16 and no more then 256. 493 */ 494 nswbuf = max(min(nbuf/4, 256), 16); 495 #ifdef NSWBUF_MIN 496 if (nswbuf < NSWBUF_MIN) 497 nswbuf = NSWBUF_MIN; 498 #endif 499 #ifdef DIRECTIO 500 ffs_rawread_setup(); 501 #endif 502 503 /* 504 * Reserve space for the buffer cache buffers 505 */ 506 swbuf = (void *)v; 507 v = (caddr_t)(swbuf + nswbuf); 508 buf = (void *)v; 509 v = (caddr_t)(buf + nbuf); 510 511 return(v); 512 } 513 514 /* Initialize the buffer subsystem. Called before use of any buffers. */ 515 void 516 bufinit(void) 517 { 518 struct buf *bp; 519 int i; 520 521 mtx_init(&bqlock, "buf queue lock", NULL, MTX_DEF); 522 mtx_init(&rbreqlock, "runningbufspace lock", NULL, MTX_DEF); 523 mtx_init(&nblock, "needsbuffer lock", NULL, MTX_DEF); 524 mtx_init(&bdlock, "buffer daemon lock", NULL, MTX_DEF); 525 mtx_init(&bdonelock, "bdone lock", NULL, MTX_DEF); 526 527 /* next, make a null set of free lists */ 528 for (i = 0; i < BUFFER_QUEUES; i++) 529 TAILQ_INIT(&bufqueues[i]); 530 531 /* finally, initialize each buffer header and stick on empty q */ 532 for (i = 0; i < nbuf; i++) { 533 bp = &buf[i]; 534 bzero(bp, sizeof *bp); 535 bp->b_flags = B_INVAL; /* we're just an empty header */ 536 bp->b_rcred = NOCRED; 537 bp->b_wcred = NOCRED; 538 bp->b_qindex = QUEUE_EMPTY; 539 bp->b_vflags = 0; 540 bp->b_xflags = 0; 541 LIST_INIT(&bp->b_dep); 542 BUF_LOCKINIT(bp); 543 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist); 544 } 545 546 /* 547 * maxbufspace is the absolute maximum amount of buffer space we are 548 * allowed to reserve in KVM and in real terms. The absolute maximum 549 * is nominally used by buf_daemon. hibufspace is the nominal maximum 550 * used by most other processes. The differential is required to 551 * ensure that buf_daemon is able to run when other processes might 552 * be blocked waiting for buffer space. 553 * 554 * maxbufspace is based on BKVASIZE. Allocating buffers larger then 555 * this may result in KVM fragmentation which is not handled optimally 556 * by the system. 557 */ 558 maxbufspace = nbuf * BKVASIZE; 559 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10); 560 lobufspace = hibufspace - MAXBSIZE; 561 562 lorunningspace = 512 * 1024; 563 hirunningspace = 1024 * 1024; 564 565 /* 566 * Limit the amount of malloc memory since it is wired permanently into 567 * the kernel space. Even though this is accounted for in the buffer 568 * allocation, we don't want the malloced region to grow uncontrolled. 569 * The malloc scheme improves memory utilization significantly on average 570 * (small) directories. 571 */ 572 maxbufmallocspace = hibufspace / 20; 573 574 /* 575 * Reduce the chance of a deadlock occuring by limiting the number 576 * of delayed-write dirty buffers we allow to stack up. 577 */ 578 hidirtybuffers = nbuf / 4 + 20; 579 dirtybufthresh = hidirtybuffers * 9 / 10; 580 numdirtybuffers = 0; 581 /* 582 * To support extreme low-memory systems, make sure hidirtybuffers cannot 583 * eat up all available buffer space. This occurs when our minimum cannot 584 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming 585 * BKVASIZE'd (8K) buffers. 586 */ 587 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) { 588 hidirtybuffers >>= 1; 589 } 590 lodirtybuffers = hidirtybuffers / 2; 591 592 /* 593 * Try to keep the number of free buffers in the specified range, 594 * and give special processes (e.g. like buf_daemon) access to an 595 * emergency reserve. 596 */ 597 lofreebuffers = nbuf / 18 + 5; 598 hifreebuffers = 2 * lofreebuffers; 599 numfreebuffers = nbuf; 600 601 /* 602 * Maximum number of async ops initiated per buf_daemon loop. This is 603 * somewhat of a hack at the moment, we really need to limit ourselves 604 * based on the number of bytes of I/O in-transit that were initiated 605 * from buf_daemon. 606 */ 607 608 bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ | 609 VM_ALLOC_NORMAL | VM_ALLOC_WIRED); 610 } 611 612 /* 613 * bfreekva() - free the kva allocation for a buffer. 614 * 615 * Must be called at splbio() or higher as this is the only locking for 616 * buffer_map. 617 * 618 * Since this call frees up buffer space, we call bufspacewakeup(). 619 */ 620 static void 621 bfreekva(struct buf *bp) 622 { 623 624 if (bp->b_kvasize) { 625 atomic_add_int(&buffreekvacnt, 1); 626 atomic_subtract_int(&bufspace, bp->b_kvasize); 627 vm_map_delete(buffer_map, 628 (vm_offset_t) bp->b_kvabase, 629 (vm_offset_t) bp->b_kvabase + bp->b_kvasize 630 ); 631 bp->b_kvasize = 0; 632 bufspacewakeup(); 633 } 634 } 635 636 /* 637 * bremfree: 638 * 639 * Mark the buffer for removal from the appropriate free list in brelse. 640 * 641 */ 642 void 643 bremfree(struct buf *bp) 644 { 645 646 CTR3(KTR_BUF, "bremfree(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 647 KASSERT(BUF_REFCNT(bp), ("bremfree: buf must be locked.")); 648 KASSERT((bp->b_flags & B_REMFREE) == 0 && bp->b_qindex != QUEUE_NONE, 649 ("bremfree: buffer %p not on a queue.", bp)); 650 651 bp->b_flags |= B_REMFREE; 652 /* Fixup numfreebuffers count. */ 653 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) 654 atomic_subtract_int(&numfreebuffers, 1); 655 } 656 657 /* 658 * bremfreef: 659 * 660 * Force an immediate removal from a free list. Used only in nfs when 661 * it abuses the b_freelist pointer. 662 */ 663 void 664 bremfreef(struct buf *bp) 665 { 666 mtx_lock(&bqlock); 667 bremfreel(bp); 668 mtx_unlock(&bqlock); 669 } 670 671 /* 672 * bremfreel: 673 * 674 * Removes a buffer from the free list, must be called with the 675 * bqlock held. 676 */ 677 static void 678 bremfreel(struct buf *bp) 679 { 680 int s = splbio(); 681 682 CTR3(KTR_BUF, "bremfreel(%p) vp %p flags %X", 683 bp, bp->b_vp, bp->b_flags); 684 KASSERT(BUF_REFCNT(bp), ("bremfreel: buffer %p not locked.", bp)); 685 KASSERT(bp->b_qindex != QUEUE_NONE, 686 ("bremfreel: buffer %p not on a queue.", bp)); 687 mtx_assert(&bqlock, MA_OWNED); 688 689 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist); 690 bp->b_qindex = QUEUE_NONE; 691 /* 692 * If this was a delayed bremfree() we only need to remove the buffer 693 * from the queue and return the stats are already done. 694 */ 695 if (bp->b_flags & B_REMFREE) { 696 bp->b_flags &= ~B_REMFREE; 697 splx(s); 698 return; 699 } 700 /* 701 * Fixup numfreebuffers count. If the buffer is invalid or not 702 * delayed-write, the buffer was free and we must decrement 703 * numfreebuffers. 704 */ 705 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) 706 atomic_subtract_int(&numfreebuffers, 1); 707 splx(s); 708 } 709 710 711 /* 712 * Get a buffer with the specified data. Look in the cache first. We 713 * must clear BIO_ERROR and B_INVAL prior to initiating I/O. If B_CACHE 714 * is set, the buffer is valid and we do not have to do anything ( see 715 * getblk() ). This is really just a special case of breadn(). 716 */ 717 int 718 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred, 719 struct buf **bpp) 720 { 721 722 return (breadn(vp, blkno, size, 0, 0, 0, cred, bpp)); 723 } 724 725 /* 726 * Operates like bread, but also starts asynchronous I/O on 727 * read-ahead blocks. We must clear BIO_ERROR and B_INVAL prior 728 * to initiating I/O . If B_CACHE is set, the buffer is valid 729 * and we do not have to do anything. 730 */ 731 int 732 breadn(struct vnode * vp, daddr_t blkno, int size, 733 daddr_t * rablkno, int *rabsize, 734 int cnt, struct ucred * cred, struct buf **bpp) 735 { 736 struct buf *bp, *rabp; 737 int i; 738 int rv = 0, readwait = 0; 739 740 CTR3(KTR_BUF, "breadn(%p, %jd, %d)", vp, blkno, size); 741 *bpp = bp = getblk(vp, blkno, size, 0, 0, 0); 742 743 /* if not found in cache, do some I/O */ 744 if ((bp->b_flags & B_CACHE) == 0) { 745 if (curthread != PCPU_GET(idlethread)) 746 curthread->td_proc->p_stats->p_ru.ru_inblock++; 747 bp->b_iocmd = BIO_READ; 748 bp->b_flags &= ~B_INVAL; 749 bp->b_ioflags &= ~BIO_ERROR; 750 if (bp->b_rcred == NOCRED && cred != NOCRED) 751 bp->b_rcred = crhold(cred); 752 vfs_busy_pages(bp, 0); 753 bp->b_iooffset = dbtob(bp->b_blkno); 754 bstrategy(bp); 755 ++readwait; 756 } 757 758 for (i = 0; i < cnt; i++, rablkno++, rabsize++) { 759 if (inmem(vp, *rablkno)) 760 continue; 761 rabp = getblk(vp, *rablkno, *rabsize, 0, 0, 0); 762 763 if ((rabp->b_flags & B_CACHE) == 0) { 764 if (curthread != PCPU_GET(idlethread)) 765 curthread->td_proc->p_stats->p_ru.ru_inblock++; 766 rabp->b_flags |= B_ASYNC; 767 rabp->b_flags &= ~B_INVAL; 768 rabp->b_ioflags &= ~BIO_ERROR; 769 rabp->b_iocmd = BIO_READ; 770 if (rabp->b_rcred == NOCRED && cred != NOCRED) 771 rabp->b_rcred = crhold(cred); 772 vfs_busy_pages(rabp, 0); 773 BUF_KERNPROC(rabp); 774 rabp->b_iooffset = dbtob(rabp->b_blkno); 775 bstrategy(rabp); 776 } else { 777 brelse(rabp); 778 } 779 } 780 781 if (readwait) { 782 rv = bufwait(bp); 783 } 784 return (rv); 785 } 786 787 /* 788 * Write, release buffer on completion. (Done by iodone 789 * if async). Do not bother writing anything if the buffer 790 * is invalid. 791 * 792 * Note that we set B_CACHE here, indicating that buffer is 793 * fully valid and thus cacheable. This is true even of NFS 794 * now so we set it generally. This could be set either here 795 * or in biodone() since the I/O is synchronous. We put it 796 * here. 797 */ 798 int 799 bufwrite(struct buf *bp) 800 { 801 int oldflags, s; 802 803 CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 804 if (bp->b_flags & B_INVAL) { 805 brelse(bp); 806 return (0); 807 } 808 809 oldflags = bp->b_flags; 810 811 if (BUF_REFCNT(bp) == 0) 812 panic("bufwrite: buffer is not busy???"); 813 s = splbio(); 814 815 KASSERT(!(bp->b_vflags & BV_BKGRDINPROG), 816 ("FFS background buffer should not get here %p", bp)); 817 818 /* Mark the buffer clean */ 819 bundirty(bp); 820 821 bp->b_flags &= ~B_DONE; 822 bp->b_ioflags &= ~BIO_ERROR; 823 bp->b_flags |= B_CACHE; 824 bp->b_iocmd = BIO_WRITE; 825 826 bufobj_wref(bp->b_bufobj); 827 vfs_busy_pages(bp, 1); 828 829 /* 830 * Normal bwrites pipeline writes 831 */ 832 bp->b_runningbufspace = bp->b_bufsize; 833 atomic_add_int(&runningbufspace, bp->b_runningbufspace); 834 835 if (curthread != PCPU_GET(idlethread)) 836 curthread->td_proc->p_stats->p_ru.ru_oublock++; 837 splx(s); 838 if (oldflags & B_ASYNC) 839 BUF_KERNPROC(bp); 840 bp->b_iooffset = dbtob(bp->b_blkno); 841 bstrategy(bp); 842 843 if ((oldflags & B_ASYNC) == 0) { 844 int rtval = bufwait(bp); 845 brelse(bp); 846 return (rtval); 847 } else { 848 /* 849 * don't allow the async write to saturate the I/O 850 * system. We will not deadlock here because 851 * we are blocking waiting for I/O that is already in-progress 852 * to complete. We do not block here if it is the update 853 * or syncer daemon trying to clean up as that can lead 854 * to deadlock. 855 */ 856 if (curthread->td_proc != bufdaemonproc && 857 curthread->td_proc != updateproc) 858 waitrunningbufspace(); 859 } 860 861 return (0); 862 } 863 864 /* 865 * Delayed write. (Buffer is marked dirty). Do not bother writing 866 * anything if the buffer is marked invalid. 867 * 868 * Note that since the buffer must be completely valid, we can safely 869 * set B_CACHE. In fact, we have to set B_CACHE here rather then in 870 * biodone() in order to prevent getblk from writing the buffer 871 * out synchronously. 872 */ 873 void 874 bdwrite(struct buf *bp) 875 { 876 struct thread *td = curthread; 877 struct vnode *vp; 878 struct buf *nbp; 879 struct bufobj *bo; 880 881 CTR3(KTR_BUF, "bdwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 882 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp)); 883 KASSERT(BUF_REFCNT(bp) != 0, ("bdwrite: buffer is not busy")); 884 885 if (bp->b_flags & B_INVAL) { 886 brelse(bp); 887 return; 888 } 889 890 /* 891 * If we have too many dirty buffers, don't create any more. 892 * If we are wildly over our limit, then force a complete 893 * cleanup. Otherwise, just keep the situation from getting 894 * out of control. Note that we have to avoid a recursive 895 * disaster and not try to clean up after our own cleanup! 896 */ 897 vp = bp->b_vp; 898 bo = bp->b_bufobj; 899 if ((td->td_pflags & TDP_COWINPROGRESS) == 0) { 900 BO_LOCK(bo); 901 if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10) { 902 BO_UNLOCK(bo); 903 (void) VOP_FSYNC(vp, MNT_NOWAIT, td); 904 altbufferflushes++; 905 } else if (bo->bo_dirty.bv_cnt > dirtybufthresh) { 906 /* 907 * Try to find a buffer to flush. 908 */ 909 TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) { 910 if ((nbp->b_vflags & BV_BKGRDINPROG) || 911 BUF_LOCK(nbp, 912 LK_EXCLUSIVE | LK_NOWAIT, NULL)) 913 continue; 914 if (bp == nbp) 915 panic("bdwrite: found ourselves"); 916 BO_UNLOCK(bo); 917 /* Don't countdeps with the bo lock held. */ 918 if (buf_countdeps(nbp, 0)) { 919 BO_LOCK(bo); 920 BUF_UNLOCK(nbp); 921 continue; 922 } 923 if (nbp->b_flags & B_CLUSTEROK) { 924 vfs_bio_awrite(nbp); 925 } else { 926 bremfree(nbp); 927 bawrite(nbp); 928 } 929 dirtybufferflushes++; 930 break; 931 } 932 if (nbp == NULL) 933 BO_UNLOCK(bo); 934 } else 935 BO_UNLOCK(bo); 936 } else 937 recursiveflushes++; 938 939 bdirty(bp); 940 /* 941 * Set B_CACHE, indicating that the buffer is fully valid. This is 942 * true even of NFS now. 943 */ 944 bp->b_flags |= B_CACHE; 945 946 /* 947 * This bmap keeps the system from needing to do the bmap later, 948 * perhaps when the system is attempting to do a sync. Since it 949 * is likely that the indirect block -- or whatever other datastructure 950 * that the filesystem needs is still in memory now, it is a good 951 * thing to do this. Note also, that if the pageout daemon is 952 * requesting a sync -- there might not be enough memory to do 953 * the bmap then... So, this is important to do. 954 */ 955 if (vp->v_type != VCHR && bp->b_lblkno == bp->b_blkno) { 956 VOP_BMAP(vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL); 957 } 958 959 /* 960 * Set the *dirty* buffer range based upon the VM system dirty pages. 961 */ 962 vfs_setdirty(bp); 963 964 /* 965 * We need to do this here to satisfy the vnode_pager and the 966 * pageout daemon, so that it thinks that the pages have been 967 * "cleaned". Note that since the pages are in a delayed write 968 * buffer -- the VFS layer "will" see that the pages get written 969 * out on the next sync, or perhaps the cluster will be completed. 970 */ 971 vfs_clean_pages(bp); 972 bqrelse(bp); 973 974 /* 975 * Wakeup the buffer flushing daemon if we have a lot of dirty 976 * buffers (midpoint between our recovery point and our stall 977 * point). 978 */ 979 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2); 980 981 /* 982 * note: we cannot initiate I/O from a bdwrite even if we wanted to, 983 * due to the softdep code. 984 */ 985 } 986 987 /* 988 * bdirty: 989 * 990 * Turn buffer into delayed write request. We must clear BIO_READ and 991 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to 992 * itself to properly update it in the dirty/clean lists. We mark it 993 * B_DONE to ensure that any asynchronization of the buffer properly 994 * clears B_DONE ( else a panic will occur later ). 995 * 996 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which 997 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty() 998 * should only be called if the buffer is known-good. 999 * 1000 * Since the buffer is not on a queue, we do not update the numfreebuffers 1001 * count. 1002 * 1003 * Must be called at splbio(). 1004 * The buffer must be on QUEUE_NONE. 1005 */ 1006 void 1007 bdirty(struct buf *bp) 1008 { 1009 1010 CTR3(KTR_BUF, "bdirty(%p) vp %p flags %X", 1011 bp, bp->b_vp, bp->b_flags); 1012 KASSERT(BUF_REFCNT(bp) == 1, ("bdirty: bp %p not locked",bp)); 1013 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp)); 1014 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE, 1015 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex)); 1016 bp->b_flags &= ~(B_RELBUF); 1017 bp->b_iocmd = BIO_WRITE; 1018 1019 if ((bp->b_flags & B_DELWRI) == 0) { 1020 bp->b_flags |= /* XXX B_DONE | */ B_DELWRI; 1021 reassignbuf(bp); 1022 atomic_add_int(&numdirtybuffers, 1); 1023 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2); 1024 } 1025 } 1026 1027 /* 1028 * bundirty: 1029 * 1030 * Clear B_DELWRI for buffer. 1031 * 1032 * Since the buffer is not on a queue, we do not update the numfreebuffers 1033 * count. 1034 * 1035 * Must be called at splbio(). 1036 * The buffer must be on QUEUE_NONE. 1037 */ 1038 1039 void 1040 bundirty(struct buf *bp) 1041 { 1042 1043 CTR3(KTR_BUF, "bundirty(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 1044 KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp)); 1045 KASSERT(bp->b_flags & B_REMFREE || bp->b_qindex == QUEUE_NONE, 1046 ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex)); 1047 KASSERT(BUF_REFCNT(bp) == 1, ("bundirty: bp %p not locked",bp)); 1048 1049 if (bp->b_flags & B_DELWRI) { 1050 bp->b_flags &= ~B_DELWRI; 1051 reassignbuf(bp); 1052 atomic_subtract_int(&numdirtybuffers, 1); 1053 numdirtywakeup(lodirtybuffers); 1054 } 1055 /* 1056 * Since it is now being written, we can clear its deferred write flag. 1057 */ 1058 bp->b_flags &= ~B_DEFERRED; 1059 } 1060 1061 /* 1062 * bawrite: 1063 * 1064 * Asynchronous write. Start output on a buffer, but do not wait for 1065 * it to complete. The buffer is released when the output completes. 1066 * 1067 * bwrite() ( or the VOP routine anyway ) is responsible for handling 1068 * B_INVAL buffers. Not us. 1069 */ 1070 void 1071 bawrite(struct buf *bp) 1072 { 1073 1074 bp->b_flags |= B_ASYNC; 1075 (void) bwrite(bp); 1076 } 1077 1078 /* 1079 * bwillwrite: 1080 * 1081 * Called prior to the locking of any vnodes when we are expecting to 1082 * write. We do not want to starve the buffer cache with too many 1083 * dirty buffers so we block here. By blocking prior to the locking 1084 * of any vnodes we attempt to avoid the situation where a locked vnode 1085 * prevents the various system daemons from flushing related buffers. 1086 */ 1087 1088 void 1089 bwillwrite(void) 1090 { 1091 1092 if (numdirtybuffers >= hidirtybuffers) { 1093 int s; 1094 1095 s = splbio(); 1096 mtx_lock(&nblock); 1097 while (numdirtybuffers >= hidirtybuffers) { 1098 bd_wakeup(1); 1099 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH; 1100 msleep(&needsbuffer, &nblock, 1101 (PRIBIO + 4), "flswai", 0); 1102 } 1103 splx(s); 1104 mtx_unlock(&nblock); 1105 } 1106 } 1107 1108 /* 1109 * Return true if we have too many dirty buffers. 1110 */ 1111 int 1112 buf_dirty_count_severe(void) 1113 { 1114 1115 return(numdirtybuffers >= hidirtybuffers); 1116 } 1117 1118 /* 1119 * brelse: 1120 * 1121 * Release a busy buffer and, if requested, free its resources. The 1122 * buffer will be stashed in the appropriate bufqueue[] allowing it 1123 * to be accessed later as a cache entity or reused for other purposes. 1124 */ 1125 void 1126 brelse(struct buf *bp) 1127 { 1128 int s; 1129 1130 CTR3(KTR_BUF, "brelse(%p) vp %p flags %X", 1131 bp, bp->b_vp, bp->b_flags); 1132 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), 1133 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp)); 1134 1135 s = splbio(); 1136 1137 if (bp->b_iocmd == BIO_WRITE && 1138 (bp->b_ioflags & BIO_ERROR) && 1139 !(bp->b_flags & B_INVAL)) { 1140 /* 1141 * Failed write, redirty. Must clear BIO_ERROR to prevent 1142 * pages from being scrapped. If B_INVAL is set then 1143 * this case is not run and the next case is run to 1144 * destroy the buffer. B_INVAL can occur if the buffer 1145 * is outside the range supported by the underlying device. 1146 */ 1147 bp->b_ioflags &= ~BIO_ERROR; 1148 bdirty(bp); 1149 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL)) || 1150 (bp->b_ioflags & BIO_ERROR) || (bp->b_bufsize <= 0)) { 1151 /* 1152 * Either a failed I/O or we were asked to free or not 1153 * cache the buffer. 1154 */ 1155 bp->b_flags |= B_INVAL; 1156 if (LIST_FIRST(&bp->b_dep) != NULL) 1157 buf_deallocate(bp); 1158 if (bp->b_flags & B_DELWRI) { 1159 atomic_subtract_int(&numdirtybuffers, 1); 1160 numdirtywakeup(lodirtybuffers); 1161 } 1162 bp->b_flags &= ~(B_DELWRI | B_CACHE); 1163 if ((bp->b_flags & B_VMIO) == 0) { 1164 if (bp->b_bufsize) 1165 allocbuf(bp, 0); 1166 if (bp->b_vp) 1167 brelvp(bp); 1168 } 1169 } 1170 1171 /* 1172 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release() 1173 * is called with B_DELWRI set, the underlying pages may wind up 1174 * getting freed causing a previous write (bdwrite()) to get 'lost' 1175 * because pages associated with a B_DELWRI bp are marked clean. 1176 * 1177 * We still allow the B_INVAL case to call vfs_vmio_release(), even 1178 * if B_DELWRI is set. 1179 * 1180 * If B_DELWRI is not set we may have to set B_RELBUF if we are low 1181 * on pages to return pages to the VM page queues. 1182 */ 1183 if (bp->b_flags & B_DELWRI) 1184 bp->b_flags &= ~B_RELBUF; 1185 else if (vm_page_count_severe()) { 1186 /* 1187 * XXX This lock may not be necessary since BKGRDINPROG 1188 * cannot be set while we hold the buf lock, it can only be 1189 * cleared if it is already pending. 1190 */ 1191 if (bp->b_vp) { 1192 BO_LOCK(bp->b_bufobj); 1193 if (!(bp->b_vflags & BV_BKGRDINPROG)) 1194 bp->b_flags |= B_RELBUF; 1195 BO_UNLOCK(bp->b_bufobj); 1196 } else 1197 bp->b_flags |= B_RELBUF; 1198 } 1199 1200 /* 1201 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer 1202 * constituted, not even NFS buffers now. Two flags effect this. If 1203 * B_INVAL, the struct buf is invalidated but the VM object is kept 1204 * around ( i.e. so it is trivial to reconstitute the buffer later ). 1205 * 1206 * If BIO_ERROR or B_NOCACHE is set, pages in the VM object will be 1207 * invalidated. BIO_ERROR cannot be set for a failed write unless the 1208 * buffer is also B_INVAL because it hits the re-dirtying code above. 1209 * 1210 * Normally we can do this whether a buffer is B_DELWRI or not. If 1211 * the buffer is an NFS buffer, it is tracking piecemeal writes or 1212 * the commit state and we cannot afford to lose the buffer. If the 1213 * buffer has a background write in progress, we need to keep it 1214 * around to prevent it from being reconstituted and starting a second 1215 * background write. 1216 */ 1217 if ((bp->b_flags & B_VMIO) 1218 && !(bp->b_vp->v_mount != NULL && 1219 (bp->b_vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 && 1220 !vn_isdisk(bp->b_vp, NULL) && 1221 (bp->b_flags & B_DELWRI)) 1222 ) { 1223 1224 int i, j, resid; 1225 vm_page_t m; 1226 off_t foff; 1227 vm_pindex_t poff; 1228 vm_object_t obj; 1229 1230 obj = bp->b_bufobj->bo_object; 1231 1232 /* 1233 * Get the base offset and length of the buffer. Note that 1234 * in the VMIO case if the buffer block size is not 1235 * page-aligned then b_data pointer may not be page-aligned. 1236 * But our b_pages[] array *IS* page aligned. 1237 * 1238 * block sizes less then DEV_BSIZE (usually 512) are not 1239 * supported due to the page granularity bits (m->valid, 1240 * m->dirty, etc...). 1241 * 1242 * See man buf(9) for more information 1243 */ 1244 resid = bp->b_bufsize; 1245 foff = bp->b_offset; 1246 VM_OBJECT_LOCK(obj); 1247 for (i = 0; i < bp->b_npages; i++) { 1248 int had_bogus = 0; 1249 1250 m = bp->b_pages[i]; 1251 1252 /* 1253 * If we hit a bogus page, fixup *all* the bogus pages 1254 * now. 1255 */ 1256 if (m == bogus_page) { 1257 poff = OFF_TO_IDX(bp->b_offset); 1258 had_bogus = 1; 1259 1260 for (j = i; j < bp->b_npages; j++) { 1261 vm_page_t mtmp; 1262 mtmp = bp->b_pages[j]; 1263 if (mtmp == bogus_page) { 1264 mtmp = vm_page_lookup(obj, poff + j); 1265 if (!mtmp) { 1266 panic("brelse: page missing\n"); 1267 } 1268 bp->b_pages[j] = mtmp; 1269 } 1270 } 1271 1272 if ((bp->b_flags & B_INVAL) == 0) { 1273 pmap_qenter( 1274 trunc_page((vm_offset_t)bp->b_data), 1275 bp->b_pages, bp->b_npages); 1276 } 1277 m = bp->b_pages[i]; 1278 } 1279 if ((bp->b_flags & B_NOCACHE) || 1280 (bp->b_ioflags & BIO_ERROR)) { 1281 int poffset = foff & PAGE_MASK; 1282 int presid = resid > (PAGE_SIZE - poffset) ? 1283 (PAGE_SIZE - poffset) : resid; 1284 1285 KASSERT(presid >= 0, ("brelse: extra page")); 1286 vm_page_lock_queues(); 1287 vm_page_set_invalid(m, poffset, presid); 1288 vm_page_unlock_queues(); 1289 if (had_bogus) 1290 printf("avoided corruption bug in bogus_page/brelse code\n"); 1291 } 1292 resid -= PAGE_SIZE - (foff & PAGE_MASK); 1293 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 1294 } 1295 VM_OBJECT_UNLOCK(obj); 1296 if (bp->b_flags & (B_INVAL | B_RELBUF)) 1297 vfs_vmio_release(bp); 1298 1299 } else if (bp->b_flags & B_VMIO) { 1300 1301 if (bp->b_flags & (B_INVAL | B_RELBUF)) { 1302 vfs_vmio_release(bp); 1303 } 1304 1305 } 1306 1307 if (BUF_REFCNT(bp) > 1) { 1308 /* do not release to free list */ 1309 BUF_UNLOCK(bp); 1310 splx(s); 1311 return; 1312 } 1313 1314 /* enqueue */ 1315 mtx_lock(&bqlock); 1316 /* Handle delayed bremfree() processing. */ 1317 if (bp->b_flags & B_REMFREE) 1318 bremfreel(bp); 1319 if (bp->b_qindex != QUEUE_NONE) 1320 panic("brelse: free buffer onto another queue???"); 1321 1322 /* buffers with no memory */ 1323 if (bp->b_bufsize == 0) { 1324 bp->b_flags |= B_INVAL; 1325 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA); 1326 if (bp->b_vflags & BV_BKGRDINPROG) 1327 panic("losing buffer 1"); 1328 if (bp->b_kvasize) { 1329 bp->b_qindex = QUEUE_EMPTYKVA; 1330 } else { 1331 bp->b_qindex = QUEUE_EMPTY; 1332 } 1333 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist); 1334 /* buffers with junk contents */ 1335 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF) || 1336 (bp->b_ioflags & BIO_ERROR)) { 1337 bp->b_flags |= B_INVAL; 1338 bp->b_xflags &= ~(BX_BKGRDWRITE | BX_ALTDATA); 1339 if (bp->b_vflags & BV_BKGRDINPROG) 1340 panic("losing buffer 2"); 1341 bp->b_qindex = QUEUE_CLEAN; 1342 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist); 1343 /* remaining buffers */ 1344 } else { 1345 if (bp->b_flags & B_DELWRI) 1346 bp->b_qindex = QUEUE_DIRTY; 1347 else 1348 bp->b_qindex = QUEUE_CLEAN; 1349 if (bp->b_flags & B_AGE) 1350 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist); 1351 else 1352 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist); 1353 } 1354 mtx_unlock(&bqlock); 1355 1356 /* 1357 * If B_INVAL and B_DELWRI is set, clear B_DELWRI. We have already 1358 * placed the buffer on the correct queue. We must also disassociate 1359 * the device and vnode for a B_INVAL buffer so gbincore() doesn't 1360 * find it. 1361 */ 1362 if (bp->b_flags & B_INVAL) { 1363 if (bp->b_flags & B_DELWRI) 1364 bundirty(bp); 1365 if (bp->b_vp) 1366 brelvp(bp); 1367 } 1368 1369 /* 1370 * Fixup numfreebuffers count. The bp is on an appropriate queue 1371 * unless locked. We then bump numfreebuffers if it is not B_DELWRI. 1372 * We've already handled the B_INVAL case ( B_DELWRI will be clear 1373 * if B_INVAL is set ). 1374 */ 1375 1376 if (!(bp->b_flags & B_DELWRI)) 1377 bufcountwakeup(); 1378 1379 /* 1380 * Something we can maybe free or reuse 1381 */ 1382 if (bp->b_bufsize || bp->b_kvasize) 1383 bufspacewakeup(); 1384 1385 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF | B_DIRECT); 1386 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY)) 1387 panic("brelse: not dirty"); 1388 /* unlock */ 1389 BUF_UNLOCK(bp); 1390 splx(s); 1391 } 1392 1393 /* 1394 * Release a buffer back to the appropriate queue but do not try to free 1395 * it. The buffer is expected to be used again soon. 1396 * 1397 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by 1398 * biodone() to requeue an async I/O on completion. It is also used when 1399 * known good buffers need to be requeued but we think we may need the data 1400 * again soon. 1401 * 1402 * XXX we should be able to leave the B_RELBUF hint set on completion. 1403 */ 1404 void 1405 bqrelse(struct buf *bp) 1406 { 1407 int s; 1408 1409 s = splbio(); 1410 1411 CTR3(KTR_BUF, "bqrelse(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 1412 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), 1413 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp)); 1414 1415 if (BUF_REFCNT(bp) > 1) { 1416 /* do not release to free list */ 1417 BUF_UNLOCK(bp); 1418 splx(s); 1419 return; 1420 } 1421 mtx_lock(&bqlock); 1422 /* Handle delayed bremfree() processing. */ 1423 if (bp->b_flags & B_REMFREE) 1424 bremfreel(bp); 1425 if (bp->b_qindex != QUEUE_NONE) 1426 panic("bqrelse: free buffer onto another queue???"); 1427 /* buffers with stale but valid contents */ 1428 if (bp->b_flags & B_DELWRI) { 1429 bp->b_qindex = QUEUE_DIRTY; 1430 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist); 1431 } else { 1432 /* 1433 * XXX This lock may not be necessary since BKGRDINPROG 1434 * cannot be set while we hold the buf lock, it can only be 1435 * cleared if it is already pending. 1436 */ 1437 BO_LOCK(bp->b_bufobj); 1438 if (!vm_page_count_severe() || bp->b_vflags & BV_BKGRDINPROG) { 1439 BO_UNLOCK(bp->b_bufobj); 1440 bp->b_qindex = QUEUE_CLEAN; 1441 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, 1442 b_freelist); 1443 } else { 1444 /* 1445 * We are too low on memory, we have to try to free 1446 * the buffer (most importantly: the wired pages 1447 * making up its backing store) *now*. 1448 */ 1449 BO_UNLOCK(bp->b_bufobj); 1450 mtx_unlock(&bqlock); 1451 splx(s); 1452 brelse(bp); 1453 return; 1454 } 1455 } 1456 mtx_unlock(&bqlock); 1457 1458 if ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI)) 1459 bufcountwakeup(); 1460 1461 /* 1462 * Something we can maybe free or reuse. 1463 */ 1464 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI)) 1465 bufspacewakeup(); 1466 1467 bp->b_flags &= ~(B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF); 1468 if ((bp->b_flags & B_DELWRI) == 0 && (bp->b_xflags & BX_VNDIRTY)) 1469 panic("bqrelse: not dirty"); 1470 /* unlock */ 1471 BUF_UNLOCK(bp); 1472 splx(s); 1473 } 1474 1475 /* Give pages used by the bp back to the VM system (where possible) */ 1476 static void 1477 vfs_vmio_release(struct buf *bp) 1478 { 1479 int i; 1480 vm_page_t m; 1481 1482 VM_OBJECT_LOCK(bp->b_bufobj->bo_object); 1483 vm_page_lock_queues(); 1484 for (i = 0; i < bp->b_npages; i++) { 1485 m = bp->b_pages[i]; 1486 bp->b_pages[i] = NULL; 1487 /* 1488 * In order to keep page LRU ordering consistent, put 1489 * everything on the inactive queue. 1490 */ 1491 vm_page_unwire(m, 0); 1492 /* 1493 * We don't mess with busy pages, it is 1494 * the responsibility of the process that 1495 * busied the pages to deal with them. 1496 */ 1497 if ((m->flags & PG_BUSY) || (m->busy != 0)) 1498 continue; 1499 1500 if (m->wire_count == 0) { 1501 /* 1502 * Might as well free the page if we can and it has 1503 * no valid data. We also free the page if the 1504 * buffer was used for direct I/O 1505 */ 1506 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && 1507 m->hold_count == 0) { 1508 pmap_remove_all(m); 1509 vm_page_free(m); 1510 } else if (bp->b_flags & B_DIRECT) { 1511 vm_page_try_to_free(m); 1512 } else if (vm_page_count_severe()) { 1513 vm_page_try_to_cache(m); 1514 } 1515 } 1516 } 1517 vm_page_unlock_queues(); 1518 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object); 1519 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages); 1520 1521 if (bp->b_bufsize) { 1522 bufspacewakeup(); 1523 bp->b_bufsize = 0; 1524 } 1525 bp->b_npages = 0; 1526 bp->b_flags &= ~B_VMIO; 1527 if (bp->b_vp) 1528 brelvp(bp); 1529 } 1530 1531 /* 1532 * Check to see if a block at a particular lbn is available for a clustered 1533 * write. 1534 */ 1535 static int 1536 vfs_bio_clcheck(struct vnode *vp, int size, daddr_t lblkno, daddr_t blkno) 1537 { 1538 struct buf *bpa; 1539 int match; 1540 1541 match = 0; 1542 1543 /* If the buf isn't in core skip it */ 1544 if ((bpa = gbincore(&vp->v_bufobj, lblkno)) == NULL) 1545 return (0); 1546 1547 /* If the buf is busy we don't want to wait for it */ 1548 if (BUF_LOCK(bpa, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) 1549 return (0); 1550 1551 /* Only cluster with valid clusterable delayed write buffers */ 1552 if ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) != 1553 (B_DELWRI | B_CLUSTEROK)) 1554 goto done; 1555 1556 if (bpa->b_bufsize != size) 1557 goto done; 1558 1559 /* 1560 * Check to see if it is in the expected place on disk and that the 1561 * block has been mapped. 1562 */ 1563 if ((bpa->b_blkno != bpa->b_lblkno) && (bpa->b_blkno == blkno)) 1564 match = 1; 1565 done: 1566 BUF_UNLOCK(bpa); 1567 return (match); 1568 } 1569 1570 /* 1571 * vfs_bio_awrite: 1572 * 1573 * Implement clustered async writes for clearing out B_DELWRI buffers. 1574 * This is much better then the old way of writing only one buffer at 1575 * a time. Note that we may not be presented with the buffers in the 1576 * correct order, so we search for the cluster in both directions. 1577 */ 1578 int 1579 vfs_bio_awrite(struct buf *bp) 1580 { 1581 int i; 1582 int j; 1583 daddr_t lblkno = bp->b_lblkno; 1584 struct vnode *vp = bp->b_vp; 1585 int s; 1586 int ncl; 1587 int nwritten; 1588 int size; 1589 int maxcl; 1590 1591 s = splbio(); 1592 /* 1593 * right now we support clustered writing only to regular files. If 1594 * we find a clusterable block we could be in the middle of a cluster 1595 * rather then at the beginning. 1596 */ 1597 if ((vp->v_type == VREG) && 1598 (vp->v_mount != 0) && /* Only on nodes that have the size info */ 1599 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) { 1600 1601 size = vp->v_mount->mnt_stat.f_iosize; 1602 maxcl = MAXPHYS / size; 1603 1604 VI_LOCK(vp); 1605 for (i = 1; i < maxcl; i++) 1606 if (vfs_bio_clcheck(vp, size, lblkno + i, 1607 bp->b_blkno + ((i * size) >> DEV_BSHIFT)) == 0) 1608 break; 1609 1610 for (j = 1; i + j <= maxcl && j <= lblkno; j++) 1611 if (vfs_bio_clcheck(vp, size, lblkno - j, 1612 bp->b_blkno - ((j * size) >> DEV_BSHIFT)) == 0) 1613 break; 1614 1615 VI_UNLOCK(vp); 1616 --j; 1617 ncl = i + j; 1618 /* 1619 * this is a possible cluster write 1620 */ 1621 if (ncl != 1) { 1622 BUF_UNLOCK(bp); 1623 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl); 1624 splx(s); 1625 return nwritten; 1626 } 1627 } 1628 1629 bremfree(bp); 1630 bp->b_flags |= B_ASYNC; 1631 1632 splx(s); 1633 /* 1634 * default (old) behavior, writing out only one block 1635 * 1636 * XXX returns b_bufsize instead of b_bcount for nwritten? 1637 */ 1638 nwritten = bp->b_bufsize; 1639 (void) bwrite(bp); 1640 1641 return nwritten; 1642 } 1643 1644 /* 1645 * getnewbuf: 1646 * 1647 * Find and initialize a new buffer header, freeing up existing buffers 1648 * in the bufqueues as necessary. The new buffer is returned locked. 1649 * 1650 * Important: B_INVAL is not set. If the caller wishes to throw the 1651 * buffer away, the caller must set B_INVAL prior to calling brelse(). 1652 * 1653 * We block if: 1654 * We have insufficient buffer headers 1655 * We have insufficient buffer space 1656 * buffer_map is too fragmented ( space reservation fails ) 1657 * If we have to flush dirty buffers ( but we try to avoid this ) 1658 * 1659 * To avoid VFS layer recursion we do not flush dirty buffers ourselves. 1660 * Instead we ask the buf daemon to do it for us. We attempt to 1661 * avoid piecemeal wakeups of the pageout daemon. 1662 */ 1663 1664 static struct buf * 1665 getnewbuf(int slpflag, int slptimeo, int size, int maxsize) 1666 { 1667 struct buf *bp; 1668 struct buf *nbp; 1669 int defrag = 0; 1670 int nqindex; 1671 static int flushingbufs; 1672 1673 /* 1674 * We can't afford to block since we might be holding a vnode lock, 1675 * which may prevent system daemons from running. We deal with 1676 * low-memory situations by proactively returning memory and running 1677 * async I/O rather then sync I/O. 1678 */ 1679 1680 atomic_add_int(&getnewbufcalls, 1); 1681 atomic_subtract_int(&getnewbufrestarts, 1); 1682 restart: 1683 atomic_add_int(&getnewbufrestarts, 1); 1684 1685 /* 1686 * Setup for scan. If we do not have enough free buffers, 1687 * we setup a degenerate case that immediately fails. Note 1688 * that if we are specially marked process, we are allowed to 1689 * dip into our reserves. 1690 * 1691 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN 1692 * 1693 * We start with EMPTYKVA. If the list is empty we backup to EMPTY. 1694 * However, there are a number of cases (defragging, reusing, ...) 1695 * where we cannot backup. 1696 */ 1697 mtx_lock(&bqlock); 1698 nqindex = QUEUE_EMPTYKVA; 1699 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]); 1700 1701 if (nbp == NULL) { 1702 /* 1703 * If no EMPTYKVA buffers and we are either 1704 * defragging or reusing, locate a CLEAN buffer 1705 * to free or reuse. If bufspace useage is low 1706 * skip this step so we can allocate a new buffer. 1707 */ 1708 if (defrag || bufspace >= lobufspace) { 1709 nqindex = QUEUE_CLEAN; 1710 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]); 1711 } 1712 1713 /* 1714 * If we could not find or were not allowed to reuse a 1715 * CLEAN buffer, check to see if it is ok to use an EMPTY 1716 * buffer. We can only use an EMPTY buffer if allocating 1717 * its KVA would not otherwise run us out of buffer space. 1718 */ 1719 if (nbp == NULL && defrag == 0 && 1720 bufspace + maxsize < hibufspace) { 1721 nqindex = QUEUE_EMPTY; 1722 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]); 1723 } 1724 } 1725 1726 /* 1727 * Run scan, possibly freeing data and/or kva mappings on the fly 1728 * depending. 1729 */ 1730 1731 while ((bp = nbp) != NULL) { 1732 int qindex = nqindex; 1733 1734 /* 1735 * Calculate next bp ( we can only use it if we do not block 1736 * or do other fancy things ). 1737 */ 1738 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) { 1739 switch(qindex) { 1740 case QUEUE_EMPTY: 1741 nqindex = QUEUE_EMPTYKVA; 1742 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]))) 1743 break; 1744 /* FALLTHROUGH */ 1745 case QUEUE_EMPTYKVA: 1746 nqindex = QUEUE_CLEAN; 1747 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]))) 1748 break; 1749 /* FALLTHROUGH */ 1750 case QUEUE_CLEAN: 1751 /* 1752 * nbp is NULL. 1753 */ 1754 break; 1755 } 1756 } 1757 /* 1758 * If we are defragging then we need a buffer with 1759 * b_kvasize != 0. XXX this situation should no longer 1760 * occur, if defrag is non-zero the buffer's b_kvasize 1761 * should also be non-zero at this point. XXX 1762 */ 1763 if (defrag && bp->b_kvasize == 0) { 1764 printf("Warning: defrag empty buffer %p\n", bp); 1765 continue; 1766 } 1767 1768 /* 1769 * Start freeing the bp. This is somewhat involved. nbp 1770 * remains valid only for QUEUE_EMPTY[KVA] bp's. 1771 */ 1772 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) 1773 continue; 1774 if (bp->b_vp) { 1775 BO_LOCK(bp->b_bufobj); 1776 if (bp->b_vflags & BV_BKGRDINPROG) { 1777 BO_UNLOCK(bp->b_bufobj); 1778 BUF_UNLOCK(bp); 1779 continue; 1780 } 1781 BO_UNLOCK(bp->b_bufobj); 1782 } 1783 CTR6(KTR_BUF, 1784 "getnewbuf(%p) vp %p flags %X kvasize %d bufsize %d " 1785 "queue %d (recycling)", bp, bp->b_vp, bp->b_flags, 1786 bp->b_kvasize, bp->b_bufsize, qindex); 1787 1788 /* 1789 * Sanity Checks 1790 */ 1791 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp)); 1792 1793 /* 1794 * Note: we no longer distinguish between VMIO and non-VMIO 1795 * buffers. 1796 */ 1797 1798 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex)); 1799 1800 bremfreel(bp); 1801 mtx_unlock(&bqlock); 1802 1803 if (qindex == QUEUE_CLEAN) { 1804 if (bp->b_flags & B_VMIO) { 1805 bp->b_flags &= ~B_ASYNC; 1806 vfs_vmio_release(bp); 1807 } 1808 if (bp->b_vp) 1809 brelvp(bp); 1810 } 1811 1812 /* 1813 * NOTE: nbp is now entirely invalid. We can only restart 1814 * the scan from this point on. 1815 * 1816 * Get the rest of the buffer freed up. b_kva* is still 1817 * valid after this operation. 1818 */ 1819 1820 if (bp->b_rcred != NOCRED) { 1821 crfree(bp->b_rcred); 1822 bp->b_rcred = NOCRED; 1823 } 1824 if (bp->b_wcred != NOCRED) { 1825 crfree(bp->b_wcred); 1826 bp->b_wcred = NOCRED; 1827 } 1828 if (LIST_FIRST(&bp->b_dep) != NULL) 1829 buf_deallocate(bp); 1830 if (bp->b_vflags & BV_BKGRDINPROG) 1831 panic("losing buffer 3"); 1832 1833 if (bp->b_bufsize) 1834 allocbuf(bp, 0); 1835 1836 bp->b_flags = 0; 1837 bp->b_ioflags = 0; 1838 bp->b_xflags = 0; 1839 bp->b_vflags = 0; 1840 bp->b_vp = NULL; 1841 bp->b_blkno = bp->b_lblkno = 0; 1842 bp->b_offset = NOOFFSET; 1843 bp->b_iodone = 0; 1844 bp->b_error = 0; 1845 bp->b_resid = 0; 1846 bp->b_bcount = 0; 1847 bp->b_npages = 0; 1848 bp->b_dirtyoff = bp->b_dirtyend = 0; 1849 bp->b_bufobj = NULL; 1850 1851 LIST_INIT(&bp->b_dep); 1852 1853 /* 1854 * If we are defragging then free the buffer. 1855 */ 1856 if (defrag) { 1857 bp->b_flags |= B_INVAL; 1858 bfreekva(bp); 1859 brelse(bp); 1860 defrag = 0; 1861 goto restart; 1862 } 1863 1864 /* 1865 * If we are overcomitted then recover the buffer and its 1866 * KVM space. This occurs in rare situations when multiple 1867 * processes are blocked in getnewbuf() or allocbuf(). 1868 */ 1869 if (bufspace >= hibufspace) 1870 flushingbufs = 1; 1871 if (flushingbufs && bp->b_kvasize != 0) { 1872 bp->b_flags |= B_INVAL; 1873 bfreekva(bp); 1874 brelse(bp); 1875 goto restart; 1876 } 1877 if (bufspace < lobufspace) 1878 flushingbufs = 0; 1879 break; 1880 } 1881 1882 /* 1883 * If we exhausted our list, sleep as appropriate. We may have to 1884 * wakeup various daemons and write out some dirty buffers. 1885 * 1886 * Generally we are sleeping due to insufficient buffer space. 1887 */ 1888 1889 if (bp == NULL) { 1890 int flags; 1891 char *waitmsg; 1892 1893 mtx_unlock(&bqlock); 1894 if (defrag) { 1895 flags = VFS_BIO_NEED_BUFSPACE; 1896 waitmsg = "nbufkv"; 1897 } else if (bufspace >= hibufspace) { 1898 waitmsg = "nbufbs"; 1899 flags = VFS_BIO_NEED_BUFSPACE; 1900 } else { 1901 waitmsg = "newbuf"; 1902 flags = VFS_BIO_NEED_ANY; 1903 } 1904 1905 bd_speedup(); /* heeeelp */ 1906 1907 mtx_lock(&nblock); 1908 needsbuffer |= flags; 1909 while (needsbuffer & flags) { 1910 if (msleep(&needsbuffer, &nblock, 1911 (PRIBIO + 4) | slpflag, waitmsg, slptimeo)) { 1912 mtx_unlock(&nblock); 1913 return (NULL); 1914 } 1915 } 1916 mtx_unlock(&nblock); 1917 } else { 1918 /* 1919 * We finally have a valid bp. We aren't quite out of the 1920 * woods, we still have to reserve kva space. In order 1921 * to keep fragmentation sane we only allocate kva in 1922 * BKVASIZE chunks. 1923 */ 1924 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK; 1925 1926 if (maxsize != bp->b_kvasize) { 1927 vm_offset_t addr = 0; 1928 1929 bfreekva(bp); 1930 1931 if (vm_map_findspace(buffer_map, 1932 vm_map_min(buffer_map), maxsize, &addr)) { 1933 /* 1934 * Uh oh. Buffer map is to fragmented. We 1935 * must defragment the map. 1936 */ 1937 atomic_add_int(&bufdefragcnt, 1); 1938 defrag = 1; 1939 bp->b_flags |= B_INVAL; 1940 brelse(bp); 1941 goto restart; 1942 } 1943 if (addr) { 1944 vm_map_insert(buffer_map, NULL, 0, 1945 addr, addr + maxsize, 1946 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT); 1947 1948 bp->b_kvabase = (caddr_t) addr; 1949 bp->b_kvasize = maxsize; 1950 atomic_add_int(&bufspace, bp->b_kvasize); 1951 atomic_add_int(&bufreusecnt, 1); 1952 } 1953 } 1954 bp->b_saveaddr = bp->b_kvabase; 1955 bp->b_data = bp->b_saveaddr; 1956 } 1957 return(bp); 1958 } 1959 1960 /* 1961 * buf_daemon: 1962 * 1963 * buffer flushing daemon. Buffers are normally flushed by the 1964 * update daemon but if it cannot keep up this process starts to 1965 * take the load in an attempt to prevent getnewbuf() from blocking. 1966 */ 1967 1968 static struct kproc_desc buf_kp = { 1969 "bufdaemon", 1970 buf_daemon, 1971 &bufdaemonproc 1972 }; 1973 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp) 1974 1975 static void 1976 buf_daemon() 1977 { 1978 int s; 1979 1980 mtx_lock(&Giant); 1981 1982 /* 1983 * This process needs to be suspended prior to shutdown sync. 1984 */ 1985 EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, bufdaemonproc, 1986 SHUTDOWN_PRI_LAST); 1987 1988 /* 1989 * This process is allowed to take the buffer cache to the limit 1990 */ 1991 s = splbio(); 1992 mtx_lock(&bdlock); 1993 1994 for (;;) { 1995 bd_request = 0; 1996 mtx_unlock(&bdlock); 1997 1998 kthread_suspend_check(bufdaemonproc); 1999 2000 /* 2001 * Do the flush. Limit the amount of in-transit I/O we 2002 * allow to build up, otherwise we would completely saturate 2003 * the I/O system. Wakeup any waiting processes before we 2004 * normally would so they can run in parallel with our drain. 2005 */ 2006 while (numdirtybuffers > lodirtybuffers) { 2007 if (flushbufqueues(0) == 0) { 2008 /* 2009 * Could not find any buffers without rollback 2010 * dependencies, so just write the first one 2011 * in the hopes of eventually making progress. 2012 */ 2013 flushbufqueues(1); 2014 break; 2015 } 2016 waitrunningbufspace(); 2017 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2); 2018 } 2019 2020 /* 2021 * Only clear bd_request if we have reached our low water 2022 * mark. The buf_daemon normally waits 1 second and 2023 * then incrementally flushes any dirty buffers that have 2024 * built up, within reason. 2025 * 2026 * If we were unable to hit our low water mark and couldn't 2027 * find any flushable buffers, we sleep half a second. 2028 * Otherwise we loop immediately. 2029 */ 2030 mtx_lock(&bdlock); 2031 if (numdirtybuffers <= lodirtybuffers) { 2032 /* 2033 * We reached our low water mark, reset the 2034 * request and sleep until we are needed again. 2035 * The sleep is just so the suspend code works. 2036 */ 2037 bd_request = 0; 2038 msleep(&bd_request, &bdlock, PVM, "psleep", hz); 2039 } else { 2040 /* 2041 * We couldn't find any flushable dirty buffers but 2042 * still have too many dirty buffers, we 2043 * have to sleep and try again. (rare) 2044 */ 2045 msleep(&bd_request, &bdlock, PVM, "qsleep", hz / 10); 2046 } 2047 } 2048 } 2049 2050 /* 2051 * flushbufqueues: 2052 * 2053 * Try to flush a buffer in the dirty queue. We must be careful to 2054 * free up B_INVAL buffers instead of write them, which NFS is 2055 * particularly sensitive to. 2056 */ 2057 static int flushwithdeps = 0; 2058 SYSCTL_INT(_vfs, OID_AUTO, flushwithdeps, CTLFLAG_RW, &flushwithdeps, 2059 0, "Number of buffers flushed with dependecies that require rollbacks"); 2060 2061 static int 2062 flushbufqueues(int flushdeps) 2063 { 2064 struct thread *td = curthread; 2065 struct vnode *vp; 2066 struct mount *mp; 2067 struct buf *bp; 2068 int hasdeps; 2069 2070 mtx_lock(&bqlock); 2071 TAILQ_FOREACH(bp, &bufqueues[QUEUE_DIRTY], b_freelist) { 2072 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) 2073 continue; 2074 BO_LOCK(bp->b_bufobj); 2075 if ((bp->b_vflags & BV_BKGRDINPROG) != 0 || 2076 (bp->b_flags & B_DELWRI) == 0) { 2077 BO_UNLOCK(bp->b_bufobj); 2078 BUF_UNLOCK(bp); 2079 continue; 2080 } 2081 BO_UNLOCK(bp->b_bufobj); 2082 if (bp->b_flags & B_INVAL) { 2083 bremfreel(bp); 2084 mtx_unlock(&bqlock); 2085 brelse(bp); 2086 return (1); 2087 } 2088 2089 if (LIST_FIRST(&bp->b_dep) != NULL && buf_countdeps(bp, 0)) { 2090 if (flushdeps == 0) { 2091 BUF_UNLOCK(bp); 2092 continue; 2093 } 2094 hasdeps = 1; 2095 } else 2096 hasdeps = 0; 2097 /* 2098 * We must hold the lock on a vnode before writing 2099 * one of its buffers. Otherwise we may confuse, or 2100 * in the case of a snapshot vnode, deadlock the 2101 * system. 2102 * 2103 * The lock order here is the reverse of the normal 2104 * of vnode followed by buf lock. This is ok because 2105 * the NOWAIT will prevent deadlock. 2106 */ 2107 vp = bp->b_vp; 2108 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) { 2109 BUF_UNLOCK(bp); 2110 continue; 2111 } 2112 if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) == 0) { 2113 mtx_unlock(&bqlock); 2114 CTR3(KTR_BUF, "flushbufqueue(%p) vp %p flags %X", 2115 bp, bp->b_vp, bp->b_flags); 2116 vfs_bio_awrite(bp); 2117 vn_finished_write(mp); 2118 VOP_UNLOCK(vp, 0, td); 2119 flushwithdeps += hasdeps; 2120 return (1); 2121 } 2122 vn_finished_write(mp); 2123 BUF_UNLOCK(bp); 2124 } 2125 mtx_unlock(&bqlock); 2126 return (0); 2127 } 2128 2129 /* 2130 * Check to see if a block is currently memory resident. 2131 */ 2132 struct buf * 2133 incore(struct bufobj *bo, daddr_t blkno) 2134 { 2135 struct buf *bp; 2136 2137 int s = splbio(); 2138 BO_LOCK(bo); 2139 bp = gbincore(bo, blkno); 2140 BO_UNLOCK(bo); 2141 splx(s); 2142 return (bp); 2143 } 2144 2145 /* 2146 * Returns true if no I/O is needed to access the 2147 * associated VM object. This is like incore except 2148 * it also hunts around in the VM system for the data. 2149 */ 2150 2151 static int 2152 inmem(struct vnode * vp, daddr_t blkno) 2153 { 2154 vm_object_t obj; 2155 vm_offset_t toff, tinc, size; 2156 vm_page_t m; 2157 vm_ooffset_t off; 2158 2159 ASSERT_VOP_LOCKED(vp, "inmem"); 2160 2161 if (incore(&vp->v_bufobj, blkno)) 2162 return 1; 2163 if (vp->v_mount == NULL) 2164 return 0; 2165 obj = vp->v_object; 2166 if (obj == NULL) 2167 return (0); 2168 2169 size = PAGE_SIZE; 2170 if (size > vp->v_mount->mnt_stat.f_iosize) 2171 size = vp->v_mount->mnt_stat.f_iosize; 2172 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize; 2173 2174 VM_OBJECT_LOCK(obj); 2175 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) { 2176 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff)); 2177 if (!m) 2178 goto notinmem; 2179 tinc = size; 2180 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK)) 2181 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK); 2182 if (vm_page_is_valid(m, 2183 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0) 2184 goto notinmem; 2185 } 2186 VM_OBJECT_UNLOCK(obj); 2187 return 1; 2188 2189 notinmem: 2190 VM_OBJECT_UNLOCK(obj); 2191 return (0); 2192 } 2193 2194 /* 2195 * vfs_setdirty: 2196 * 2197 * Sets the dirty range for a buffer based on the status of the dirty 2198 * bits in the pages comprising the buffer. 2199 * 2200 * The range is limited to the size of the buffer. 2201 * 2202 * This routine is primarily used by NFS, but is generalized for the 2203 * B_VMIO case. 2204 */ 2205 static void 2206 vfs_setdirty(struct buf *bp) 2207 { 2208 int i; 2209 vm_object_t object; 2210 2211 /* 2212 * Degenerate case - empty buffer 2213 */ 2214 2215 if (bp->b_bufsize == 0) 2216 return; 2217 2218 /* 2219 * We qualify the scan for modified pages on whether the 2220 * object has been flushed yet. The OBJ_WRITEABLE flag 2221 * is not cleared simply by protecting pages off. 2222 */ 2223 2224 if ((bp->b_flags & B_VMIO) == 0) 2225 return; 2226 2227 object = bp->b_pages[0]->object; 2228 VM_OBJECT_LOCK(object); 2229 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY)) 2230 printf("Warning: object %p writeable but not mightbedirty\n", object); 2231 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY)) 2232 printf("Warning: object %p mightbedirty but not writeable\n", object); 2233 2234 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) { 2235 vm_offset_t boffset; 2236 vm_offset_t eoffset; 2237 2238 vm_page_lock_queues(); 2239 /* 2240 * test the pages to see if they have been modified directly 2241 * by users through the VM system. 2242 */ 2243 for (i = 0; i < bp->b_npages; i++) 2244 vm_page_test_dirty(bp->b_pages[i]); 2245 2246 /* 2247 * Calculate the encompassing dirty range, boffset and eoffset, 2248 * (eoffset - boffset) bytes. 2249 */ 2250 2251 for (i = 0; i < bp->b_npages; i++) { 2252 if (bp->b_pages[i]->dirty) 2253 break; 2254 } 2255 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK); 2256 2257 for (i = bp->b_npages - 1; i >= 0; --i) { 2258 if (bp->b_pages[i]->dirty) { 2259 break; 2260 } 2261 } 2262 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK); 2263 2264 vm_page_unlock_queues(); 2265 /* 2266 * Fit it to the buffer. 2267 */ 2268 2269 if (eoffset > bp->b_bcount) 2270 eoffset = bp->b_bcount; 2271 2272 /* 2273 * If we have a good dirty range, merge with the existing 2274 * dirty range. 2275 */ 2276 2277 if (boffset < eoffset) { 2278 if (bp->b_dirtyoff > boffset) 2279 bp->b_dirtyoff = boffset; 2280 if (bp->b_dirtyend < eoffset) 2281 bp->b_dirtyend = eoffset; 2282 } 2283 } 2284 VM_OBJECT_UNLOCK(object); 2285 } 2286 2287 /* 2288 * getblk: 2289 * 2290 * Get a block given a specified block and offset into a file/device. 2291 * The buffers B_DONE bit will be cleared on return, making it almost 2292 * ready for an I/O initiation. B_INVAL may or may not be set on 2293 * return. The caller should clear B_INVAL prior to initiating a 2294 * READ. 2295 * 2296 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for 2297 * an existing buffer. 2298 * 2299 * For a VMIO buffer, B_CACHE is modified according to the backing VM. 2300 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set 2301 * and then cleared based on the backing VM. If the previous buffer is 2302 * non-0-sized but invalid, B_CACHE will be cleared. 2303 * 2304 * If getblk() must create a new buffer, the new buffer is returned with 2305 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which 2306 * case it is returned with B_INVAL clear and B_CACHE set based on the 2307 * backing VM. 2308 * 2309 * getblk() also forces a bwrite() for any B_DELWRI buffer whos 2310 * B_CACHE bit is clear. 2311 * 2312 * What this means, basically, is that the caller should use B_CACHE to 2313 * determine whether the buffer is fully valid or not and should clear 2314 * B_INVAL prior to issuing a read. If the caller intends to validate 2315 * the buffer by loading its data area with something, the caller needs 2316 * to clear B_INVAL. If the caller does this without issuing an I/O, 2317 * the caller should set B_CACHE ( as an optimization ), else the caller 2318 * should issue the I/O and biodone() will set B_CACHE if the I/O was 2319 * a write attempt or if it was a successfull read. If the caller 2320 * intends to issue a READ, the caller must clear B_INVAL and BIO_ERROR 2321 * prior to issuing the READ. biodone() will *not* clear B_INVAL. 2322 */ 2323 struct buf * 2324 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo, 2325 int flags) 2326 { 2327 struct buf *bp; 2328 struct bufobj *bo; 2329 int s; 2330 int error; 2331 2332 CTR3(KTR_BUF, "getblk(%p, %ld, %d)", vp, (long)blkno, size); 2333 ASSERT_VOP_LOCKED(vp, "getblk"); 2334 if (size > MAXBSIZE) 2335 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE); 2336 2337 bo = &vp->v_bufobj; 2338 s = splbio(); 2339 loop: 2340 /* 2341 * Block if we are low on buffers. Certain processes are allowed 2342 * to completely exhaust the buffer cache. 2343 * 2344 * If this check ever becomes a bottleneck it may be better to 2345 * move it into the else, when gbincore() fails. At the moment 2346 * it isn't a problem. 2347 * 2348 * XXX remove if 0 sections (clean this up after its proven) 2349 */ 2350 if (numfreebuffers == 0) { 2351 if (curthread == PCPU_GET(idlethread)) 2352 return NULL; 2353 mtx_lock(&nblock); 2354 needsbuffer |= VFS_BIO_NEED_ANY; 2355 mtx_unlock(&nblock); 2356 } 2357 2358 VI_LOCK(vp); 2359 bp = gbincore(bo, blkno); 2360 if (bp != NULL) { 2361 int lockflags; 2362 /* 2363 * Buffer is in-core. If the buffer is not busy, it must 2364 * be on a queue. 2365 */ 2366 lockflags = LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK; 2367 2368 if (flags & GB_LOCK_NOWAIT) 2369 lockflags |= LK_NOWAIT; 2370 2371 error = BUF_TIMELOCK(bp, lockflags, 2372 VI_MTX(vp), "getblk", slpflag, slptimeo); 2373 2374 /* 2375 * If we slept and got the lock we have to restart in case 2376 * the buffer changed identities. 2377 */ 2378 if (error == ENOLCK) 2379 goto loop; 2380 /* We timed out or were interrupted. */ 2381 else if (error) 2382 return (NULL); 2383 2384 /* 2385 * The buffer is locked. B_CACHE is cleared if the buffer is 2386 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set 2387 * and for a VMIO buffer B_CACHE is adjusted according to the 2388 * backing VM cache. 2389 */ 2390 if (bp->b_flags & B_INVAL) 2391 bp->b_flags &= ~B_CACHE; 2392 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0) 2393 bp->b_flags |= B_CACHE; 2394 bremfree(bp); 2395 2396 /* 2397 * check for size inconsistancies for non-VMIO case. 2398 */ 2399 2400 if (bp->b_bcount != size) { 2401 if ((bp->b_flags & B_VMIO) == 0 || 2402 (size > bp->b_kvasize)) { 2403 if (bp->b_flags & B_DELWRI) { 2404 bp->b_flags |= B_NOCACHE; 2405 bwrite(bp); 2406 } else { 2407 if ((bp->b_flags & B_VMIO) && 2408 (LIST_FIRST(&bp->b_dep) == NULL)) { 2409 bp->b_flags |= B_RELBUF; 2410 brelse(bp); 2411 } else { 2412 bp->b_flags |= B_NOCACHE; 2413 bwrite(bp); 2414 } 2415 } 2416 goto loop; 2417 } 2418 } 2419 2420 /* 2421 * If the size is inconsistant in the VMIO case, we can resize 2422 * the buffer. This might lead to B_CACHE getting set or 2423 * cleared. If the size has not changed, B_CACHE remains 2424 * unchanged from its previous state. 2425 */ 2426 2427 if (bp->b_bcount != size) 2428 allocbuf(bp, size); 2429 2430 KASSERT(bp->b_offset != NOOFFSET, 2431 ("getblk: no buffer offset")); 2432 2433 /* 2434 * A buffer with B_DELWRI set and B_CACHE clear must 2435 * be committed before we can return the buffer in 2436 * order to prevent the caller from issuing a read 2437 * ( due to B_CACHE not being set ) and overwriting 2438 * it. 2439 * 2440 * Most callers, including NFS and FFS, need this to 2441 * operate properly either because they assume they 2442 * can issue a read if B_CACHE is not set, or because 2443 * ( for example ) an uncached B_DELWRI might loop due 2444 * to softupdates re-dirtying the buffer. In the latter 2445 * case, B_CACHE is set after the first write completes, 2446 * preventing further loops. 2447 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE 2448 * above while extending the buffer, we cannot allow the 2449 * buffer to remain with B_CACHE set after the write 2450 * completes or it will represent a corrupt state. To 2451 * deal with this we set B_NOCACHE to scrap the buffer 2452 * after the write. 2453 * 2454 * We might be able to do something fancy, like setting 2455 * B_CACHE in bwrite() except if B_DELWRI is already set, 2456 * so the below call doesn't set B_CACHE, but that gets real 2457 * confusing. This is much easier. 2458 */ 2459 2460 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) { 2461 bp->b_flags |= B_NOCACHE; 2462 bwrite(bp); 2463 goto loop; 2464 } 2465 2466 splx(s); 2467 bp->b_flags &= ~B_DONE; 2468 } else { 2469 int bsize, maxsize, vmio; 2470 off_t offset; 2471 2472 /* 2473 * Buffer is not in-core, create new buffer. The buffer 2474 * returned by getnewbuf() is locked. Note that the returned 2475 * buffer is also considered valid (not marked B_INVAL). 2476 */ 2477 VI_UNLOCK(vp); 2478 /* 2479 * If the user does not want us to create the buffer, bail out 2480 * here. 2481 */ 2482 if (flags & GB_NOCREAT) { 2483 splx(s); 2484 return NULL; 2485 } 2486 2487 bsize = bo->bo_bsize; 2488 offset = blkno * bsize; 2489 vmio = vp->v_object != NULL; 2490 maxsize = vmio ? size + (offset & PAGE_MASK) : size; 2491 maxsize = imax(maxsize, bsize); 2492 2493 bp = getnewbuf(slpflag, slptimeo, size, maxsize); 2494 if (bp == NULL) { 2495 if (slpflag || slptimeo) { 2496 splx(s); 2497 return NULL; 2498 } 2499 goto loop; 2500 } 2501 2502 /* 2503 * This code is used to make sure that a buffer is not 2504 * created while the getnewbuf routine is blocked. 2505 * This can be a problem whether the vnode is locked or not. 2506 * If the buffer is created out from under us, we have to 2507 * throw away the one we just created. There is now window 2508 * race because we are safely running at splbio() from the 2509 * point of the duplicate buffer creation through to here, 2510 * and we've locked the buffer. 2511 * 2512 * Note: this must occur before we associate the buffer 2513 * with the vp especially considering limitations in 2514 * the splay tree implementation when dealing with duplicate 2515 * lblkno's. 2516 */ 2517 BO_LOCK(bo); 2518 if (gbincore(bo, blkno)) { 2519 BO_UNLOCK(bo); 2520 bp->b_flags |= B_INVAL; 2521 brelse(bp); 2522 goto loop; 2523 } 2524 2525 /* 2526 * Insert the buffer into the hash, so that it can 2527 * be found by incore. 2528 */ 2529 bp->b_blkno = bp->b_lblkno = blkno; 2530 bp->b_offset = offset; 2531 2532 bgetvp(vp, bp); 2533 BO_UNLOCK(bo); 2534 2535 /* 2536 * set B_VMIO bit. allocbuf() the buffer bigger. Since the 2537 * buffer size starts out as 0, B_CACHE will be set by 2538 * allocbuf() for the VMIO case prior to it testing the 2539 * backing store for validity. 2540 */ 2541 2542 if (vmio) { 2543 bp->b_flags |= B_VMIO; 2544 #if defined(VFS_BIO_DEBUG) 2545 if (vn_canvmio(vp) != TRUE) 2546 printf("getblk: VMIO on vnode type %d\n", 2547 vp->v_type); 2548 #endif 2549 KASSERT(vp->v_object == bp->b_bufobj->bo_object, 2550 ("ARGH! different b_bufobj->bo_object %p %p %p\n", 2551 bp, vp->v_object, bp->b_bufobj->bo_object)); 2552 } else { 2553 bp->b_flags &= ~B_VMIO; 2554 KASSERT(bp->b_bufobj->bo_object == NULL, 2555 ("ARGH! has b_bufobj->bo_object %p %p\n", 2556 bp, bp->b_bufobj->bo_object)); 2557 } 2558 2559 allocbuf(bp, size); 2560 2561 splx(s); 2562 bp->b_flags &= ~B_DONE; 2563 } 2564 CTR4(KTR_BUF, "getblk(%p, %ld, %d) = %p", vp, (long)blkno, size, bp); 2565 KASSERT(BUF_REFCNT(bp) == 1, ("getblk: bp %p not locked",bp)); 2566 KASSERT(bp->b_bufobj == bo, 2567 ("wrong b_bufobj %p should be %p", bp->b_bufobj, bo)); 2568 return (bp); 2569 } 2570 2571 /* 2572 * Get an empty, disassociated buffer of given size. The buffer is initially 2573 * set to B_INVAL. 2574 */ 2575 struct buf * 2576 geteblk(int size) 2577 { 2578 struct buf *bp; 2579 int s; 2580 int maxsize; 2581 2582 maxsize = (size + BKVAMASK) & ~BKVAMASK; 2583 2584 s = splbio(); 2585 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0) 2586 continue; 2587 splx(s); 2588 allocbuf(bp, size); 2589 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */ 2590 KASSERT(BUF_REFCNT(bp) == 1, ("geteblk: bp %p not locked",bp)); 2591 return (bp); 2592 } 2593 2594 2595 /* 2596 * This code constitutes the buffer memory from either anonymous system 2597 * memory (in the case of non-VMIO operations) or from an associated 2598 * VM object (in the case of VMIO operations). This code is able to 2599 * resize a buffer up or down. 2600 * 2601 * Note that this code is tricky, and has many complications to resolve 2602 * deadlock or inconsistant data situations. Tread lightly!!! 2603 * There are B_CACHE and B_DELWRI interactions that must be dealt with by 2604 * the caller. Calling this code willy nilly can result in the loss of data. 2605 * 2606 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with 2607 * B_CACHE for the non-VMIO case. 2608 */ 2609 2610 int 2611 allocbuf(struct buf *bp, int size) 2612 { 2613 int newbsize, mbsize; 2614 int i; 2615 2616 if (BUF_REFCNT(bp) == 0) 2617 panic("allocbuf: buffer not busy"); 2618 2619 if (bp->b_kvasize < size) 2620 panic("allocbuf: buffer too small"); 2621 2622 if ((bp->b_flags & B_VMIO) == 0) { 2623 caddr_t origbuf; 2624 int origbufsize; 2625 /* 2626 * Just get anonymous memory from the kernel. Don't 2627 * mess with B_CACHE. 2628 */ 2629 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1); 2630 if (bp->b_flags & B_MALLOC) 2631 newbsize = mbsize; 2632 else 2633 newbsize = round_page(size); 2634 2635 if (newbsize < bp->b_bufsize) { 2636 /* 2637 * malloced buffers are not shrunk 2638 */ 2639 if (bp->b_flags & B_MALLOC) { 2640 if (newbsize) { 2641 bp->b_bcount = size; 2642 } else { 2643 free(bp->b_data, M_BIOBUF); 2644 if (bp->b_bufsize) { 2645 atomic_subtract_int( 2646 &bufmallocspace, 2647 bp->b_bufsize); 2648 bufspacewakeup(); 2649 bp->b_bufsize = 0; 2650 } 2651 bp->b_saveaddr = bp->b_kvabase; 2652 bp->b_data = bp->b_saveaddr; 2653 bp->b_bcount = 0; 2654 bp->b_flags &= ~B_MALLOC; 2655 } 2656 return 1; 2657 } 2658 vm_hold_free_pages( 2659 bp, 2660 (vm_offset_t) bp->b_data + newbsize, 2661 (vm_offset_t) bp->b_data + bp->b_bufsize); 2662 } else if (newbsize > bp->b_bufsize) { 2663 /* 2664 * We only use malloced memory on the first allocation. 2665 * and revert to page-allocated memory when the buffer 2666 * grows. 2667 */ 2668 /* 2669 * There is a potential smp race here that could lead 2670 * to bufmallocspace slightly passing the max. It 2671 * is probably extremely rare and not worth worrying 2672 * over. 2673 */ 2674 if ( (bufmallocspace < maxbufmallocspace) && 2675 (bp->b_bufsize == 0) && 2676 (mbsize <= PAGE_SIZE/2)) { 2677 2678 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK); 2679 bp->b_bufsize = mbsize; 2680 bp->b_bcount = size; 2681 bp->b_flags |= B_MALLOC; 2682 atomic_add_int(&bufmallocspace, mbsize); 2683 return 1; 2684 } 2685 origbuf = NULL; 2686 origbufsize = 0; 2687 /* 2688 * If the buffer is growing on its other-than-first allocation, 2689 * then we revert to the page-allocation scheme. 2690 */ 2691 if (bp->b_flags & B_MALLOC) { 2692 origbuf = bp->b_data; 2693 origbufsize = bp->b_bufsize; 2694 bp->b_data = bp->b_kvabase; 2695 if (bp->b_bufsize) { 2696 atomic_subtract_int(&bufmallocspace, 2697 bp->b_bufsize); 2698 bufspacewakeup(); 2699 bp->b_bufsize = 0; 2700 } 2701 bp->b_flags &= ~B_MALLOC; 2702 newbsize = round_page(newbsize); 2703 } 2704 vm_hold_load_pages( 2705 bp, 2706 (vm_offset_t) bp->b_data + bp->b_bufsize, 2707 (vm_offset_t) bp->b_data + newbsize); 2708 if (origbuf) { 2709 bcopy(origbuf, bp->b_data, origbufsize); 2710 free(origbuf, M_BIOBUF); 2711 } 2712 } 2713 } else { 2714 int desiredpages; 2715 2716 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1); 2717 desiredpages = (size == 0) ? 0 : 2718 num_pages((bp->b_offset & PAGE_MASK) + newbsize); 2719 2720 if (bp->b_flags & B_MALLOC) 2721 panic("allocbuf: VMIO buffer can't be malloced"); 2722 /* 2723 * Set B_CACHE initially if buffer is 0 length or will become 2724 * 0-length. 2725 */ 2726 if (size == 0 || bp->b_bufsize == 0) 2727 bp->b_flags |= B_CACHE; 2728 2729 if (newbsize < bp->b_bufsize) { 2730 /* 2731 * DEV_BSIZE aligned new buffer size is less then the 2732 * DEV_BSIZE aligned existing buffer size. Figure out 2733 * if we have to remove any pages. 2734 */ 2735 if (desiredpages < bp->b_npages) { 2736 vm_page_t m; 2737 2738 VM_OBJECT_LOCK(bp->b_bufobj->bo_object); 2739 vm_page_lock_queues(); 2740 for (i = desiredpages; i < bp->b_npages; i++) { 2741 /* 2742 * the page is not freed here -- it 2743 * is the responsibility of 2744 * vnode_pager_setsize 2745 */ 2746 m = bp->b_pages[i]; 2747 KASSERT(m != bogus_page, 2748 ("allocbuf: bogus page found")); 2749 while (vm_page_sleep_if_busy(m, TRUE, "biodep")) 2750 vm_page_lock_queues(); 2751 2752 bp->b_pages[i] = NULL; 2753 vm_page_unwire(m, 0); 2754 } 2755 vm_page_unlock_queues(); 2756 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object); 2757 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) + 2758 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages)); 2759 bp->b_npages = desiredpages; 2760 } 2761 } else if (size > bp->b_bcount) { 2762 /* 2763 * We are growing the buffer, possibly in a 2764 * byte-granular fashion. 2765 */ 2766 struct vnode *vp; 2767 vm_object_t obj; 2768 vm_offset_t toff; 2769 vm_offset_t tinc; 2770 2771 /* 2772 * Step 1, bring in the VM pages from the object, 2773 * allocating them if necessary. We must clear 2774 * B_CACHE if these pages are not valid for the 2775 * range covered by the buffer. 2776 */ 2777 2778 vp = bp->b_vp; 2779 obj = bp->b_bufobj->bo_object; 2780 2781 VM_OBJECT_LOCK(obj); 2782 while (bp->b_npages < desiredpages) { 2783 vm_page_t m; 2784 vm_pindex_t pi; 2785 2786 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages; 2787 if ((m = vm_page_lookup(obj, pi)) == NULL) { 2788 /* 2789 * note: must allocate system pages 2790 * since blocking here could intefere 2791 * with paging I/O, no matter which 2792 * process we are. 2793 */ 2794 m = vm_page_alloc(obj, pi, 2795 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | 2796 VM_ALLOC_WIRED); 2797 if (m == NULL) { 2798 atomic_add_int(&vm_pageout_deficit, 2799 desiredpages - bp->b_npages); 2800 VM_OBJECT_UNLOCK(obj); 2801 VM_WAIT; 2802 VM_OBJECT_LOCK(obj); 2803 } else { 2804 bp->b_flags &= ~B_CACHE; 2805 bp->b_pages[bp->b_npages] = m; 2806 ++bp->b_npages; 2807 } 2808 continue; 2809 } 2810 2811 /* 2812 * We found a page. If we have to sleep on it, 2813 * retry because it might have gotten freed out 2814 * from under us. 2815 * 2816 * We can only test PG_BUSY here. Blocking on 2817 * m->busy might lead to a deadlock: 2818 * 2819 * vm_fault->getpages->cluster_read->allocbuf 2820 * 2821 */ 2822 vm_page_lock_queues(); 2823 if (vm_page_sleep_if_busy(m, FALSE, "pgtblk")) 2824 continue; 2825 2826 /* 2827 * We have a good page. Should we wakeup the 2828 * page daemon? 2829 */ 2830 if ((curproc != pageproc) && 2831 ((m->queue - m->pc) == PQ_CACHE) && 2832 ((cnt.v_free_count + cnt.v_cache_count) < 2833 (cnt.v_free_min + cnt.v_cache_min))) { 2834 pagedaemon_wakeup(); 2835 } 2836 vm_page_wire(m); 2837 vm_page_unlock_queues(); 2838 bp->b_pages[bp->b_npages] = m; 2839 ++bp->b_npages; 2840 } 2841 2842 /* 2843 * Step 2. We've loaded the pages into the buffer, 2844 * we have to figure out if we can still have B_CACHE 2845 * set. Note that B_CACHE is set according to the 2846 * byte-granular range ( bcount and size ), new the 2847 * aligned range ( newbsize ). 2848 * 2849 * The VM test is against m->valid, which is DEV_BSIZE 2850 * aligned. Needless to say, the validity of the data 2851 * needs to also be DEV_BSIZE aligned. Note that this 2852 * fails with NFS if the server or some other client 2853 * extends the file's EOF. If our buffer is resized, 2854 * B_CACHE may remain set! XXX 2855 */ 2856 2857 toff = bp->b_bcount; 2858 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK); 2859 2860 while ((bp->b_flags & B_CACHE) && toff < size) { 2861 vm_pindex_t pi; 2862 2863 if (tinc > (size - toff)) 2864 tinc = size - toff; 2865 2866 pi = ((bp->b_offset & PAGE_MASK) + toff) >> 2867 PAGE_SHIFT; 2868 2869 vfs_buf_test_cache( 2870 bp, 2871 bp->b_offset, 2872 toff, 2873 tinc, 2874 bp->b_pages[pi] 2875 ); 2876 toff += tinc; 2877 tinc = PAGE_SIZE; 2878 } 2879 VM_OBJECT_UNLOCK(obj); 2880 2881 /* 2882 * Step 3, fixup the KVM pmap. Remember that 2883 * bp->b_data is relative to bp->b_offset, but 2884 * bp->b_offset may be offset into the first page. 2885 */ 2886 2887 bp->b_data = (caddr_t) 2888 trunc_page((vm_offset_t)bp->b_data); 2889 pmap_qenter( 2890 (vm_offset_t)bp->b_data, 2891 bp->b_pages, 2892 bp->b_npages 2893 ); 2894 2895 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 2896 (vm_offset_t)(bp->b_offset & PAGE_MASK)); 2897 } 2898 } 2899 if (newbsize < bp->b_bufsize) 2900 bufspacewakeup(); 2901 bp->b_bufsize = newbsize; /* actual buffer allocation */ 2902 bp->b_bcount = size; /* requested buffer size */ 2903 return 1; 2904 } 2905 2906 void 2907 biodone(struct bio *bp) 2908 { 2909 2910 mtx_lock(&bdonelock); 2911 bp->bio_flags |= BIO_DONE; 2912 if (bp->bio_done == NULL) 2913 wakeup(bp); 2914 mtx_unlock(&bdonelock); 2915 if (bp->bio_done != NULL) 2916 bp->bio_done(bp); 2917 } 2918 2919 /* 2920 * Wait for a BIO to finish. 2921 * 2922 * XXX: resort to a timeout for now. The optimal locking (if any) for this 2923 * case is not yet clear. 2924 */ 2925 int 2926 biowait(struct bio *bp, const char *wchan) 2927 { 2928 2929 mtx_lock(&bdonelock); 2930 while ((bp->bio_flags & BIO_DONE) == 0) 2931 msleep(bp, &bdonelock, PRIBIO, wchan, hz / 10); 2932 mtx_unlock(&bdonelock); 2933 if (bp->bio_error != 0) 2934 return (bp->bio_error); 2935 if (!(bp->bio_flags & BIO_ERROR)) 2936 return (0); 2937 return (EIO); 2938 } 2939 2940 void 2941 biofinish(struct bio *bp, struct devstat *stat, int error) 2942 { 2943 2944 if (error) { 2945 bp->bio_error = error; 2946 bp->bio_flags |= BIO_ERROR; 2947 } 2948 if (stat != NULL) 2949 devstat_end_transaction_bio(stat, bp); 2950 biodone(bp); 2951 } 2952 2953 /* 2954 * bufwait: 2955 * 2956 * Wait for buffer I/O completion, returning error status. The buffer 2957 * is left locked and B_DONE on return. B_EINTR is converted into an EINTR 2958 * error and cleared. 2959 */ 2960 int 2961 bufwait(struct buf *bp) 2962 { 2963 int s; 2964 2965 s = splbio(); 2966 if (bp->b_iocmd == BIO_READ) 2967 bwait(bp, PRIBIO, "biord"); 2968 else 2969 bwait(bp, PRIBIO, "biowr"); 2970 splx(s); 2971 if (bp->b_flags & B_EINTR) { 2972 bp->b_flags &= ~B_EINTR; 2973 return (EINTR); 2974 } 2975 if (bp->b_ioflags & BIO_ERROR) { 2976 return (bp->b_error ? bp->b_error : EIO); 2977 } else { 2978 return (0); 2979 } 2980 } 2981 2982 /* 2983 * Call back function from struct bio back up to struct buf. 2984 */ 2985 static void 2986 bufdonebio(struct bio *bip) 2987 { 2988 struct buf *bp; 2989 2990 bp = bip->bio_caller2; 2991 bp->b_resid = bp->b_bcount - bip->bio_completed; 2992 bp->b_resid = bip->bio_resid; /* XXX: remove */ 2993 bp->b_ioflags = bip->bio_flags; 2994 bp->b_error = bip->bio_error; 2995 if (bp->b_error) 2996 bp->b_ioflags |= BIO_ERROR; 2997 bufdone(bp); 2998 g_destroy_bio(bip); 2999 } 3000 3001 void 3002 dev_strategy(struct cdev *dev, struct buf *bp) 3003 { 3004 struct cdevsw *csw; 3005 struct bio *bip; 3006 3007 if ((!bp->b_iocmd) || (bp->b_iocmd & (bp->b_iocmd - 1))) 3008 panic("b_iocmd botch"); 3009 for (;;) { 3010 bip = g_new_bio(); 3011 if (bip != NULL) 3012 break; 3013 /* Try again later */ 3014 tsleep(&bp, PRIBIO, "dev_strat", hz/10); 3015 } 3016 bip->bio_cmd = bp->b_iocmd; 3017 bip->bio_offset = bp->b_iooffset; 3018 bip->bio_length = bp->b_bcount; 3019 bip->bio_bcount = bp->b_bcount; /* XXX: remove */ 3020 bip->bio_data = bp->b_data; 3021 bip->bio_done = bufdonebio; 3022 bip->bio_caller2 = bp; 3023 bip->bio_dev = dev; 3024 KASSERT(dev->si_refcount > 0, 3025 ("dev_strategy on un-referenced struct cdev *(%s)", 3026 devtoname(dev))); 3027 csw = dev_refthread(dev); 3028 if (csw == NULL) { 3029 bp->b_error = ENXIO; 3030 bp->b_ioflags = BIO_ERROR; 3031 bufdone(bp); 3032 return; 3033 } 3034 (*csw->d_strategy)(bip); 3035 dev_relthread(dev); 3036 } 3037 3038 /* 3039 * bufdone: 3040 * 3041 * Finish I/O on a buffer, optionally calling a completion function. 3042 * This is usually called from an interrupt so process blocking is 3043 * not allowed. 3044 * 3045 * biodone is also responsible for setting B_CACHE in a B_VMIO bp. 3046 * In a non-VMIO bp, B_CACHE will be set on the next getblk() 3047 * assuming B_INVAL is clear. 3048 * 3049 * For the VMIO case, we set B_CACHE if the op was a read and no 3050 * read error occured, or if the op was a write. B_CACHE is never 3051 * set if the buffer is invalid or otherwise uncacheable. 3052 * 3053 * biodone does not mess with B_INVAL, allowing the I/O routine or the 3054 * initiator to leave B_INVAL set to brelse the buffer out of existance 3055 * in the biodone routine. 3056 */ 3057 void 3058 bufdone(struct buf *bp) 3059 { 3060 struct bufobj *dropobj; 3061 int s; 3062 void (*biodone)(struct buf *); 3063 3064 3065 CTR3(KTR_BUF, "bufdone(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags); 3066 s = splbio(); 3067 dropobj = NULL; 3068 3069 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp))); 3070 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp)); 3071 3072 runningbufwakeup(bp); 3073 if (bp->b_iocmd == BIO_WRITE) 3074 dropobj = bp->b_bufobj; 3075 /* call optional completion function if requested */ 3076 if (bp->b_iodone != NULL) { 3077 biodone = bp->b_iodone; 3078 bp->b_iodone = NULL; 3079 /* 3080 * Device drivers may or may not hold giant, hold it here 3081 * if we're calling into unknown code. 3082 */ 3083 mtx_lock(&Giant); 3084 bp->b_flags |= B_DONE; 3085 (*biodone) (bp); 3086 mtx_unlock(&Giant); 3087 if (dropobj) 3088 bufobj_wdrop(dropobj); 3089 splx(s); 3090 return; 3091 } 3092 if (LIST_FIRST(&bp->b_dep) != NULL) 3093 buf_complete(bp); 3094 3095 if (bp->b_flags & B_VMIO) { 3096 int i; 3097 vm_ooffset_t foff; 3098 vm_page_t m; 3099 vm_object_t obj; 3100 int iosize; 3101 struct vnode *vp = bp->b_vp; 3102 3103 obj = bp->b_bufobj->bo_object; 3104 3105 #if defined(VFS_BIO_DEBUG) 3106 mp_fixme("usecount and vflag accessed without locks."); 3107 if (vp->v_usecount == 0) { 3108 panic("biodone: zero vnode ref count"); 3109 } 3110 3111 KASSERT(vp->v_object != NULL, 3112 ("biodone: vnode %p has no vm_object", vp)); 3113 #endif 3114 3115 foff = bp->b_offset; 3116 KASSERT(bp->b_offset != NOOFFSET, 3117 ("biodone: no buffer offset")); 3118 3119 VM_OBJECT_LOCK(obj); 3120 #if defined(VFS_BIO_DEBUG) 3121 if (obj->paging_in_progress < bp->b_npages) { 3122 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n", 3123 obj->paging_in_progress, bp->b_npages); 3124 } 3125 #endif 3126 3127 /* 3128 * Set B_CACHE if the op was a normal read and no error 3129 * occured. B_CACHE is set for writes in the b*write() 3130 * routines. 3131 */ 3132 iosize = bp->b_bcount - bp->b_resid; 3133 if (bp->b_iocmd == BIO_READ && 3134 !(bp->b_flags & (B_INVAL|B_NOCACHE)) && 3135 !(bp->b_ioflags & BIO_ERROR)) { 3136 bp->b_flags |= B_CACHE; 3137 } 3138 vm_page_lock_queues(); 3139 for (i = 0; i < bp->b_npages; i++) { 3140 int bogusflag = 0; 3141 int resid; 3142 3143 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff; 3144 if (resid > iosize) 3145 resid = iosize; 3146 3147 /* 3148 * cleanup bogus pages, restoring the originals 3149 */ 3150 m = bp->b_pages[i]; 3151 if (m == bogus_page) { 3152 bogusflag = 1; 3153 m = vm_page_lookup(obj, OFF_TO_IDX(foff)); 3154 if (m == NULL) 3155 panic("biodone: page disappeared!"); 3156 bp->b_pages[i] = m; 3157 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages); 3158 } 3159 #if defined(VFS_BIO_DEBUG) 3160 if (OFF_TO_IDX(foff) != m->pindex) { 3161 printf( 3162 "biodone: foff(%jd)/m->pindex(%ju) mismatch\n", 3163 (intmax_t)foff, (uintmax_t)m->pindex); 3164 } 3165 #endif 3166 3167 /* 3168 * In the write case, the valid and clean bits are 3169 * already changed correctly ( see bdwrite() ), so we 3170 * only need to do this here in the read case. 3171 */ 3172 if ((bp->b_iocmd == BIO_READ) && !bogusflag && resid > 0) { 3173 vfs_page_set_valid(bp, foff, i, m); 3174 } 3175 3176 /* 3177 * when debugging new filesystems or buffer I/O methods, this 3178 * is the most common error that pops up. if you see this, you 3179 * have not set the page busy flag correctly!!! 3180 */ 3181 if (m->busy == 0) { 3182 printf("biodone: page busy < 0, " 3183 "pindex: %d, foff: 0x(%x,%x), " 3184 "resid: %d, index: %d\n", 3185 (int) m->pindex, (int)(foff >> 32), 3186 (int) foff & 0xffffffff, resid, i); 3187 if (!vn_isdisk(vp, NULL)) 3188 printf(" iosize: %jd, lblkno: %jd, flags: 0x%x, npages: %d\n", 3189 (intmax_t)bp->b_vp->v_mount->mnt_stat.f_iosize, 3190 (intmax_t) bp->b_lblkno, 3191 bp->b_flags, bp->b_npages); 3192 else 3193 printf(" VDEV, lblkno: %jd, flags: 0x%x, npages: %d\n", 3194 (intmax_t) bp->b_lblkno, 3195 bp->b_flags, bp->b_npages); 3196 printf(" valid: 0x%lx, dirty: 0x%lx, wired: %d\n", 3197 (u_long)m->valid, (u_long)m->dirty, 3198 m->wire_count); 3199 panic("biodone: page busy < 0\n"); 3200 } 3201 vm_page_io_finish(m); 3202 vm_object_pip_subtract(obj, 1); 3203 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 3204 iosize -= resid; 3205 } 3206 vm_page_unlock_queues(); 3207 vm_object_pip_wakeupn(obj, 0); 3208 VM_OBJECT_UNLOCK(obj); 3209 } 3210 3211 /* 3212 * For asynchronous completions, release the buffer now. The brelse 3213 * will do a wakeup there if necessary - so no need to do a wakeup 3214 * here in the async case. The sync case always needs to do a wakeup. 3215 */ 3216 3217 if (bp->b_flags & B_ASYNC) { 3218 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_RELBUF)) || (bp->b_ioflags & BIO_ERROR)) 3219 brelse(bp); 3220 else 3221 bqrelse(bp); 3222 } else 3223 bdone(bp); 3224 if (dropobj) 3225 bufobj_wdrop(dropobj); 3226 splx(s); 3227 } 3228 3229 /* 3230 * This routine is called in lieu of iodone in the case of 3231 * incomplete I/O. This keeps the busy status for pages 3232 * consistant. 3233 */ 3234 void 3235 vfs_unbusy_pages(struct buf *bp) 3236 { 3237 int i; 3238 vm_object_t obj; 3239 vm_page_t m; 3240 3241 runningbufwakeup(bp); 3242 if (!(bp->b_flags & B_VMIO)) 3243 return; 3244 3245 obj = bp->b_bufobj->bo_object; 3246 VM_OBJECT_LOCK(obj); 3247 vm_page_lock_queues(); 3248 for (i = 0; i < bp->b_npages; i++) { 3249 m = bp->b_pages[i]; 3250 if (m == bogus_page) { 3251 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i); 3252 if (!m) 3253 panic("vfs_unbusy_pages: page missing\n"); 3254 bp->b_pages[i] = m; 3255 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 3256 bp->b_pages, bp->b_npages); 3257 } 3258 vm_object_pip_subtract(obj, 1); 3259 vm_page_io_finish(m); 3260 } 3261 vm_page_unlock_queues(); 3262 vm_object_pip_wakeupn(obj, 0); 3263 VM_OBJECT_UNLOCK(obj); 3264 } 3265 3266 /* 3267 * vfs_page_set_valid: 3268 * 3269 * Set the valid bits in a page based on the supplied offset. The 3270 * range is restricted to the buffer's size. 3271 * 3272 * This routine is typically called after a read completes. 3273 */ 3274 static void 3275 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m) 3276 { 3277 vm_ooffset_t soff, eoff; 3278 3279 mtx_assert(&vm_page_queue_mtx, MA_OWNED); 3280 /* 3281 * Start and end offsets in buffer. eoff - soff may not cross a 3282 * page boundry or cross the end of the buffer. The end of the 3283 * buffer, in this case, is our file EOF, not the allocation size 3284 * of the buffer. 3285 */ 3286 soff = off; 3287 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK; 3288 if (eoff > bp->b_offset + bp->b_bcount) 3289 eoff = bp->b_offset + bp->b_bcount; 3290 3291 /* 3292 * Set valid range. This is typically the entire buffer and thus the 3293 * entire page. 3294 */ 3295 if (eoff > soff) { 3296 vm_page_set_validclean( 3297 m, 3298 (vm_offset_t) (soff & PAGE_MASK), 3299 (vm_offset_t) (eoff - soff) 3300 ); 3301 } 3302 } 3303 3304 /* 3305 * This routine is called before a device strategy routine. 3306 * It is used to tell the VM system that paging I/O is in 3307 * progress, and treat the pages associated with the buffer 3308 * almost as being PG_BUSY. Also the object paging_in_progress 3309 * flag is handled to make sure that the object doesn't become 3310 * inconsistant. 3311 * 3312 * Since I/O has not been initiated yet, certain buffer flags 3313 * such as BIO_ERROR or B_INVAL may be in an inconsistant state 3314 * and should be ignored. 3315 */ 3316 void 3317 vfs_busy_pages(struct buf *bp, int clear_modify) 3318 { 3319 int i, bogus; 3320 vm_object_t obj; 3321 vm_ooffset_t foff; 3322 vm_page_t m; 3323 3324 if (!(bp->b_flags & B_VMIO)) 3325 return; 3326 3327 obj = bp->b_bufobj->bo_object; 3328 foff = bp->b_offset; 3329 KASSERT(bp->b_offset != NOOFFSET, 3330 ("vfs_busy_pages: no buffer offset")); 3331 vfs_setdirty(bp); 3332 VM_OBJECT_LOCK(obj); 3333 retry: 3334 vm_page_lock_queues(); 3335 for (i = 0; i < bp->b_npages; i++) { 3336 m = bp->b_pages[i]; 3337 3338 if (vm_page_sleep_if_busy(m, FALSE, "vbpage")) 3339 goto retry; 3340 } 3341 bogus = 0; 3342 for (i = 0; i < bp->b_npages; i++) { 3343 m = bp->b_pages[i]; 3344 3345 if ((bp->b_flags & B_CLUSTER) == 0) { 3346 vm_object_pip_add(obj, 1); 3347 vm_page_io_start(m); 3348 } 3349 /* 3350 * When readying a buffer for a read ( i.e 3351 * clear_modify == 0 ), it is important to do 3352 * bogus_page replacement for valid pages in 3353 * partially instantiated buffers. Partially 3354 * instantiated buffers can, in turn, occur when 3355 * reconstituting a buffer from its VM backing store 3356 * base. We only have to do this if B_CACHE is 3357 * clear ( which causes the I/O to occur in the 3358 * first place ). The replacement prevents the read 3359 * I/O from overwriting potentially dirty VM-backed 3360 * pages. XXX bogus page replacement is, uh, bogus. 3361 * It may not work properly with small-block devices. 3362 * We need to find a better way. 3363 */ 3364 pmap_remove_all(m); 3365 if (clear_modify) 3366 vfs_page_set_valid(bp, foff, i, m); 3367 else if (m->valid == VM_PAGE_BITS_ALL && 3368 (bp->b_flags & B_CACHE) == 0) { 3369 bp->b_pages[i] = bogus_page; 3370 bogus++; 3371 } 3372 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 3373 } 3374 vm_page_unlock_queues(); 3375 VM_OBJECT_UNLOCK(obj); 3376 if (bogus) 3377 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 3378 bp->b_pages, bp->b_npages); 3379 } 3380 3381 /* 3382 * Tell the VM system that the pages associated with this buffer 3383 * are clean. This is used for delayed writes where the data is 3384 * going to go to disk eventually without additional VM intevention. 3385 * 3386 * Note that while we only really need to clean through to b_bcount, we 3387 * just go ahead and clean through to b_bufsize. 3388 */ 3389 static void 3390 vfs_clean_pages(struct buf *bp) 3391 { 3392 int i; 3393 vm_ooffset_t foff, noff, eoff; 3394 vm_page_t m; 3395 3396 if (!(bp->b_flags & B_VMIO)) 3397 return; 3398 3399 foff = bp->b_offset; 3400 KASSERT(bp->b_offset != NOOFFSET, 3401 ("vfs_clean_pages: no buffer offset")); 3402 VM_OBJECT_LOCK(bp->b_bufobj->bo_object); 3403 vm_page_lock_queues(); 3404 for (i = 0; i < bp->b_npages; i++) { 3405 m = bp->b_pages[i]; 3406 noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 3407 eoff = noff; 3408 3409 if (eoff > bp->b_offset + bp->b_bufsize) 3410 eoff = bp->b_offset + bp->b_bufsize; 3411 vfs_page_set_valid(bp, foff, i, m); 3412 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */ 3413 foff = noff; 3414 } 3415 vm_page_unlock_queues(); 3416 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object); 3417 } 3418 3419 /* 3420 * vfs_bio_set_validclean: 3421 * 3422 * Set the range within the buffer to valid and clean. The range is 3423 * relative to the beginning of the buffer, b_offset. Note that b_offset 3424 * itself may be offset from the beginning of the first page. 3425 * 3426 */ 3427 3428 void 3429 vfs_bio_set_validclean(struct buf *bp, int base, int size) 3430 { 3431 int i, n; 3432 vm_page_t m; 3433 3434 if (!(bp->b_flags & B_VMIO)) 3435 return; 3436 /* 3437 * Fixup base to be relative to beginning of first page. 3438 * Set initial n to be the maximum number of bytes in the 3439 * first page that can be validated. 3440 */ 3441 3442 base += (bp->b_offset & PAGE_MASK); 3443 n = PAGE_SIZE - (base & PAGE_MASK); 3444 3445 VM_OBJECT_LOCK(bp->b_bufobj->bo_object); 3446 vm_page_lock_queues(); 3447 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) { 3448 m = bp->b_pages[i]; 3449 if (n > size) 3450 n = size; 3451 vm_page_set_validclean(m, base & PAGE_MASK, n); 3452 base += n; 3453 size -= n; 3454 n = PAGE_SIZE; 3455 } 3456 vm_page_unlock_queues(); 3457 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object); 3458 } 3459 3460 /* 3461 * vfs_bio_clrbuf: 3462 * 3463 * clear a buffer. This routine essentially fakes an I/O, so we need 3464 * to clear BIO_ERROR and B_INVAL. 3465 * 3466 * Note that while we only theoretically need to clear through b_bcount, 3467 * we go ahead and clear through b_bufsize. 3468 */ 3469 3470 void 3471 vfs_bio_clrbuf(struct buf *bp) 3472 { 3473 int i, j, mask = 0; 3474 caddr_t sa, ea; 3475 3476 if ((bp->b_flags & (B_VMIO | B_MALLOC)) != B_VMIO) { 3477 clrbuf(bp); 3478 return; 3479 } 3480 3481 bp->b_flags &= ~B_INVAL; 3482 bp->b_ioflags &= ~BIO_ERROR; 3483 VM_OBJECT_LOCK(bp->b_bufobj->bo_object); 3484 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) && 3485 (bp->b_offset & PAGE_MASK) == 0) { 3486 if (bp->b_pages[0] == bogus_page) 3487 goto unlock; 3488 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1; 3489 VM_OBJECT_LOCK_ASSERT(bp->b_pages[0]->object, MA_OWNED); 3490 if ((bp->b_pages[0]->valid & mask) == mask) 3491 goto unlock; 3492 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) && 3493 ((bp->b_pages[0]->valid & mask) == 0)) { 3494 bzero(bp->b_data, bp->b_bufsize); 3495 bp->b_pages[0]->valid |= mask; 3496 goto unlock; 3497 } 3498 } 3499 ea = sa = bp->b_data; 3500 for(i = 0; i < bp->b_npages; i++, sa = ea) { 3501 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE); 3502 ea = (caddr_t)(vm_offset_t)ulmin( 3503 (u_long)(vm_offset_t)ea, 3504 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize); 3505 if (bp->b_pages[i] == bogus_page) 3506 continue; 3507 j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE; 3508 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j; 3509 VM_OBJECT_LOCK_ASSERT(bp->b_pages[i]->object, MA_OWNED); 3510 if ((bp->b_pages[i]->valid & mask) == mask) 3511 continue; 3512 if ((bp->b_pages[i]->valid & mask) == 0) { 3513 if ((bp->b_pages[i]->flags & PG_ZERO) == 0) 3514 bzero(sa, ea - sa); 3515 } else { 3516 for (; sa < ea; sa += DEV_BSIZE, j++) { 3517 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) && 3518 (bp->b_pages[i]->valid & (1 << j)) == 0) 3519 bzero(sa, DEV_BSIZE); 3520 } 3521 } 3522 bp->b_pages[i]->valid |= mask; 3523 } 3524 unlock: 3525 VM_OBJECT_UNLOCK(bp->b_bufobj->bo_object); 3526 bp->b_resid = 0; 3527 } 3528 3529 /* 3530 * vm_hold_load_pages and vm_hold_free_pages get pages into 3531 * a buffers address space. The pages are anonymous and are 3532 * not associated with a file object. 3533 */ 3534 static void 3535 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to) 3536 { 3537 vm_offset_t pg; 3538 vm_page_t p; 3539 int index; 3540 3541 to = round_page(to); 3542 from = round_page(from); 3543 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT; 3544 3545 VM_OBJECT_LOCK(kernel_object); 3546 for (pg = from; pg < to; pg += PAGE_SIZE, index++) { 3547 tryagain: 3548 /* 3549 * note: must allocate system pages since blocking here 3550 * could intefere with paging I/O, no matter which 3551 * process we are. 3552 */ 3553 p = vm_page_alloc(kernel_object, 3554 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT), 3555 VM_ALLOC_NOBUSY | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED); 3556 if (!p) { 3557 atomic_add_int(&vm_pageout_deficit, 3558 (to - pg) >> PAGE_SHIFT); 3559 VM_OBJECT_UNLOCK(kernel_object); 3560 VM_WAIT; 3561 VM_OBJECT_LOCK(kernel_object); 3562 goto tryagain; 3563 } 3564 p->valid = VM_PAGE_BITS_ALL; 3565 pmap_qenter(pg, &p, 1); 3566 bp->b_pages[index] = p; 3567 } 3568 VM_OBJECT_UNLOCK(kernel_object); 3569 bp->b_npages = index; 3570 } 3571 3572 /* Return pages associated with this buf to the vm system */ 3573 static void 3574 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to) 3575 { 3576 vm_offset_t pg; 3577 vm_page_t p; 3578 int index, newnpages; 3579 3580 from = round_page(from); 3581 to = round_page(to); 3582 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT; 3583 3584 VM_OBJECT_LOCK(kernel_object); 3585 for (pg = from; pg < to; pg += PAGE_SIZE, index++) { 3586 p = bp->b_pages[index]; 3587 if (p && (index < bp->b_npages)) { 3588 if (p->busy) { 3589 printf( 3590 "vm_hold_free_pages: blkno: %jd, lblkno: %jd\n", 3591 (intmax_t)bp->b_blkno, 3592 (intmax_t)bp->b_lblkno); 3593 } 3594 bp->b_pages[index] = NULL; 3595 pmap_qremove(pg, 1); 3596 vm_page_lock_queues(); 3597 vm_page_unwire(p, 0); 3598 vm_page_free(p); 3599 vm_page_unlock_queues(); 3600 } 3601 } 3602 VM_OBJECT_UNLOCK(kernel_object); 3603 bp->b_npages = newnpages; 3604 } 3605 3606 /* 3607 * Map an IO request into kernel virtual address space. 3608 * 3609 * All requests are (re)mapped into kernel VA space. 3610 * Notice that we use b_bufsize for the size of the buffer 3611 * to be mapped. b_bcount might be modified by the driver. 3612 * 3613 * Note that even if the caller determines that the address space should 3614 * be valid, a race or a smaller-file mapped into a larger space may 3615 * actually cause vmapbuf() to fail, so all callers of vmapbuf() MUST 3616 * check the return value. 3617 */ 3618 int 3619 vmapbuf(struct buf *bp) 3620 { 3621 caddr_t addr, kva; 3622 vm_prot_t prot; 3623 int pidx, i; 3624 struct vm_page *m; 3625 struct pmap *pmap = &curproc->p_vmspace->vm_pmap; 3626 3627 if (bp->b_bufsize < 0) 3628 return (-1); 3629 prot = VM_PROT_READ; 3630 if (bp->b_iocmd == BIO_READ) 3631 prot |= VM_PROT_WRITE; /* Less backwards than it looks */ 3632 for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data), pidx = 0; 3633 addr < bp->b_data + bp->b_bufsize; 3634 addr += PAGE_SIZE, pidx++) { 3635 /* 3636 * Do the vm_fault if needed; do the copy-on-write thing 3637 * when reading stuff off device into memory. 3638 * 3639 * NOTE! Must use pmap_extract() because addr may be in 3640 * the userland address space, and kextract is only guarenteed 3641 * to work for the kernland address space (see: sparc64 port). 3642 */ 3643 retry: 3644 if (vm_fault_quick(addr >= bp->b_data ? addr : bp->b_data, 3645 prot) < 0) { 3646 vm_page_lock_queues(); 3647 for (i = 0; i < pidx; ++i) { 3648 vm_page_unhold(bp->b_pages[i]); 3649 bp->b_pages[i] = NULL; 3650 } 3651 vm_page_unlock_queues(); 3652 return(-1); 3653 } 3654 m = pmap_extract_and_hold(pmap, (vm_offset_t)addr, prot); 3655 if (m == NULL) 3656 goto retry; 3657 bp->b_pages[pidx] = m; 3658 } 3659 if (pidx > btoc(MAXPHYS)) 3660 panic("vmapbuf: mapped more than MAXPHYS"); 3661 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx); 3662 3663 kva = bp->b_saveaddr; 3664 bp->b_npages = pidx; 3665 bp->b_saveaddr = bp->b_data; 3666 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK); 3667 return(0); 3668 } 3669 3670 /* 3671 * Free the io map PTEs associated with this IO operation. 3672 * We also invalidate the TLB entries and restore the original b_addr. 3673 */ 3674 void 3675 vunmapbuf(struct buf *bp) 3676 { 3677 int pidx; 3678 int npages; 3679 3680 npages = bp->b_npages; 3681 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages); 3682 vm_page_lock_queues(); 3683 for (pidx = 0; pidx < npages; pidx++) 3684 vm_page_unhold(bp->b_pages[pidx]); 3685 vm_page_unlock_queues(); 3686 3687 bp->b_data = bp->b_saveaddr; 3688 } 3689 3690 void 3691 bdone(struct buf *bp) 3692 { 3693 3694 mtx_lock(&bdonelock); 3695 bp->b_flags |= B_DONE; 3696 wakeup(bp); 3697 mtx_unlock(&bdonelock); 3698 } 3699 3700 void 3701 bwait(struct buf *bp, u_char pri, const char *wchan) 3702 { 3703 3704 mtx_lock(&bdonelock); 3705 while ((bp->b_flags & B_DONE) == 0) 3706 msleep(bp, &bdonelock, pri, wchan, 0); 3707 mtx_unlock(&bdonelock); 3708 } 3709 3710 int 3711 bufsync(struct bufobj *bo, int waitfor, struct thread *td) 3712 { 3713 3714 return (VOP_FSYNC(bo->__bo_vnode, waitfor, td)); 3715 } 3716 3717 void 3718 bufstrategy(struct bufobj *bo, struct buf *bp) 3719 { 3720 int i = 0; 3721 struct vnode *vp; 3722 3723 vp = bp->b_vp; 3724 KASSERT(vp == bo->bo_private, ("Inconsistent vnode bufstrategy")); 3725 KASSERT(vp->v_type != VCHR && vp->v_type != VBLK, 3726 ("Wrong vnode in bufstrategy(bp=%p, vp=%p)", bp, vp)); 3727 i = VOP_STRATEGY(vp, bp); 3728 KASSERT(i == 0, ("VOP_STRATEGY failed bp=%p vp=%p", bp, bp->b_vp)); 3729 } 3730 3731 void 3732 bufobj_wref(struct bufobj *bo) 3733 { 3734 3735 KASSERT(bo != NULL, ("NULL bo in bufobj_wref")); 3736 BO_LOCK(bo); 3737 bo->bo_numoutput++; 3738 BO_UNLOCK(bo); 3739 } 3740 3741 void 3742 bufobj_wdrop(struct bufobj *bo) 3743 { 3744 3745 KASSERT(bo != NULL, ("NULL bo in bufobj_wdrop")); 3746 BO_LOCK(bo); 3747 KASSERT(bo->bo_numoutput > 0, ("bufobj_wdrop non-positive count")); 3748 if ((--bo->bo_numoutput == 0) && (bo->bo_flag & BO_WWAIT)) { 3749 bo->bo_flag &= ~BO_WWAIT; 3750 wakeup(&bo->bo_numoutput); 3751 } 3752 BO_UNLOCK(bo); 3753 } 3754 3755 int 3756 bufobj_wwait(struct bufobj *bo, int slpflag, int timeo) 3757 { 3758 int error; 3759 3760 KASSERT(bo != NULL, ("NULL bo in bufobj_wwait")); 3761 ASSERT_BO_LOCKED(bo); 3762 error = 0; 3763 while (bo->bo_numoutput) { 3764 bo->bo_flag |= BO_WWAIT; 3765 error = msleep(&bo->bo_numoutput, BO_MTX(bo), 3766 slpflag | (PRIBIO + 1), "bo_wwait", timeo); 3767 if (error) 3768 break; 3769 } 3770 return (error); 3771 } 3772 3773 #include "opt_ddb.h" 3774 #ifdef DDB 3775 #include <ddb/ddb.h> 3776 3777 /* DDB command to show buffer data */ 3778 DB_SHOW_COMMAND(buffer, db_show_buffer) 3779 { 3780 /* get args */ 3781 struct buf *bp = (struct buf *)addr; 3782 3783 if (!have_addr) { 3784 db_printf("usage: show buffer <addr>\n"); 3785 return; 3786 } 3787 3788 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS); 3789 db_printf( 3790 "b_error = %d, b_bufsize = %ld, b_bcount = %ld, b_resid = %ld\n" 3791 "b_bufobj = (%p), b_data = %p, b_blkno = %jd\n", 3792 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid, 3793 bp->b_bufobj, bp->b_data, (intmax_t)bp->b_blkno); 3794 if (bp->b_npages) { 3795 int i; 3796 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages); 3797 for (i = 0; i < bp->b_npages; i++) { 3798 vm_page_t m; 3799 m = bp->b_pages[i]; 3800 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object, 3801 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m)); 3802 if ((i + 1) < bp->b_npages) 3803 db_printf(","); 3804 } 3805 db_printf("\n"); 3806 } 3807 } 3808 #endif /* DDB */ 3809