1 /* 2 * Copyright (c) 1994,1997 John S. Dyson 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice immediately at the beginning of the file, without modification, 10 * this list of conditions, and the following disclaimer. 11 * 2. Absolutely no warranty of function or purpose is made by the author 12 * John S. Dyson. 13 * 14 * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $ 15 */ 16 17 /* 18 * this file contains a new buffer I/O scheme implementing a coherent 19 * VM object and buffer cache scheme. Pains have been taken to make 20 * sure that the performance degradation associated with schemes such 21 * as this is not realized. 22 * 23 * Author: John S. Dyson 24 * Significant help during the development and debugging phases 25 * had been provided by David Greenman, also of the FreeBSD core team. 26 * 27 * see man buf(9) for more info. 28 */ 29 30 #include <sys/param.h> 31 #include <sys/systm.h> 32 #include <sys/buf.h> 33 #include <sys/conf.h> 34 #include <sys/devicestat.h> 35 #include <sys/eventhandler.h> 36 #include <sys/lock.h> 37 #include <sys/malloc.h> 38 #include <sys/mount.h> 39 #include <sys/kernel.h> 40 #include <sys/kthread.h> 41 #include <sys/proc.h> 42 #include <sys/reboot.h> 43 #include <sys/resourcevar.h> 44 #include <sys/sysctl.h> 45 #include <sys/vmmeter.h> 46 #include <sys/vnode.h> 47 #include <sys/dsched.h> 48 #include <vm/vm.h> 49 #include <vm/vm_param.h> 50 #include <vm/vm_kern.h> 51 #include <vm/vm_pageout.h> 52 #include <vm/vm_page.h> 53 #include <vm/vm_object.h> 54 #include <vm/vm_extern.h> 55 #include <vm/vm_map.h> 56 #include <vm/vm_pager.h> 57 #include <vm/swap_pager.h> 58 59 #include <sys/buf2.h> 60 #include <sys/thread2.h> 61 #include <sys/spinlock2.h> 62 #include <sys/mplock2.h> 63 #include <vm/vm_page2.h> 64 65 #include "opt_ddb.h" 66 #ifdef DDB 67 #include <ddb/ddb.h> 68 #endif 69 70 /* 71 * Buffer queues. 72 */ 73 enum bufq_type { 74 BQUEUE_NONE, /* not on any queue */ 75 BQUEUE_LOCKED, /* locked buffers */ 76 BQUEUE_CLEAN, /* non-B_DELWRI buffers */ 77 BQUEUE_DIRTY, /* B_DELWRI buffers */ 78 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */ 79 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */ 80 BQUEUE_EMPTY, /* empty buffer headers */ 81 82 BUFFER_QUEUES /* number of buffer queues */ 83 }; 84 85 typedef enum bufq_type bufq_type_t; 86 87 #define BD_WAKE_SIZE 16384 88 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1) 89 90 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES]; 91 static struct spinlock bufqspin = SPINLOCK_INITIALIZER(&bufqspin); 92 static struct spinlock bufcspin = SPINLOCK_INITIALIZER(&bufcspin); 93 94 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer"); 95 96 struct buf *buf; /* buffer header pool */ 97 98 static void vfs_clean_pages(struct buf *bp); 99 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m); 100 static void vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m); 101 static void vfs_vmio_release(struct buf *bp); 102 static int flushbufqueues(bufq_type_t q); 103 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit); 104 105 static void bd_signal(int totalspace); 106 static void buf_daemon(void); 107 static void buf_daemon_hw(void); 108 109 /* 110 * bogus page -- for I/O to/from partially complete buffers 111 * this is a temporary solution to the problem, but it is not 112 * really that bad. it would be better to split the buffer 113 * for input in the case of buffers partially already in memory, 114 * but the code is intricate enough already. 115 */ 116 vm_page_t bogus_page; 117 118 /* 119 * These are all static, but make the ones we export globals so we do 120 * not need to use compiler magic. 121 */ 122 long bufspace; /* locked by buffer_map */ 123 long maxbufspace; 124 static long bufmallocspace; /* atomic ops */ 125 long maxbufmallocspace, lobufspace, hibufspace; 126 static int bufreusecnt, bufdefragcnt, buffreekvacnt; 127 static long lorunningspace; 128 static long hirunningspace; 129 static int runningbufreq; /* locked by bufcspin */ 130 static long dirtybufspace; /* locked by bufcspin */ 131 static int dirtybufcount; /* locked by bufcspin */ 132 static long dirtybufspacehw; /* locked by bufcspin */ 133 static int dirtybufcounthw; /* locked by bufcspin */ 134 static long runningbufspace; /* locked by bufcspin */ 135 static int runningbufcount; /* locked by bufcspin */ 136 long lodirtybufspace; 137 long hidirtybufspace; 138 static int getnewbufcalls; 139 static int getnewbufrestarts; 140 static int recoverbufcalls; 141 static int needsbuffer; /* locked by bufcspin */ 142 static int bd_request; /* locked by bufcspin */ 143 static int bd_request_hw; /* locked by bufcspin */ 144 static u_int bd_wake_ary[BD_WAKE_SIZE]; 145 static u_int bd_wake_index; 146 static u_int vm_cycle_point = 40; /* 23-36 will migrate more act->inact */ 147 static int debug_commit; 148 149 static struct thread *bufdaemon_td; 150 static struct thread *bufdaemonhw_td; 151 static u_int lowmempgallocs; 152 static u_int lowmempgfails; 153 154 /* 155 * Sysctls for operational control of the buffer cache. 156 */ 157 SYSCTL_LONG(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0, 158 "Number of dirty buffers to flush before bufdaemon becomes inactive"); 159 SYSCTL_LONG(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0, 160 "High watermark used to trigger explicit flushing of dirty buffers"); 161 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0, 162 "Minimum amount of buffer space required for active I/O"); 163 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0, 164 "Maximum amount of buffer space to usable for active I/O"); 165 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgallocs, CTLFLAG_RW, &lowmempgallocs, 0, 166 "Page allocations done during periods of very low free memory"); 167 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgfails, CTLFLAG_RW, &lowmempgfails, 0, 168 "Page allocations which failed during periods of very low free memory"); 169 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0, 170 "Recycle pages to active or inactive queue transition pt 0-64"); 171 /* 172 * Sysctls determining current state of the buffer cache. 173 */ 174 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0, 175 "Total number of buffers in buffer cache"); 176 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0, 177 "Pending bytes of dirty buffers (all)"); 178 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0, 179 "Pending bytes of dirty buffers (heavy weight)"); 180 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0, 181 "Pending number of dirty buffers"); 182 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0, 183 "Pending number of dirty buffers (heavy weight)"); 184 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0, 185 "I/O bytes currently in progress due to asynchronous writes"); 186 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0, 187 "I/O buffers currently in progress due to asynchronous writes"); 188 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0, 189 "Hard limit on maximum amount of memory usable for buffer space"); 190 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0, 191 "Soft limit on maximum amount of memory usable for buffer space"); 192 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0, 193 "Minimum amount of memory to reserve for system buffer space"); 194 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0, 195 "Amount of memory available for buffers"); 196 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace, 197 0, "Maximum amount of memory reserved for buffers using malloc"); 198 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0, 199 "Amount of memory left for buffers using malloc-scheme"); 200 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0, 201 "New buffer header acquisition requests"); 202 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts, 203 0, "New buffer header acquisition restarts"); 204 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0, 205 "Recover VM space in an emergency"); 206 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0, 207 "Buffer acquisition restarts due to fragmented buffer map"); 208 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0, 209 "Amount of time KVA space was deallocated in an arbitrary buffer"); 210 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0, 211 "Amount of time buffer re-use operations were successful"); 212 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, ""); 213 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf), 214 "sizeof(struct buf)"); 215 216 char *buf_wmesg = BUF_WMESG; 217 218 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */ 219 #define VFS_BIO_NEED_UNUSED02 0x02 220 #define VFS_BIO_NEED_UNUSED04 0x04 221 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */ 222 223 /* 224 * bufspacewakeup: 225 * 226 * Called when buffer space is potentially available for recovery. 227 * getnewbuf() will block on this flag when it is unable to free 228 * sufficient buffer space. Buffer space becomes recoverable when 229 * bp's get placed back in the queues. 230 */ 231 static __inline void 232 bufspacewakeup(void) 233 { 234 /* 235 * If someone is waiting for BUF space, wake them up. Even 236 * though we haven't freed the kva space yet, the waiting 237 * process will be able to now. 238 */ 239 spin_lock(&bufcspin); 240 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) { 241 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE; 242 spin_unlock(&bufcspin); 243 wakeup(&needsbuffer); 244 } else { 245 spin_unlock(&bufcspin); 246 } 247 } 248 249 /* 250 * runningbufwakeup: 251 * 252 * Accounting for I/O in progress. 253 * 254 */ 255 static __inline void 256 runningbufwakeup(struct buf *bp) 257 { 258 long totalspace; 259 long limit; 260 261 if ((totalspace = bp->b_runningbufspace) != 0) { 262 spin_lock(&bufcspin); 263 runningbufspace -= totalspace; 264 --runningbufcount; 265 bp->b_runningbufspace = 0; 266 267 /* 268 * see waitrunningbufspace() for limit test. 269 */ 270 limit = hirunningspace * 3 / 6; 271 if (runningbufreq && runningbufspace <= limit) { 272 runningbufreq = 0; 273 spin_unlock(&bufcspin); 274 wakeup(&runningbufreq); 275 } else { 276 spin_unlock(&bufcspin); 277 } 278 bd_signal(totalspace); 279 } 280 } 281 282 /* 283 * bufcountwakeup: 284 * 285 * Called when a buffer has been added to one of the free queues to 286 * account for the buffer and to wakeup anyone waiting for free buffers. 287 * This typically occurs when large amounts of metadata are being handled 288 * by the buffer cache ( else buffer space runs out first, usually ). 289 * 290 * MPSAFE 291 */ 292 static __inline void 293 bufcountwakeup(void) 294 { 295 spin_lock(&bufcspin); 296 if (needsbuffer) { 297 needsbuffer &= ~VFS_BIO_NEED_ANY; 298 spin_unlock(&bufcspin); 299 wakeup(&needsbuffer); 300 } else { 301 spin_unlock(&bufcspin); 302 } 303 } 304 305 /* 306 * waitrunningbufspace() 307 * 308 * If runningbufspace exceeds 4/6 hirunningspace we block until 309 * runningbufspace drops to 3/6 hirunningspace. We also block if another 310 * thread blocked here in order to be fair, even if runningbufspace 311 * is now lower than the limit. 312 * 313 * The caller may be using this function to block in a tight loop, we 314 * must block while runningbufspace is greater than at least 315 * hirunningspace * 3 / 6. 316 */ 317 void 318 waitrunningbufspace(void) 319 { 320 long limit = hirunningspace * 4 / 6; 321 322 if (runningbufspace > limit || runningbufreq) { 323 spin_lock(&bufcspin); 324 while (runningbufspace > limit || runningbufreq) { 325 runningbufreq = 1; 326 ssleep(&runningbufreq, &bufcspin, 0, "wdrn1", 0); 327 } 328 spin_unlock(&bufcspin); 329 } 330 } 331 332 /* 333 * buf_dirty_count_severe: 334 * 335 * Return true if we have too many dirty buffers. 336 */ 337 int 338 buf_dirty_count_severe(void) 339 { 340 return (runningbufspace + dirtybufspace >= hidirtybufspace || 341 dirtybufcount >= nbuf / 2); 342 } 343 344 /* 345 * Return true if the amount of running I/O is severe and BIOQ should 346 * start bursting. 347 */ 348 int 349 buf_runningbufspace_severe(void) 350 { 351 return (runningbufspace >= hirunningspace * 4 / 6); 352 } 353 354 /* 355 * vfs_buf_test_cache: 356 * 357 * Called when a buffer is extended. This function clears the B_CACHE 358 * bit if the newly extended portion of the buffer does not contain 359 * valid data. 360 * 361 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer 362 * cache buffers. The VM pages remain dirty, as someone had mmap()'d 363 * them while a clean buffer was present. 364 */ 365 static __inline__ 366 void 367 vfs_buf_test_cache(struct buf *bp, 368 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size, 369 vm_page_t m) 370 { 371 if (bp->b_flags & B_CACHE) { 372 int base = (foff + off) & PAGE_MASK; 373 if (vm_page_is_valid(m, base, size) == 0) 374 bp->b_flags &= ~B_CACHE; 375 } 376 } 377 378 /* 379 * bd_speedup() 380 * 381 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the 382 * low water mark. 383 * 384 * MPSAFE 385 */ 386 static __inline__ 387 void 388 bd_speedup(void) 389 { 390 if (dirtybufspace < lodirtybufspace && dirtybufcount < nbuf / 2) 391 return; 392 393 if (bd_request == 0 && 394 (dirtybufspace - dirtybufspacehw > lodirtybufspace / 2 || 395 dirtybufcount - dirtybufcounthw >= nbuf / 2)) { 396 spin_lock(&bufcspin); 397 bd_request = 1; 398 spin_unlock(&bufcspin); 399 wakeup(&bd_request); 400 } 401 if (bd_request_hw == 0 && 402 (dirtybufspacehw > lodirtybufspace / 2 || 403 dirtybufcounthw >= nbuf / 2)) { 404 spin_lock(&bufcspin); 405 bd_request_hw = 1; 406 spin_unlock(&bufcspin); 407 wakeup(&bd_request_hw); 408 } 409 } 410 411 /* 412 * bd_heatup() 413 * 414 * Get the buf_daemon heated up when the number of running and dirty 415 * buffers exceeds the mid-point. 416 * 417 * Return the total number of dirty bytes past the second mid point 418 * as a measure of how much excess dirty data there is in the system. 419 * 420 * MPSAFE 421 */ 422 int 423 bd_heatup(void) 424 { 425 long mid1; 426 long mid2; 427 long totalspace; 428 429 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2; 430 431 totalspace = runningbufspace + dirtybufspace; 432 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) { 433 bd_speedup(); 434 mid2 = mid1 + (hidirtybufspace - mid1) / 2; 435 if (totalspace >= mid2) 436 return(totalspace - mid2); 437 } 438 return(0); 439 } 440 441 /* 442 * bd_wait() 443 * 444 * Wait for the buffer cache to flush (totalspace) bytes worth of 445 * buffers, then return. 446 * 447 * Regardless this function blocks while the number of dirty buffers 448 * exceeds hidirtybufspace. 449 * 450 * MPSAFE 451 */ 452 void 453 bd_wait(int totalspace) 454 { 455 u_int i; 456 int count; 457 458 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td) 459 return; 460 461 while (totalspace > 0) { 462 bd_heatup(); 463 if (totalspace > runningbufspace + dirtybufspace) 464 totalspace = runningbufspace + dirtybufspace; 465 count = totalspace / BKVASIZE; 466 if (count >= BD_WAKE_SIZE) 467 count = BD_WAKE_SIZE - 1; 468 469 spin_lock(&bufcspin); 470 i = (bd_wake_index + count) & BD_WAKE_MASK; 471 ++bd_wake_ary[i]; 472 473 /* 474 * This is not a strict interlock, so we play a bit loose 475 * with locking access to dirtybufspace* 476 */ 477 tsleep_interlock(&bd_wake_ary[i], 0); 478 spin_unlock(&bufcspin); 479 tsleep(&bd_wake_ary[i], PINTERLOCKED, "flstik", hz); 480 481 totalspace = runningbufspace + dirtybufspace - hidirtybufspace; 482 } 483 } 484 485 /* 486 * bd_signal() 487 * 488 * This function is called whenever runningbufspace or dirtybufspace 489 * is reduced. Track threads waiting for run+dirty buffer I/O 490 * complete. 491 * 492 * MPSAFE 493 */ 494 static void 495 bd_signal(int totalspace) 496 { 497 u_int i; 498 499 if (totalspace > 0) { 500 if (totalspace > BKVASIZE * BD_WAKE_SIZE) 501 totalspace = BKVASIZE * BD_WAKE_SIZE; 502 spin_lock(&bufcspin); 503 while (totalspace > 0) { 504 i = bd_wake_index++; 505 i &= BD_WAKE_MASK; 506 if (bd_wake_ary[i]) { 507 bd_wake_ary[i] = 0; 508 spin_unlock(&bufcspin); 509 wakeup(&bd_wake_ary[i]); 510 spin_lock(&bufcspin); 511 } 512 totalspace -= BKVASIZE; 513 } 514 spin_unlock(&bufcspin); 515 } 516 } 517 518 /* 519 * BIO tracking support routines. 520 * 521 * Release a ref on a bio_track. Wakeup requests are atomically released 522 * along with the last reference so bk_active will never wind up set to 523 * only 0x80000000. 524 * 525 * MPSAFE 526 */ 527 static 528 void 529 bio_track_rel(struct bio_track *track) 530 { 531 int active; 532 int desired; 533 534 /* 535 * Shortcut 536 */ 537 active = track->bk_active; 538 if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0)) 539 return; 540 541 /* 542 * Full-on. Note that the wait flag is only atomically released on 543 * the 1->0 count transition. 544 * 545 * We check for a negative count transition using bit 30 since bit 31 546 * has a different meaning. 547 */ 548 for (;;) { 549 desired = (active & 0x7FFFFFFF) - 1; 550 if (desired) 551 desired |= active & 0x80000000; 552 if (atomic_cmpset_int(&track->bk_active, active, desired)) { 553 if (desired & 0x40000000) 554 panic("bio_track_rel: bad count: %p\n", track); 555 if (active & 0x80000000) 556 wakeup(track); 557 break; 558 } 559 active = track->bk_active; 560 } 561 } 562 563 /* 564 * Wait for the tracking count to reach 0. 565 * 566 * Use atomic ops such that the wait flag is only set atomically when 567 * bk_active is non-zero. 568 * 569 * MPSAFE 570 */ 571 int 572 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo) 573 { 574 int active; 575 int desired; 576 int error; 577 578 /* 579 * Shortcut 580 */ 581 if (track->bk_active == 0) 582 return(0); 583 584 /* 585 * Full-on. Note that the wait flag may only be atomically set if 586 * the active count is non-zero. 587 * 588 * NOTE: We cannot optimize active == desired since a wakeup could 589 * clear active prior to our tsleep_interlock(). 590 */ 591 error = 0; 592 while ((active = track->bk_active) != 0) { 593 cpu_ccfence(); 594 desired = active | 0x80000000; 595 tsleep_interlock(track, slp_flags); 596 if (atomic_cmpset_int(&track->bk_active, active, desired)) { 597 error = tsleep(track, slp_flags | PINTERLOCKED, 598 "trwait", slp_timo); 599 if (error) 600 break; 601 } 602 } 603 return (error); 604 } 605 606 /* 607 * bufinit: 608 * 609 * Load time initialisation of the buffer cache, called from machine 610 * dependant initialization code. 611 */ 612 void 613 bufinit(void) 614 { 615 struct buf *bp; 616 vm_offset_t bogus_offset; 617 int i; 618 619 /* next, make a null set of free lists */ 620 for (i = 0; i < BUFFER_QUEUES; i++) 621 TAILQ_INIT(&bufqueues[i]); 622 623 /* finally, initialize each buffer header and stick on empty q */ 624 for (i = 0; i < nbuf; i++) { 625 bp = &buf[i]; 626 bzero(bp, sizeof *bp); 627 bp->b_flags = B_INVAL; /* we're just an empty header */ 628 bp->b_cmd = BUF_CMD_DONE; 629 bp->b_qindex = BQUEUE_EMPTY; 630 initbufbio(bp); 631 xio_init(&bp->b_xio); 632 buf_dep_init(bp); 633 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist); 634 } 635 636 /* 637 * maxbufspace is the absolute maximum amount of buffer space we are 638 * allowed to reserve in KVM and in real terms. The absolute maximum 639 * is nominally used by buf_daemon. hibufspace is the nominal maximum 640 * used by most other processes. The differential is required to 641 * ensure that buf_daemon is able to run when other processes might 642 * be blocked waiting for buffer space. 643 * 644 * maxbufspace is based on BKVASIZE. Allocating buffers larger then 645 * this may result in KVM fragmentation which is not handled optimally 646 * by the system. 647 */ 648 maxbufspace = (long)nbuf * BKVASIZE; 649 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10); 650 lobufspace = hibufspace - MAXBSIZE; 651 652 lorunningspace = 512 * 1024; 653 /* hirunningspace -- see below */ 654 655 /* 656 * Limit the amount of malloc memory since it is wired permanently 657 * into the kernel space. Even though this is accounted for in 658 * the buffer allocation, we don't want the malloced region to grow 659 * uncontrolled. The malloc scheme improves memory utilization 660 * significantly on average (small) directories. 661 */ 662 maxbufmallocspace = hibufspace / 20; 663 664 /* 665 * Reduce the chance of a deadlock occuring by limiting the number 666 * of delayed-write dirty buffers we allow to stack up. 667 * 668 * We don't want too much actually queued to the device at once 669 * (XXX this needs to be per-mount!), because the buffers will 670 * wind up locked for a very long period of time while the I/O 671 * drains. 672 */ 673 hidirtybufspace = hibufspace / 2; /* dirty + running */ 674 hirunningspace = hibufspace / 16; /* locked & queued to device */ 675 if (hirunningspace < 1024 * 1024) 676 hirunningspace = 1024 * 1024; 677 678 dirtybufspace = 0; 679 dirtybufspacehw = 0; 680 681 lodirtybufspace = hidirtybufspace / 2; 682 683 /* 684 * Maximum number of async ops initiated per buf_daemon loop. This is 685 * somewhat of a hack at the moment, we really need to limit ourselves 686 * based on the number of bytes of I/O in-transit that were initiated 687 * from buf_daemon. 688 */ 689 690 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE); 691 vm_object_hold(&kernel_object); 692 bogus_page = vm_page_alloc(&kernel_object, 693 (bogus_offset >> PAGE_SHIFT), 694 VM_ALLOC_NORMAL); 695 vm_object_drop(&kernel_object); 696 vmstats.v_wire_count++; 697 698 } 699 700 /* 701 * Initialize the embedded bio structures, typically used by 702 * deprecated code which tries to allocate its own struct bufs. 703 */ 704 void 705 initbufbio(struct buf *bp) 706 { 707 bp->b_bio1.bio_buf = bp; 708 bp->b_bio1.bio_prev = NULL; 709 bp->b_bio1.bio_offset = NOOFFSET; 710 bp->b_bio1.bio_next = &bp->b_bio2; 711 bp->b_bio1.bio_done = NULL; 712 bp->b_bio1.bio_flags = 0; 713 714 bp->b_bio2.bio_buf = bp; 715 bp->b_bio2.bio_prev = &bp->b_bio1; 716 bp->b_bio2.bio_offset = NOOFFSET; 717 bp->b_bio2.bio_next = NULL; 718 bp->b_bio2.bio_done = NULL; 719 bp->b_bio2.bio_flags = 0; 720 721 BUF_LOCKINIT(bp); 722 } 723 724 /* 725 * Reinitialize the embedded bio structures as well as any additional 726 * translation cache layers. 727 */ 728 void 729 reinitbufbio(struct buf *bp) 730 { 731 struct bio *bio; 732 733 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) { 734 bio->bio_done = NULL; 735 bio->bio_offset = NOOFFSET; 736 } 737 } 738 739 /* 740 * Undo the effects of an initbufbio(). 741 */ 742 void 743 uninitbufbio(struct buf *bp) 744 { 745 dsched_exit_buf(bp); 746 BUF_LOCKFREE(bp); 747 } 748 749 /* 750 * Push another BIO layer onto an existing BIO and return it. The new 751 * BIO layer may already exist, holding cached translation data. 752 */ 753 struct bio * 754 push_bio(struct bio *bio) 755 { 756 struct bio *nbio; 757 758 if ((nbio = bio->bio_next) == NULL) { 759 int index = bio - &bio->bio_buf->b_bio_array[0]; 760 if (index >= NBUF_BIO - 1) { 761 panic("push_bio: too many layers bp %p\n", 762 bio->bio_buf); 763 } 764 nbio = &bio->bio_buf->b_bio_array[index + 1]; 765 bio->bio_next = nbio; 766 nbio->bio_prev = bio; 767 nbio->bio_buf = bio->bio_buf; 768 nbio->bio_offset = NOOFFSET; 769 nbio->bio_done = NULL; 770 nbio->bio_next = NULL; 771 } 772 KKASSERT(nbio->bio_done == NULL); 773 return(nbio); 774 } 775 776 /* 777 * Pop a BIO translation layer, returning the previous layer. The 778 * must have been previously pushed. 779 */ 780 struct bio * 781 pop_bio(struct bio *bio) 782 { 783 return(bio->bio_prev); 784 } 785 786 void 787 clearbiocache(struct bio *bio) 788 { 789 while (bio) { 790 bio->bio_offset = NOOFFSET; 791 bio = bio->bio_next; 792 } 793 } 794 795 /* 796 * bfreekva: 797 * 798 * Free the KVA allocation for buffer 'bp'. 799 * 800 * Must be called from a critical section as this is the only locking for 801 * buffer_map. 802 * 803 * Since this call frees up buffer space, we call bufspacewakeup(). 804 * 805 * MPALMOSTSAFE 806 */ 807 static void 808 bfreekva(struct buf *bp) 809 { 810 int count; 811 812 if (bp->b_kvasize) { 813 ++buffreekvacnt; 814 count = vm_map_entry_reserve(MAP_RESERVE_COUNT); 815 vm_map_lock(&buffer_map); 816 bufspace -= bp->b_kvasize; 817 vm_map_delete(&buffer_map, 818 (vm_offset_t) bp->b_kvabase, 819 (vm_offset_t) bp->b_kvabase + bp->b_kvasize, 820 &count 821 ); 822 vm_map_unlock(&buffer_map); 823 vm_map_entry_release(count); 824 bp->b_kvasize = 0; 825 bp->b_kvabase = NULL; 826 bufspacewakeup(); 827 } 828 } 829 830 /* 831 * bremfree: 832 * 833 * Remove the buffer from the appropriate free list. 834 */ 835 static __inline void 836 _bremfree(struct buf *bp) 837 { 838 if (bp->b_qindex != BQUEUE_NONE) { 839 KASSERT(BUF_REFCNTNB(bp) == 1, 840 ("bremfree: bp %p not locked",bp)); 841 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist); 842 bp->b_qindex = BQUEUE_NONE; 843 } else { 844 if (BUF_REFCNTNB(bp) <= 1) 845 panic("bremfree: removing a buffer not on a queue"); 846 } 847 } 848 849 void 850 bremfree(struct buf *bp) 851 { 852 spin_lock(&bufqspin); 853 _bremfree(bp); 854 spin_unlock(&bufqspin); 855 } 856 857 static void 858 bremfree_locked(struct buf *bp) 859 { 860 _bremfree(bp); 861 } 862 863 /* 864 * This version of bread issues any required I/O asyncnronously and 865 * makes a callback on completion. 866 * 867 * The callback must check whether BIO_DONE is set in the bio and issue 868 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing 869 * BIO_DONE and disposing of the I/O (bqrelse()ing it). 870 */ 871 void 872 breadcb(struct vnode *vp, off_t loffset, int size, 873 void (*func)(struct bio *), void *arg) 874 { 875 struct buf *bp; 876 877 bp = getblk(vp, loffset, size, 0, 0); 878 879 /* if not found in cache, do some I/O */ 880 if ((bp->b_flags & B_CACHE) == 0) { 881 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL); 882 bp->b_cmd = BUF_CMD_READ; 883 bp->b_bio1.bio_done = func; 884 bp->b_bio1.bio_caller_info1.ptr = arg; 885 vfs_busy_pages(vp, bp); 886 BUF_KERNPROC(bp); 887 vn_strategy(vp, &bp->b_bio1); 888 } else if (func) { 889 /* 890 * Since we are issuing the callback synchronously it cannot 891 * race the BIO_DONE, so no need for atomic ops here. 892 */ 893 /*bp->b_bio1.bio_done = func;*/ 894 bp->b_bio1.bio_caller_info1.ptr = arg; 895 bp->b_bio1.bio_flags |= BIO_DONE; 896 func(&bp->b_bio1); 897 } else { 898 bqrelse(bp); 899 } 900 } 901 902 /* 903 * breadnx() - Terminal function for bread() and breadn(). 904 * 905 * This function will start asynchronous I/O on read-ahead blocks as well 906 * as satisfy the primary request. 907 * 908 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is 909 * set, the buffer is valid and we do not have to do anything. 910 */ 911 int 912 breadnx(struct vnode *vp, off_t loffset, int size, off_t *raoffset, 913 int *rabsize, int cnt, struct buf **bpp) 914 { 915 struct buf *bp, *rabp; 916 int i; 917 int rv = 0, readwait = 0; 918 919 if (*bpp) 920 bp = *bpp; 921 else 922 *bpp = bp = getblk(vp, loffset, size, 0, 0); 923 924 /* if not found in cache, do some I/O */ 925 if ((bp->b_flags & B_CACHE) == 0) { 926 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL); 927 bp->b_cmd = BUF_CMD_READ; 928 bp->b_bio1.bio_done = biodone_sync; 929 bp->b_bio1.bio_flags |= BIO_SYNC; 930 vfs_busy_pages(vp, bp); 931 vn_strategy(vp, &bp->b_bio1); 932 ++readwait; 933 } 934 935 for (i = 0; i < cnt; i++, raoffset++, rabsize++) { 936 if (inmem(vp, *raoffset)) 937 continue; 938 rabp = getblk(vp, *raoffset, *rabsize, 0, 0); 939 940 if ((rabp->b_flags & B_CACHE) == 0) { 941 rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL); 942 rabp->b_cmd = BUF_CMD_READ; 943 vfs_busy_pages(vp, rabp); 944 BUF_KERNPROC(rabp); 945 vn_strategy(vp, &rabp->b_bio1); 946 } else { 947 brelse(rabp); 948 } 949 } 950 if (readwait) 951 rv = biowait(&bp->b_bio1, "biord"); 952 return (rv); 953 } 954 955 /* 956 * bwrite: 957 * 958 * Synchronous write, waits for completion. 959 * 960 * Write, release buffer on completion. (Done by iodone 961 * if async). Do not bother writing anything if the buffer 962 * is invalid. 963 * 964 * Note that we set B_CACHE here, indicating that buffer is 965 * fully valid and thus cacheable. This is true even of NFS 966 * now so we set it generally. This could be set either here 967 * or in biodone() since the I/O is synchronous. We put it 968 * here. 969 */ 970 int 971 bwrite(struct buf *bp) 972 { 973 int error; 974 975 if (bp->b_flags & B_INVAL) { 976 brelse(bp); 977 return (0); 978 } 979 if (BUF_REFCNTNB(bp) == 0) 980 panic("bwrite: buffer is not busy???"); 981 982 /* Mark the buffer clean */ 983 bundirty(bp); 984 985 bp->b_flags &= ~(B_ERROR | B_EINTR); 986 bp->b_flags |= B_CACHE; 987 bp->b_cmd = BUF_CMD_WRITE; 988 bp->b_bio1.bio_done = biodone_sync; 989 bp->b_bio1.bio_flags |= BIO_SYNC; 990 vfs_busy_pages(bp->b_vp, bp); 991 992 /* 993 * Normal bwrites pipeline writes. NOTE: b_bufsize is only 994 * valid for vnode-backed buffers. 995 */ 996 bsetrunningbufspace(bp, bp->b_bufsize); 997 vn_strategy(bp->b_vp, &bp->b_bio1); 998 error = biowait(&bp->b_bio1, "biows"); 999 brelse(bp); 1000 1001 return (error); 1002 } 1003 1004 /* 1005 * bawrite: 1006 * 1007 * Asynchronous write. Start output on a buffer, but do not wait for 1008 * it to complete. The buffer is released when the output completes. 1009 * 1010 * bwrite() ( or the VOP routine anyway ) is responsible for handling 1011 * B_INVAL buffers. Not us. 1012 */ 1013 void 1014 bawrite(struct buf *bp) 1015 { 1016 if (bp->b_flags & B_INVAL) { 1017 brelse(bp); 1018 return; 1019 } 1020 if (BUF_REFCNTNB(bp) == 0) 1021 panic("bwrite: buffer is not busy???"); 1022 1023 /* Mark the buffer clean */ 1024 bundirty(bp); 1025 1026 bp->b_flags &= ~(B_ERROR | B_EINTR); 1027 bp->b_flags |= B_CACHE; 1028 bp->b_cmd = BUF_CMD_WRITE; 1029 KKASSERT(bp->b_bio1.bio_done == NULL); 1030 vfs_busy_pages(bp->b_vp, bp); 1031 1032 /* 1033 * Normal bwrites pipeline writes. NOTE: b_bufsize is only 1034 * valid for vnode-backed buffers. 1035 */ 1036 bsetrunningbufspace(bp, bp->b_bufsize); 1037 BUF_KERNPROC(bp); 1038 vn_strategy(bp->b_vp, &bp->b_bio1); 1039 } 1040 1041 /* 1042 * bowrite: 1043 * 1044 * Ordered write. Start output on a buffer, and flag it so that the 1045 * device will write it in the order it was queued. The buffer is 1046 * released when the output completes. bwrite() ( or the VOP routine 1047 * anyway ) is responsible for handling B_INVAL buffers. 1048 */ 1049 int 1050 bowrite(struct buf *bp) 1051 { 1052 bp->b_flags |= B_ORDERED; 1053 bawrite(bp); 1054 return (0); 1055 } 1056 1057 /* 1058 * bdwrite: 1059 * 1060 * Delayed write. (Buffer is marked dirty). Do not bother writing 1061 * anything if the buffer is marked invalid. 1062 * 1063 * Note that since the buffer must be completely valid, we can safely 1064 * set B_CACHE. In fact, we have to set B_CACHE here rather then in 1065 * biodone() in order to prevent getblk from writing the buffer 1066 * out synchronously. 1067 */ 1068 void 1069 bdwrite(struct buf *bp) 1070 { 1071 if (BUF_REFCNTNB(bp) == 0) 1072 panic("bdwrite: buffer is not busy"); 1073 1074 if (bp->b_flags & B_INVAL) { 1075 brelse(bp); 1076 return; 1077 } 1078 bdirty(bp); 1079 1080 if (dsched_is_clear_buf_priv(bp)) 1081 dsched_new_buf(bp); 1082 1083 /* 1084 * Set B_CACHE, indicating that the buffer is fully valid. This is 1085 * true even of NFS now. 1086 */ 1087 bp->b_flags |= B_CACHE; 1088 1089 /* 1090 * This bmap keeps the system from needing to do the bmap later, 1091 * perhaps when the system is attempting to do a sync. Since it 1092 * is likely that the indirect block -- or whatever other datastructure 1093 * that the filesystem needs is still in memory now, it is a good 1094 * thing to do this. Note also, that if the pageout daemon is 1095 * requesting a sync -- there might not be enough memory to do 1096 * the bmap then... So, this is important to do. 1097 */ 1098 if (bp->b_bio2.bio_offset == NOOFFSET) { 1099 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset, 1100 NULL, NULL, BUF_CMD_WRITE); 1101 } 1102 1103 /* 1104 * Because the underlying pages may still be mapped and 1105 * writable trying to set the dirty buffer (b_dirtyoff/end) 1106 * range here will be inaccurate. 1107 * 1108 * However, we must still clean the pages to satisfy the 1109 * vnode_pager and pageout daemon, so theythink the pages 1110 * have been "cleaned". What has really occured is that 1111 * they've been earmarked for later writing by the buffer 1112 * cache. 1113 * 1114 * So we get the b_dirtyoff/end update but will not actually 1115 * depend on it (NFS that is) until the pages are busied for 1116 * writing later on. 1117 */ 1118 vfs_clean_pages(bp); 1119 bqrelse(bp); 1120 1121 /* 1122 * note: we cannot initiate I/O from a bdwrite even if we wanted to, 1123 * due to the softdep code. 1124 */ 1125 } 1126 1127 /* 1128 * Fake write - return pages to VM system as dirty, leave the buffer clean. 1129 * This is used by tmpfs. 1130 * 1131 * It is important for any VFS using this routine to NOT use it for 1132 * IO_SYNC or IO_ASYNC operations which occur when the system really 1133 * wants to flush VM pages to backing store. 1134 */ 1135 void 1136 buwrite(struct buf *bp) 1137 { 1138 vm_page_t m; 1139 int i; 1140 1141 /* 1142 * Only works for VMIO buffers. If the buffer is already 1143 * marked for delayed-write we can't avoid the bdwrite(). 1144 */ 1145 if ((bp->b_flags & B_VMIO) == 0 || (bp->b_flags & B_DELWRI)) { 1146 bdwrite(bp); 1147 return; 1148 } 1149 1150 /* 1151 * Set valid & dirty. 1152 */ 1153 for (i = 0; i < bp->b_xio.xio_npages; i++) { 1154 m = bp->b_xio.xio_pages[i]; 1155 vfs_dirty_one_page(bp, i, m); 1156 } 1157 bqrelse(bp); 1158 } 1159 1160 /* 1161 * bdirty: 1162 * 1163 * Turn buffer into delayed write request by marking it B_DELWRI. 1164 * B_RELBUF and B_NOCACHE must be cleared. 1165 * 1166 * We reassign the buffer to itself to properly update it in the 1167 * dirty/clean lists. 1168 * 1169 * Must be called from a critical section. 1170 * The buffer must be on BQUEUE_NONE. 1171 */ 1172 void 1173 bdirty(struct buf *bp) 1174 { 1175 KASSERT(bp->b_qindex == BQUEUE_NONE, 1176 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex)); 1177 if (bp->b_flags & B_NOCACHE) { 1178 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp); 1179 bp->b_flags &= ~B_NOCACHE; 1180 } 1181 if (bp->b_flags & B_INVAL) { 1182 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp); 1183 } 1184 bp->b_flags &= ~B_RELBUF; 1185 1186 if ((bp->b_flags & B_DELWRI) == 0) { 1187 lwkt_gettoken(&bp->b_vp->v_token); 1188 bp->b_flags |= B_DELWRI; 1189 reassignbuf(bp); 1190 lwkt_reltoken(&bp->b_vp->v_token); 1191 1192 spin_lock(&bufcspin); 1193 ++dirtybufcount; 1194 dirtybufspace += bp->b_bufsize; 1195 if (bp->b_flags & B_HEAVY) { 1196 ++dirtybufcounthw; 1197 dirtybufspacehw += bp->b_bufsize; 1198 } 1199 spin_unlock(&bufcspin); 1200 1201 bd_heatup(); 1202 } 1203 } 1204 1205 /* 1206 * Set B_HEAVY, indicating that this is a heavy-weight buffer that 1207 * needs to be flushed with a different buf_daemon thread to avoid 1208 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf(). 1209 */ 1210 void 1211 bheavy(struct buf *bp) 1212 { 1213 if ((bp->b_flags & B_HEAVY) == 0) { 1214 bp->b_flags |= B_HEAVY; 1215 if (bp->b_flags & B_DELWRI) { 1216 spin_lock(&bufcspin); 1217 ++dirtybufcounthw; 1218 dirtybufspacehw += bp->b_bufsize; 1219 spin_unlock(&bufcspin); 1220 } 1221 } 1222 } 1223 1224 /* 1225 * bundirty: 1226 * 1227 * Clear B_DELWRI for buffer. 1228 * 1229 * Must be called from a critical section. 1230 * 1231 * The buffer is typically on BQUEUE_NONE but there is one case in 1232 * brelse() that calls this function after placing the buffer on 1233 * a different queue. 1234 * 1235 * MPSAFE 1236 */ 1237 void 1238 bundirty(struct buf *bp) 1239 { 1240 if (bp->b_flags & B_DELWRI) { 1241 lwkt_gettoken(&bp->b_vp->v_token); 1242 bp->b_flags &= ~B_DELWRI; 1243 reassignbuf(bp); 1244 lwkt_reltoken(&bp->b_vp->v_token); 1245 1246 spin_lock(&bufcspin); 1247 --dirtybufcount; 1248 dirtybufspace -= bp->b_bufsize; 1249 if (bp->b_flags & B_HEAVY) { 1250 --dirtybufcounthw; 1251 dirtybufspacehw -= bp->b_bufsize; 1252 } 1253 spin_unlock(&bufcspin); 1254 1255 bd_signal(bp->b_bufsize); 1256 } 1257 /* 1258 * Since it is now being written, we can clear its deferred write flag. 1259 */ 1260 bp->b_flags &= ~B_DEFERRED; 1261 } 1262 1263 /* 1264 * Set the b_runningbufspace field, used to track how much I/O is 1265 * in progress at any given moment. 1266 */ 1267 void 1268 bsetrunningbufspace(struct buf *bp, int bytes) 1269 { 1270 bp->b_runningbufspace = bytes; 1271 if (bytes) { 1272 spin_lock(&bufcspin); 1273 runningbufspace += bytes; 1274 ++runningbufcount; 1275 spin_unlock(&bufcspin); 1276 } 1277 } 1278 1279 /* 1280 * brelse: 1281 * 1282 * Release a busy buffer and, if requested, free its resources. The 1283 * buffer will be stashed in the appropriate bufqueue[] allowing it 1284 * to be accessed later as a cache entity or reused for other purposes. 1285 * 1286 * MPALMOSTSAFE 1287 */ 1288 void 1289 brelse(struct buf *bp) 1290 { 1291 #ifdef INVARIANTS 1292 int saved_flags = bp->b_flags; 1293 #endif 1294 1295 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp)); 1296 1297 /* 1298 * If B_NOCACHE is set we are being asked to destroy the buffer and 1299 * its backing store. Clear B_DELWRI. 1300 * 1301 * B_NOCACHE is set in two cases: (1) when the caller really wants 1302 * to destroy the buffer and backing store and (2) when the caller 1303 * wants to destroy the buffer and backing store after a write 1304 * completes. 1305 */ 1306 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) { 1307 bundirty(bp); 1308 } 1309 1310 if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) { 1311 /* 1312 * A re-dirtied buffer is only subject to destruction 1313 * by B_INVAL. B_ERROR and B_NOCACHE are ignored. 1314 */ 1315 /* leave buffer intact */ 1316 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) || 1317 (bp->b_bufsize <= 0)) { 1318 /* 1319 * Either a failed read or we were asked to free or not 1320 * cache the buffer. This path is reached with B_DELWRI 1321 * set only if B_INVAL is already set. B_NOCACHE governs 1322 * backing store destruction. 1323 * 1324 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the 1325 * buffer cannot be immediately freed. 1326 */ 1327 bp->b_flags |= B_INVAL; 1328 if (LIST_FIRST(&bp->b_dep) != NULL) 1329 buf_deallocate(bp); 1330 if (bp->b_flags & B_DELWRI) { 1331 spin_lock(&bufcspin); 1332 --dirtybufcount; 1333 dirtybufspace -= bp->b_bufsize; 1334 if (bp->b_flags & B_HEAVY) { 1335 --dirtybufcounthw; 1336 dirtybufspacehw -= bp->b_bufsize; 1337 } 1338 spin_unlock(&bufcspin); 1339 1340 bd_signal(bp->b_bufsize); 1341 } 1342 bp->b_flags &= ~(B_DELWRI | B_CACHE); 1343 } 1344 1345 /* 1346 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set, 1347 * or if b_refs is non-zero. 1348 * 1349 * If vfs_vmio_release() is called with either bit set, the 1350 * underlying pages may wind up getting freed causing a previous 1351 * write (bdwrite()) to get 'lost' because pages associated with 1352 * a B_DELWRI bp are marked clean. Pages associated with a 1353 * B_LOCKED buffer may be mapped by the filesystem. 1354 * 1355 * If we want to release the buffer ourselves (rather then the 1356 * originator asking us to release it), give the originator a 1357 * chance to countermand the release by setting B_LOCKED. 1358 * 1359 * We still allow the B_INVAL case to call vfs_vmio_release(), even 1360 * if B_DELWRI is set. 1361 * 1362 * If B_DELWRI is not set we may have to set B_RELBUF if we are low 1363 * on pages to return pages to the VM page queues. 1364 */ 1365 if ((bp->b_flags & (B_DELWRI | B_LOCKED)) || bp->b_refs) { 1366 bp->b_flags &= ~B_RELBUF; 1367 } else if (vm_page_count_min(0)) { 1368 if (LIST_FIRST(&bp->b_dep) != NULL) 1369 buf_deallocate(bp); /* can set B_LOCKED */ 1370 if (bp->b_flags & (B_DELWRI | B_LOCKED)) 1371 bp->b_flags &= ~B_RELBUF; 1372 else 1373 bp->b_flags |= B_RELBUF; 1374 } 1375 1376 /* 1377 * Make sure b_cmd is clear. It may have already been cleared by 1378 * biodone(). 1379 * 1380 * At this point destroying the buffer is governed by the B_INVAL 1381 * or B_RELBUF flags. 1382 */ 1383 bp->b_cmd = BUF_CMD_DONE; 1384 dsched_exit_buf(bp); 1385 1386 /* 1387 * VMIO buffer rundown. Make sure the VM page array is restored 1388 * after an I/O may have replaces some of the pages with bogus pages 1389 * in order to not destroy dirty pages in a fill-in read. 1390 * 1391 * Note that due to the code above, if a buffer is marked B_DELWRI 1392 * then the B_RELBUF and B_NOCACHE bits will always be clear. 1393 * B_INVAL may still be set, however. 1394 * 1395 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer 1396 * but not the backing store. B_NOCACHE will destroy the backing 1397 * store. 1398 * 1399 * Note that dirty NFS buffers contain byte-granular write ranges 1400 * and should not be destroyed w/ B_INVAL even if the backing store 1401 * is left intact. 1402 */ 1403 if (bp->b_flags & B_VMIO) { 1404 /* 1405 * Rundown for VMIO buffers which are not dirty NFS buffers. 1406 */ 1407 int i, j, resid; 1408 vm_page_t m; 1409 off_t foff; 1410 vm_pindex_t poff; 1411 vm_object_t obj; 1412 struct vnode *vp; 1413 1414 vp = bp->b_vp; 1415 1416 /* 1417 * Get the base offset and length of the buffer. Note that 1418 * in the VMIO case if the buffer block size is not 1419 * page-aligned then b_data pointer may not be page-aligned. 1420 * But our b_xio.xio_pages array *IS* page aligned. 1421 * 1422 * block sizes less then DEV_BSIZE (usually 512) are not 1423 * supported due to the page granularity bits (m->valid, 1424 * m->dirty, etc...). 1425 * 1426 * See man buf(9) for more information 1427 */ 1428 1429 resid = bp->b_bufsize; 1430 foff = bp->b_loffset; 1431 1432 for (i = 0; i < bp->b_xio.xio_npages; i++) { 1433 m = bp->b_xio.xio_pages[i]; 1434 vm_page_flag_clear(m, PG_ZERO); 1435 /* 1436 * If we hit a bogus page, fixup *all* of them 1437 * now. Note that we left these pages wired 1438 * when we removed them so they had better exist, 1439 * and they cannot be ripped out from under us so 1440 * no critical section protection is necessary. 1441 */ 1442 if (m == bogus_page) { 1443 obj = vp->v_object; 1444 poff = OFF_TO_IDX(bp->b_loffset); 1445 1446 vm_object_hold(obj); 1447 for (j = i; j < bp->b_xio.xio_npages; j++) { 1448 vm_page_t mtmp; 1449 1450 mtmp = bp->b_xio.xio_pages[j]; 1451 if (mtmp == bogus_page) { 1452 mtmp = vm_page_lookup(obj, poff + j); 1453 if (!mtmp) { 1454 panic("brelse: page missing"); 1455 } 1456 bp->b_xio.xio_pages[j] = mtmp; 1457 } 1458 } 1459 bp->b_flags &= ~B_HASBOGUS; 1460 vm_object_drop(obj); 1461 1462 if ((bp->b_flags & B_INVAL) == 0) { 1463 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 1464 bp->b_xio.xio_pages, bp->b_xio.xio_npages); 1465 } 1466 m = bp->b_xio.xio_pages[i]; 1467 } 1468 1469 /* 1470 * Invalidate the backing store if B_NOCACHE is set 1471 * (e.g. used with vinvalbuf()). If this is NFS 1472 * we impose a requirement that the block size be 1473 * a multiple of PAGE_SIZE and create a temporary 1474 * hack to basically invalidate the whole page. The 1475 * problem is that NFS uses really odd buffer sizes 1476 * especially when tracking piecemeal writes and 1477 * it also vinvalbuf()'s a lot, which would result 1478 * in only partial page validation and invalidation 1479 * here. If the file page is mmap()'d, however, 1480 * all the valid bits get set so after we invalidate 1481 * here we would end up with weird m->valid values 1482 * like 0xfc. nfs_getpages() can't handle this so 1483 * we clear all the valid bits for the NFS case 1484 * instead of just some of them. 1485 * 1486 * The real bug is the VM system having to set m->valid 1487 * to VM_PAGE_BITS_ALL for faulted-in pages, which 1488 * itself is an artifact of the whole 512-byte 1489 * granular mess that exists to support odd block 1490 * sizes and UFS meta-data block sizes (e.g. 6144). 1491 * A complete rewrite is required. 1492 * 1493 * XXX 1494 */ 1495 if (bp->b_flags & (B_NOCACHE|B_ERROR)) { 1496 int poffset = foff & PAGE_MASK; 1497 int presid; 1498 1499 presid = PAGE_SIZE - poffset; 1500 if (bp->b_vp->v_tag == VT_NFS && 1501 bp->b_vp->v_type == VREG) { 1502 ; /* entire page */ 1503 } else if (presid > resid) { 1504 presid = resid; 1505 } 1506 KASSERT(presid >= 0, ("brelse: extra page")); 1507 vm_page_set_invalid(m, poffset, presid); 1508 1509 /* 1510 * Also make sure any swap cache is removed 1511 * as it is now stale (HAMMER in particular 1512 * uses B_NOCACHE to deal with buffer 1513 * aliasing). 1514 */ 1515 swap_pager_unswapped(m); 1516 } 1517 resid -= PAGE_SIZE - (foff & PAGE_MASK); 1518 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 1519 } 1520 if (bp->b_flags & (B_INVAL | B_RELBUF)) 1521 vfs_vmio_release(bp); 1522 } else { 1523 /* 1524 * Rundown for non-VMIO buffers. 1525 */ 1526 if (bp->b_flags & (B_INVAL | B_RELBUF)) { 1527 if (bp->b_bufsize) 1528 allocbuf(bp, 0); 1529 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL); 1530 if (bp->b_vp) 1531 brelvp(bp); 1532 } 1533 } 1534 1535 if (bp->b_qindex != BQUEUE_NONE) 1536 panic("brelse: free buffer onto another queue???"); 1537 if (BUF_REFCNTNB(bp) > 1) { 1538 /* Temporary panic to verify exclusive locking */ 1539 /* This panic goes away when we allow shared refs */ 1540 panic("brelse: multiple refs"); 1541 /* NOT REACHED */ 1542 return; 1543 } 1544 1545 /* 1546 * Figure out the correct queue to place the cleaned up buffer on. 1547 * Buffers placed in the EMPTY or EMPTYKVA had better already be 1548 * disassociated from their vnode. 1549 */ 1550 spin_lock(&bufqspin); 1551 if (bp->b_flags & B_LOCKED) { 1552 /* 1553 * Buffers that are locked are placed in the locked queue 1554 * immediately, regardless of their state. 1555 */ 1556 bp->b_qindex = BQUEUE_LOCKED; 1557 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist); 1558 } else if (bp->b_bufsize == 0) { 1559 /* 1560 * Buffers with no memory. Due to conditionals near the top 1561 * of brelse() such buffers should probably already be 1562 * marked B_INVAL and disassociated from their vnode. 1563 */ 1564 bp->b_flags |= B_INVAL; 1565 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp)); 1566 KKASSERT((bp->b_flags & B_HASHED) == 0); 1567 if (bp->b_kvasize) { 1568 bp->b_qindex = BQUEUE_EMPTYKVA; 1569 } else { 1570 bp->b_qindex = BQUEUE_EMPTY; 1571 } 1572 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist); 1573 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) { 1574 /* 1575 * Buffers with junk contents. Again these buffers had better 1576 * already be disassociated from their vnode. 1577 */ 1578 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp)); 1579 KKASSERT((bp->b_flags & B_HASHED) == 0); 1580 bp->b_flags |= B_INVAL; 1581 bp->b_qindex = BQUEUE_CLEAN; 1582 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist); 1583 } else { 1584 /* 1585 * Remaining buffers. These buffers are still associated with 1586 * their vnode. 1587 */ 1588 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) { 1589 case B_DELWRI: 1590 bp->b_qindex = BQUEUE_DIRTY; 1591 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist); 1592 break; 1593 case B_DELWRI | B_HEAVY: 1594 bp->b_qindex = BQUEUE_DIRTY_HW; 1595 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp, 1596 b_freelist); 1597 break; 1598 default: 1599 /* 1600 * NOTE: Buffers are always placed at the end of the 1601 * queue. If B_AGE is not set the buffer will cycle 1602 * through the queue twice. 1603 */ 1604 bp->b_qindex = BQUEUE_CLEAN; 1605 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist); 1606 break; 1607 } 1608 } 1609 spin_unlock(&bufqspin); 1610 1611 /* 1612 * If B_INVAL, clear B_DELWRI. We've already placed the buffer 1613 * on the correct queue. 1614 */ 1615 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI)) 1616 bundirty(bp); 1617 1618 /* 1619 * The bp is on an appropriate queue unless locked. If it is not 1620 * locked or dirty we can wakeup threads waiting for buffer space. 1621 * 1622 * We've already handled the B_INVAL case ( B_DELWRI will be clear 1623 * if B_INVAL is set ). 1624 */ 1625 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0) 1626 bufcountwakeup(); 1627 1628 /* 1629 * Something we can maybe free or reuse 1630 */ 1631 if (bp->b_bufsize || bp->b_kvasize) 1632 bufspacewakeup(); 1633 1634 /* 1635 * Clean up temporary flags and unlock the buffer. 1636 */ 1637 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT); 1638 BUF_UNLOCK(bp); 1639 } 1640 1641 /* 1642 * bqrelse: 1643 * 1644 * Release a buffer back to the appropriate queue but do not try to free 1645 * it. The buffer is expected to be used again soon. 1646 * 1647 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by 1648 * biodone() to requeue an async I/O on completion. It is also used when 1649 * known good buffers need to be requeued but we think we may need the data 1650 * again soon. 1651 * 1652 * XXX we should be able to leave the B_RELBUF hint set on completion. 1653 * 1654 * MPSAFE 1655 */ 1656 void 1657 bqrelse(struct buf *bp) 1658 { 1659 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp)); 1660 1661 if (bp->b_qindex != BQUEUE_NONE) 1662 panic("bqrelse: free buffer onto another queue???"); 1663 if (BUF_REFCNTNB(bp) > 1) { 1664 /* do not release to free list */ 1665 panic("bqrelse: multiple refs"); 1666 return; 1667 } 1668 1669 buf_act_advance(bp); 1670 1671 spin_lock(&bufqspin); 1672 if (bp->b_flags & B_LOCKED) { 1673 /* 1674 * Locked buffers are released to the locked queue. However, 1675 * if the buffer is dirty it will first go into the dirty 1676 * queue and later on after the I/O completes successfully it 1677 * will be released to the locked queue. 1678 */ 1679 bp->b_qindex = BQUEUE_LOCKED; 1680 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist); 1681 } else if (bp->b_flags & B_DELWRI) { 1682 bp->b_qindex = (bp->b_flags & B_HEAVY) ? 1683 BQUEUE_DIRTY_HW : BQUEUE_DIRTY; 1684 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist); 1685 } else if (vm_page_count_min(0)) { 1686 /* 1687 * We are too low on memory, we have to try to free the 1688 * buffer (most importantly: the wired pages making up its 1689 * backing store) *now*. 1690 */ 1691 spin_unlock(&bufqspin); 1692 brelse(bp); 1693 return; 1694 } else { 1695 bp->b_qindex = BQUEUE_CLEAN; 1696 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist); 1697 } 1698 spin_unlock(&bufqspin); 1699 1700 if ((bp->b_flags & B_LOCKED) == 0 && 1701 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) { 1702 bufcountwakeup(); 1703 } 1704 1705 /* 1706 * Something we can maybe free or reuse. 1707 */ 1708 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI)) 1709 bufspacewakeup(); 1710 1711 /* 1712 * Final cleanup and unlock. Clear bits that are only used while a 1713 * buffer is actively locked. 1714 */ 1715 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF); 1716 dsched_exit_buf(bp); 1717 BUF_UNLOCK(bp); 1718 } 1719 1720 /* 1721 * Hold a buffer, preventing it from being reused. This will prevent 1722 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL 1723 * operations. If a B_INVAL operation occurs the buffer will remain held 1724 * but the underlying pages may get ripped out. 1725 * 1726 * These functions are typically used in VOP_READ/VOP_WRITE functions 1727 * to hold a buffer during a copyin or copyout, preventing deadlocks 1728 * or recursive lock panics when read()/write() is used over mmap()'d 1729 * space. 1730 * 1731 * NOTE: bqhold() requires that the buffer be locked at the time of the 1732 * hold. bqdrop() has no requirements other than the buffer having 1733 * previously been held. 1734 */ 1735 void 1736 bqhold(struct buf *bp) 1737 { 1738 atomic_add_int(&bp->b_refs, 1); 1739 } 1740 1741 void 1742 bqdrop(struct buf *bp) 1743 { 1744 KKASSERT(bp->b_refs > 0); 1745 atomic_add_int(&bp->b_refs, -1); 1746 } 1747 1748 /* 1749 * Return backing pages held by the buffer 'bp' back to the VM system. 1750 * This routine is called when the bp is invalidated, released, or 1751 * reused. 1752 * 1753 * The KVA mapping (b_data) for the underlying pages is removed by 1754 * this function. 1755 * 1756 * WARNING! This routine is integral to the low memory critical path 1757 * when a buffer is B_RELBUF'd. If the system has a severe page 1758 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE 1759 * queues so they can be reused in the current pageout daemon 1760 * pass. 1761 */ 1762 static void 1763 vfs_vmio_release(struct buf *bp) 1764 { 1765 int i; 1766 vm_page_t m; 1767 1768 for (i = 0; i < bp->b_xio.xio_npages; i++) { 1769 m = bp->b_xio.xio_pages[i]; 1770 bp->b_xio.xio_pages[i] = NULL; 1771 1772 /* 1773 * We need to own the page in order to safely unwire it. 1774 */ 1775 vm_page_busy_wait(m, FALSE, "vmiopg"); 1776 1777 /* 1778 * The VFS is telling us this is not a meta-data buffer 1779 * even if it is backed by a block device. 1780 */ 1781 if (bp->b_flags & B_NOTMETA) 1782 vm_page_flag_set(m, PG_NOTMETA); 1783 1784 /* 1785 * This is a very important bit of code. We try to track 1786 * VM page use whether the pages are wired into the buffer 1787 * cache or not. While wired into the buffer cache the 1788 * bp tracks the act_count. 1789 * 1790 * We can choose to place unwired pages on the inactive 1791 * queue (0) or active queue (1). If we place too many 1792 * on the active queue the queue will cycle the act_count 1793 * on pages we'd like to keep, just from single-use pages 1794 * (such as when doing a tar-up or file scan). 1795 */ 1796 if (bp->b_act_count < vm_cycle_point) 1797 vm_page_unwire(m, 0); 1798 else 1799 vm_page_unwire(m, 1); 1800 1801 /* 1802 * If the wire_count has dropped to 0 we may need to take 1803 * further action before unbusying the page 1804 */ 1805 if (m->wire_count == 0) { 1806 vm_page_flag_clear(m, PG_ZERO); 1807 1808 if (bp->b_flags & B_DIRECT) { 1809 /* 1810 * Attempt to free the page if B_DIRECT is 1811 * set, the caller does not desire the page 1812 * to be cached. 1813 */ 1814 vm_page_wakeup(m); 1815 vm_page_try_to_free(m); 1816 } else if ((bp->b_flags & B_NOTMETA) || 1817 vm_page_count_min(0)) { 1818 /* 1819 * Attempt to move the page to PQ_CACHE 1820 * if B_NOTMETA is set. This flag is set 1821 * by HAMMER to remove one of the two pages 1822 * present when double buffering is enabled. 1823 * 1824 * Attempt to move the page to PQ_CACHE 1825 * If we have a severe page deficit. This 1826 * will cause buffer cache operations related 1827 * to pageouts to recycle the related pages 1828 * in order to avoid a low memory deadlock. 1829 */ 1830 m->act_count = bp->b_act_count; 1831 vm_page_wakeup(m); 1832 vm_page_try_to_cache(m); 1833 } else { 1834 /* 1835 * Nominal case, leave the page on the 1836 * queue the original unwiring placed it on 1837 * (active or inactive). 1838 */ 1839 m->act_count = bp->b_act_count; 1840 vm_page_wakeup(m); 1841 } 1842 } else { 1843 vm_page_wakeup(m); 1844 } 1845 } 1846 1847 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), 1848 bp->b_xio.xio_npages); 1849 if (bp->b_bufsize) { 1850 bufspacewakeup(); 1851 bp->b_bufsize = 0; 1852 } 1853 bp->b_xio.xio_npages = 0; 1854 bp->b_flags &= ~B_VMIO; 1855 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL); 1856 if (bp->b_vp) 1857 brelvp(bp); 1858 } 1859 1860 /* 1861 * vfs_bio_awrite: 1862 * 1863 * Implement clustered async writes for clearing out B_DELWRI buffers. 1864 * This is much better then the old way of writing only one buffer at 1865 * a time. Note that we may not be presented with the buffers in the 1866 * correct order, so we search for the cluster in both directions. 1867 * 1868 * The buffer is locked on call. 1869 */ 1870 int 1871 vfs_bio_awrite(struct buf *bp) 1872 { 1873 int i; 1874 int j; 1875 off_t loffset = bp->b_loffset; 1876 struct vnode *vp = bp->b_vp; 1877 int nbytes; 1878 struct buf *bpa; 1879 int nwritten; 1880 int size; 1881 1882 /* 1883 * right now we support clustered writing only to regular files. If 1884 * we find a clusterable block we could be in the middle of a cluster 1885 * rather then at the beginning. 1886 * 1887 * NOTE: b_bio1 contains the logical loffset and is aliased 1888 * to b_loffset. b_bio2 contains the translated block number. 1889 */ 1890 if ((vp->v_type == VREG) && 1891 (vp->v_mount != 0) && /* Only on nodes that have the size info */ 1892 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) { 1893 1894 size = vp->v_mount->mnt_stat.f_iosize; 1895 1896 for (i = size; i < MAXPHYS; i += size) { 1897 if ((bpa = findblk(vp, loffset + i, FINDBLK_TEST)) && 1898 BUF_REFCNT(bpa) == 0 && 1899 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) == 1900 (B_DELWRI | B_CLUSTEROK)) && 1901 (bpa->b_bufsize == size)) { 1902 if ((bpa->b_bio2.bio_offset == NOOFFSET) || 1903 (bpa->b_bio2.bio_offset != 1904 bp->b_bio2.bio_offset + i)) 1905 break; 1906 } else { 1907 break; 1908 } 1909 } 1910 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) { 1911 if ((bpa = findblk(vp, loffset - j, FINDBLK_TEST)) && 1912 BUF_REFCNT(bpa) == 0 && 1913 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) == 1914 (B_DELWRI | B_CLUSTEROK)) && 1915 (bpa->b_bufsize == size)) { 1916 if ((bpa->b_bio2.bio_offset == NOOFFSET) || 1917 (bpa->b_bio2.bio_offset != 1918 bp->b_bio2.bio_offset - j)) 1919 break; 1920 } else { 1921 break; 1922 } 1923 } 1924 j -= size; 1925 nbytes = (i + j); 1926 1927 /* 1928 * this is a possible cluster write 1929 */ 1930 if (nbytes != size) { 1931 BUF_UNLOCK(bp); 1932 nwritten = cluster_wbuild(vp, size, 1933 loffset - j, nbytes); 1934 return nwritten; 1935 } 1936 } 1937 1938 /* 1939 * default (old) behavior, writing out only one block 1940 * 1941 * XXX returns b_bufsize instead of b_bcount for nwritten? 1942 */ 1943 nwritten = bp->b_bufsize; 1944 bremfree(bp); 1945 bawrite(bp); 1946 1947 return nwritten; 1948 } 1949 1950 /* 1951 * getnewbuf: 1952 * 1953 * Find and initialize a new buffer header, freeing up existing buffers 1954 * in the bufqueues as necessary. The new buffer is returned locked. 1955 * 1956 * Important: B_INVAL is not set. If the caller wishes to throw the 1957 * buffer away, the caller must set B_INVAL prior to calling brelse(). 1958 * 1959 * We block if: 1960 * We have insufficient buffer headers 1961 * We have insufficient buffer space 1962 * buffer_map is too fragmented ( space reservation fails ) 1963 * If we have to flush dirty buffers ( but we try to avoid this ) 1964 * 1965 * To avoid VFS layer recursion we do not flush dirty buffers ourselves. 1966 * Instead we ask the buf daemon to do it for us. We attempt to 1967 * avoid piecemeal wakeups of the pageout daemon. 1968 * 1969 * MPALMOSTSAFE 1970 */ 1971 struct buf * 1972 getnewbuf(int blkflags, int slptimeo, int size, int maxsize) 1973 { 1974 struct buf *bp; 1975 struct buf *nbp; 1976 int defrag = 0; 1977 int nqindex; 1978 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0; 1979 static int flushingbufs; 1980 1981 /* 1982 * We can't afford to block since we might be holding a vnode lock, 1983 * which may prevent system daemons from running. We deal with 1984 * low-memory situations by proactively returning memory and running 1985 * async I/O rather then sync I/O. 1986 */ 1987 1988 ++getnewbufcalls; 1989 --getnewbufrestarts; 1990 restart: 1991 ++getnewbufrestarts; 1992 1993 /* 1994 * Setup for scan. If we do not have enough free buffers, 1995 * we setup a degenerate case that immediately fails. Note 1996 * that if we are specially marked process, we are allowed to 1997 * dip into our reserves. 1998 * 1999 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN 2000 * 2001 * We start with EMPTYKVA. If the list is empty we backup to EMPTY. 2002 * However, there are a number of cases (defragging, reusing, ...) 2003 * where we cannot backup. 2004 */ 2005 nqindex = BQUEUE_EMPTYKVA; 2006 spin_lock(&bufqspin); 2007 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]); 2008 2009 if (nbp == NULL) { 2010 /* 2011 * If no EMPTYKVA buffers and we are either 2012 * defragging or reusing, locate a CLEAN buffer 2013 * to free or reuse. If bufspace useage is low 2014 * skip this step so we can allocate a new buffer. 2015 */ 2016 if (defrag || bufspace >= lobufspace) { 2017 nqindex = BQUEUE_CLEAN; 2018 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]); 2019 } 2020 2021 /* 2022 * If we could not find or were not allowed to reuse a 2023 * CLEAN buffer, check to see if it is ok to use an EMPTY 2024 * buffer. We can only use an EMPTY buffer if allocating 2025 * its KVA would not otherwise run us out of buffer space. 2026 */ 2027 if (nbp == NULL && defrag == 0 && 2028 bufspace + maxsize < hibufspace) { 2029 nqindex = BQUEUE_EMPTY; 2030 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]); 2031 } 2032 } 2033 2034 /* 2035 * Run scan, possibly freeing data and/or kva mappings on the fly 2036 * depending. 2037 * 2038 * WARNING! bufqspin is held! 2039 */ 2040 while ((bp = nbp) != NULL) { 2041 int qindex = nqindex; 2042 2043 nbp = TAILQ_NEXT(bp, b_freelist); 2044 2045 /* 2046 * BQUEUE_CLEAN - B_AGE special case. If not set the bp 2047 * cycles through the queue twice before being selected. 2048 */ 2049 if (qindex == BQUEUE_CLEAN && 2050 (bp->b_flags & B_AGE) == 0 && nbp) { 2051 bp->b_flags |= B_AGE; 2052 TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist); 2053 TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist); 2054 continue; 2055 } 2056 2057 /* 2058 * Calculate next bp ( we can only use it if we do not block 2059 * or do other fancy things ). 2060 */ 2061 if (nbp == NULL) { 2062 switch(qindex) { 2063 case BQUEUE_EMPTY: 2064 nqindex = BQUEUE_EMPTYKVA; 2065 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]))) 2066 break; 2067 /* fall through */ 2068 case BQUEUE_EMPTYKVA: 2069 nqindex = BQUEUE_CLEAN; 2070 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]))) 2071 break; 2072 /* fall through */ 2073 case BQUEUE_CLEAN: 2074 /* 2075 * nbp is NULL. 2076 */ 2077 break; 2078 } 2079 } 2080 2081 /* 2082 * Sanity Checks 2083 */ 2084 KASSERT(bp->b_qindex == qindex, 2085 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp)); 2086 2087 /* 2088 * Note: we no longer distinguish between VMIO and non-VMIO 2089 * buffers. 2090 */ 2091 KASSERT((bp->b_flags & B_DELWRI) == 0, 2092 ("delwri buffer %p found in queue %d", bp, qindex)); 2093 2094 /* 2095 * Do not try to reuse a buffer with a non-zero b_refs. 2096 * This is an unsynchronized test. A synchronized test 2097 * is also performed after we lock the buffer. 2098 */ 2099 if (bp->b_refs) 2100 continue; 2101 2102 /* 2103 * If we are defragging then we need a buffer with 2104 * b_kvasize != 0. XXX this situation should no longer 2105 * occur, if defrag is non-zero the buffer's b_kvasize 2106 * should also be non-zero at this point. XXX 2107 */ 2108 if (defrag && bp->b_kvasize == 0) { 2109 kprintf("Warning: defrag empty buffer %p\n", bp); 2110 continue; 2111 } 2112 2113 /* 2114 * Start freeing the bp. This is somewhat involved. nbp 2115 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers 2116 * on the clean list must be disassociated from their 2117 * current vnode. Buffers on the empty[kva] lists have 2118 * already been disassociated. 2119 * 2120 * b_refs is checked after locking along with queue changes. 2121 * We must check here to deal with zero->nonzero transitions 2122 * made by the owner of the buffer lock, which is used by 2123 * VFS's to hold the buffer while issuing an unlocked 2124 * uiomove()s. We cannot invalidate the buffer's pages 2125 * for this case. Once we successfully lock a buffer the 2126 * only 0->1 transitions of b_refs will occur via findblk(). 2127 * 2128 * We must also check for queue changes after successful 2129 * locking as the current lock holder may dispose of the 2130 * buffer and change its queue. 2131 */ 2132 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) { 2133 spin_unlock(&bufqspin); 2134 tsleep(&bd_request, 0, "gnbxxx", (hz + 99) / 100); 2135 goto restart; 2136 } 2137 if (bp->b_qindex != qindex || bp->b_refs) { 2138 spin_unlock(&bufqspin); 2139 BUF_UNLOCK(bp); 2140 goto restart; 2141 } 2142 bremfree_locked(bp); 2143 spin_unlock(&bufqspin); 2144 2145 /* 2146 * Dependancies must be handled before we disassociate the 2147 * vnode. 2148 * 2149 * NOTE: HAMMER will set B_LOCKED if the buffer cannot 2150 * be immediately disassociated. HAMMER then becomes 2151 * responsible for releasing the buffer. 2152 * 2153 * NOTE: bufqspin is UNLOCKED now. 2154 */ 2155 if (LIST_FIRST(&bp->b_dep) != NULL) { 2156 buf_deallocate(bp); 2157 if (bp->b_flags & B_LOCKED) { 2158 bqrelse(bp); 2159 goto restart; 2160 } 2161 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL); 2162 } 2163 2164 if (qindex == BQUEUE_CLEAN) { 2165 if (bp->b_flags & B_VMIO) 2166 vfs_vmio_release(bp); 2167 if (bp->b_vp) 2168 brelvp(bp); 2169 } 2170 2171 /* 2172 * NOTE: nbp is now entirely invalid. We can only restart 2173 * the scan from this point on. 2174 * 2175 * Get the rest of the buffer freed up. b_kva* is still 2176 * valid after this operation. 2177 */ 2178 KASSERT(bp->b_vp == NULL, 2179 ("bp3 %p flags %08x vnode %p qindex %d " 2180 "unexpectededly still associated!", 2181 bp, bp->b_flags, bp->b_vp, qindex)); 2182 KKASSERT((bp->b_flags & B_HASHED) == 0); 2183 2184 /* 2185 * critical section protection is not required when 2186 * scrapping a buffer's contents because it is already 2187 * wired. 2188 */ 2189 if (bp->b_bufsize) 2190 allocbuf(bp, 0); 2191 2192 bp->b_flags = B_BNOCLIP; 2193 bp->b_cmd = BUF_CMD_DONE; 2194 bp->b_vp = NULL; 2195 bp->b_error = 0; 2196 bp->b_resid = 0; 2197 bp->b_bcount = 0; 2198 bp->b_xio.xio_npages = 0; 2199 bp->b_dirtyoff = bp->b_dirtyend = 0; 2200 bp->b_act_count = ACT_INIT; 2201 reinitbufbio(bp); 2202 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL); 2203 buf_dep_init(bp); 2204 if (blkflags & GETBLK_BHEAVY) 2205 bp->b_flags |= B_HEAVY; 2206 2207 /* 2208 * If we are defragging then free the buffer. 2209 */ 2210 if (defrag) { 2211 bp->b_flags |= B_INVAL; 2212 bfreekva(bp); 2213 brelse(bp); 2214 defrag = 0; 2215 goto restart; 2216 } 2217 2218 /* 2219 * If we are overcomitted then recover the buffer and its 2220 * KVM space. This occurs in rare situations when multiple 2221 * processes are blocked in getnewbuf() or allocbuf(). 2222 */ 2223 if (bufspace >= hibufspace) 2224 flushingbufs = 1; 2225 if (flushingbufs && bp->b_kvasize != 0) { 2226 bp->b_flags |= B_INVAL; 2227 bfreekva(bp); 2228 brelse(bp); 2229 goto restart; 2230 } 2231 if (bufspace < lobufspace) 2232 flushingbufs = 0; 2233 2234 /* 2235 * b_refs can transition to a non-zero value while we hold 2236 * the buffer locked due to a findblk(). Our brelvp() above 2237 * interlocked any future possible transitions due to 2238 * findblk()s. 2239 * 2240 * If we find b_refs to be non-zero we can destroy the 2241 * buffer's contents but we cannot yet reuse the buffer. 2242 */ 2243 if (bp->b_refs) { 2244 bp->b_flags |= B_INVAL; 2245 bfreekva(bp); 2246 brelse(bp); 2247 goto restart; 2248 } 2249 break; 2250 /* NOT REACHED, bufqspin not held */ 2251 } 2252 2253 /* 2254 * If we exhausted our list, sleep as appropriate. We may have to 2255 * wakeup various daemons and write out some dirty buffers. 2256 * 2257 * Generally we are sleeping due to insufficient buffer space. 2258 * 2259 * NOTE: bufqspin is held if bp is NULL, else it is not held. 2260 */ 2261 if (bp == NULL) { 2262 int flags; 2263 char *waitmsg; 2264 2265 spin_unlock(&bufqspin); 2266 if (defrag) { 2267 flags = VFS_BIO_NEED_BUFSPACE; 2268 waitmsg = "nbufkv"; 2269 } else if (bufspace >= hibufspace) { 2270 waitmsg = "nbufbs"; 2271 flags = VFS_BIO_NEED_BUFSPACE; 2272 } else { 2273 waitmsg = "newbuf"; 2274 flags = VFS_BIO_NEED_ANY; 2275 } 2276 2277 bd_speedup(); /* heeeelp */ 2278 spin_lock(&bufcspin); 2279 needsbuffer |= flags; 2280 while (needsbuffer & flags) { 2281 if (ssleep(&needsbuffer, &bufcspin, 2282 slpflags, waitmsg, slptimeo)) { 2283 spin_unlock(&bufcspin); 2284 return (NULL); 2285 } 2286 } 2287 spin_unlock(&bufcspin); 2288 } else { 2289 /* 2290 * We finally have a valid bp. We aren't quite out of the 2291 * woods, we still have to reserve kva space. In order 2292 * to keep fragmentation sane we only allocate kva in 2293 * BKVASIZE chunks. 2294 * 2295 * (bufqspin is not held) 2296 */ 2297 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK; 2298 2299 if (maxsize != bp->b_kvasize) { 2300 vm_offset_t addr = 0; 2301 int count; 2302 2303 bfreekva(bp); 2304 2305 count = vm_map_entry_reserve(MAP_RESERVE_COUNT); 2306 vm_map_lock(&buffer_map); 2307 2308 if (vm_map_findspace(&buffer_map, 2309 vm_map_min(&buffer_map), maxsize, 2310 maxsize, 0, &addr)) { 2311 /* 2312 * Uh oh. Buffer map is too fragmented. We 2313 * must defragment the map. 2314 */ 2315 vm_map_unlock(&buffer_map); 2316 vm_map_entry_release(count); 2317 ++bufdefragcnt; 2318 defrag = 1; 2319 bp->b_flags |= B_INVAL; 2320 brelse(bp); 2321 goto restart; 2322 } 2323 if (addr) { 2324 vm_map_insert(&buffer_map, &count, 2325 NULL, 0, 2326 addr, addr + maxsize, 2327 VM_MAPTYPE_NORMAL, 2328 VM_PROT_ALL, VM_PROT_ALL, 2329 MAP_NOFAULT); 2330 2331 bp->b_kvabase = (caddr_t) addr; 2332 bp->b_kvasize = maxsize; 2333 bufspace += bp->b_kvasize; 2334 ++bufreusecnt; 2335 } 2336 vm_map_unlock(&buffer_map); 2337 vm_map_entry_release(count); 2338 } 2339 bp->b_data = bp->b_kvabase; 2340 } 2341 return(bp); 2342 } 2343 2344 #if 0 2345 /* 2346 * This routine is called in an emergency to recover VM pages from the 2347 * buffer cache by cashing in clean buffers. The idea is to recover 2348 * enough pages to be able to satisfy a stuck bio_page_alloc(). 2349 * 2350 * XXX Currently not implemented. This function can wind up deadlocking 2351 * against another thread holding one or more of the backing pages busy. 2352 */ 2353 static int 2354 recoverbufpages(void) 2355 { 2356 struct buf *bp; 2357 int bytes = 0; 2358 2359 ++recoverbufcalls; 2360 2361 spin_lock(&bufqspin); 2362 while (bytes < MAXBSIZE) { 2363 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]); 2364 if (bp == NULL) 2365 break; 2366 2367 /* 2368 * BQUEUE_CLEAN - B_AGE special case. If not set the bp 2369 * cycles through the queue twice before being selected. 2370 */ 2371 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) { 2372 bp->b_flags |= B_AGE; 2373 TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist); 2374 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], 2375 bp, b_freelist); 2376 continue; 2377 } 2378 2379 /* 2380 * Sanity Checks 2381 */ 2382 KKASSERT(bp->b_qindex == BQUEUE_CLEAN); 2383 KKASSERT((bp->b_flags & B_DELWRI) == 0); 2384 2385 /* 2386 * Start freeing the bp. This is somewhat involved. 2387 * 2388 * Buffers on the clean list must be disassociated from 2389 * their current vnode 2390 */ 2391 2392 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) { 2393 kprintf("recoverbufpages: warning, locked buf %p, " 2394 "race corrected\n", 2395 bp); 2396 ssleep(&bd_request, &bufqspin, 0, "gnbxxx", hz / 100); 2397 continue; 2398 } 2399 if (bp->b_qindex != BQUEUE_CLEAN) { 2400 kprintf("recoverbufpages: warning, BUF_LOCK blocked " 2401 "unexpectedly on buf %p index %d, race " 2402 "corrected\n", 2403 bp, bp->b_qindex); 2404 BUF_UNLOCK(bp); 2405 continue; 2406 } 2407 bremfree_locked(bp); 2408 spin_unlock(&bufqspin); 2409 2410 /* 2411 * Dependancies must be handled before we disassociate the 2412 * vnode. 2413 * 2414 * NOTE: HAMMER will set B_LOCKED if the buffer cannot 2415 * be immediately disassociated. HAMMER then becomes 2416 * responsible for releasing the buffer. 2417 */ 2418 if (LIST_FIRST(&bp->b_dep) != NULL) { 2419 buf_deallocate(bp); 2420 if (bp->b_flags & B_LOCKED) { 2421 bqrelse(bp); 2422 spin_lock(&bufqspin); 2423 continue; 2424 } 2425 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL); 2426 } 2427 2428 bytes += bp->b_bufsize; 2429 2430 if (bp->b_flags & B_VMIO) { 2431 bp->b_flags |= B_DIRECT; /* try to free pages */ 2432 vfs_vmio_release(bp); 2433 } 2434 if (bp->b_vp) 2435 brelvp(bp); 2436 2437 KKASSERT(bp->b_vp == NULL); 2438 KKASSERT((bp->b_flags & B_HASHED) == 0); 2439 2440 /* 2441 * critical section protection is not required when 2442 * scrapping a buffer's contents because it is already 2443 * wired. 2444 */ 2445 if (bp->b_bufsize) 2446 allocbuf(bp, 0); 2447 2448 bp->b_flags = B_BNOCLIP; 2449 bp->b_cmd = BUF_CMD_DONE; 2450 bp->b_vp = NULL; 2451 bp->b_error = 0; 2452 bp->b_resid = 0; 2453 bp->b_bcount = 0; 2454 bp->b_xio.xio_npages = 0; 2455 bp->b_dirtyoff = bp->b_dirtyend = 0; 2456 reinitbufbio(bp); 2457 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL); 2458 buf_dep_init(bp); 2459 bp->b_flags |= B_INVAL; 2460 /* bfreekva(bp); */ 2461 brelse(bp); 2462 spin_lock(&bufqspin); 2463 } 2464 spin_unlock(&bufqspin); 2465 return(bytes); 2466 } 2467 #endif 2468 2469 /* 2470 * buf_daemon: 2471 * 2472 * Buffer flushing daemon. Buffers are normally flushed by the 2473 * update daemon but if it cannot keep up this process starts to 2474 * take the load in an attempt to prevent getnewbuf() from blocking. 2475 * 2476 * Once a flush is initiated it does not stop until the number 2477 * of buffers falls below lodirtybuffers, but we will wake up anyone 2478 * waiting at the mid-point. 2479 */ 2480 static struct kproc_desc buf_kp = { 2481 "bufdaemon", 2482 buf_daemon, 2483 &bufdaemon_td 2484 }; 2485 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, 2486 kproc_start, &buf_kp) 2487 2488 static struct kproc_desc bufhw_kp = { 2489 "bufdaemon_hw", 2490 buf_daemon_hw, 2491 &bufdaemonhw_td 2492 }; 2493 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, 2494 kproc_start, &bufhw_kp) 2495 2496 /* 2497 * MPSAFE thread 2498 */ 2499 static void 2500 buf_daemon1(struct thread *td, int queue, int (*buf_limit_fn)(long), 2501 int *bd_req) 2502 { 2503 long limit; 2504 2505 /* 2506 * This process needs to be suspended prior to shutdown sync. 2507 */ 2508 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, 2509 td, SHUTDOWN_PRI_LAST); 2510 curthread->td_flags |= TDF_SYSTHREAD; 2511 2512 /* 2513 * This process is allowed to take the buffer cache to the limit 2514 */ 2515 for (;;) { 2516 kproc_suspend_loop(); 2517 2518 /* 2519 * Do the flush as long as the number of dirty buffers 2520 * (including those running) exceeds lodirtybufspace. 2521 * 2522 * When flushing limit running I/O to hirunningspace 2523 * Do the flush. Limit the amount of in-transit I/O we 2524 * allow to build up, otherwise we would completely saturate 2525 * the I/O system. Wakeup any waiting processes before we 2526 * normally would so they can run in parallel with our drain. 2527 * 2528 * Our aggregate normal+HW lo water mark is lodirtybufspace, 2529 * but because we split the operation into two threads we 2530 * have to cut it in half for each thread. 2531 */ 2532 waitrunningbufspace(); 2533 limit = lodirtybufspace / 2; 2534 while (buf_limit_fn(limit)) { 2535 if (flushbufqueues(queue) == 0) 2536 break; 2537 if (runningbufspace < hirunningspace) 2538 continue; 2539 waitrunningbufspace(); 2540 } 2541 2542 /* 2543 * We reached our low water mark, reset the 2544 * request and sleep until we are needed again. 2545 * The sleep is just so the suspend code works. 2546 */ 2547 spin_lock(&bufcspin); 2548 if (*bd_req == 0) 2549 ssleep(bd_req, &bufcspin, 0, "psleep", hz); 2550 *bd_req = 0; 2551 spin_unlock(&bufcspin); 2552 } 2553 } 2554 2555 static int 2556 buf_daemon_limit(long limit) 2557 { 2558 return (runningbufspace + dirtybufspace > limit || 2559 dirtybufcount - dirtybufcounthw >= nbuf / 2); 2560 } 2561 2562 static int 2563 buf_daemon_hw_limit(long limit) 2564 { 2565 return (runningbufspace + dirtybufspacehw > limit || 2566 dirtybufcounthw >= nbuf / 2); 2567 } 2568 2569 static void 2570 buf_daemon(void) 2571 { 2572 buf_daemon1(bufdaemon_td, BQUEUE_DIRTY, buf_daemon_limit, 2573 &bd_request); 2574 } 2575 2576 static void 2577 buf_daemon_hw(void) 2578 { 2579 buf_daemon1(bufdaemonhw_td, BQUEUE_DIRTY_HW, buf_daemon_hw_limit, 2580 &bd_request_hw); 2581 } 2582 2583 /* 2584 * flushbufqueues: 2585 * 2586 * Try to flush a buffer in the dirty queue. We must be careful to 2587 * free up B_INVAL buffers instead of write them, which NFS is 2588 * particularly sensitive to. 2589 * 2590 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate 2591 * that we really want to try to get the buffer out and reuse it 2592 * due to the write load on the machine. 2593 * 2594 * We must lock the buffer in order to check its validity before we 2595 * can mess with its contents. bufqspin isn't enough. 2596 */ 2597 static int 2598 flushbufqueues(bufq_type_t q) 2599 { 2600 struct buf *bp; 2601 int r = 0; 2602 int spun; 2603 2604 spin_lock(&bufqspin); 2605 spun = 1; 2606 2607 bp = TAILQ_FIRST(&bufqueues[q]); 2608 while (bp) { 2609 if ((bp->b_flags & B_DELWRI) == 0) { 2610 kprintf("Unexpected clean buffer %p\n", bp); 2611 bp = TAILQ_NEXT(bp, b_freelist); 2612 continue; 2613 } 2614 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) { 2615 bp = TAILQ_NEXT(bp, b_freelist); 2616 continue; 2617 } 2618 KKASSERT(bp->b_qindex == q); 2619 2620 /* 2621 * Must recheck B_DELWRI after successfully locking 2622 * the buffer. 2623 */ 2624 if ((bp->b_flags & B_DELWRI) == 0) { 2625 BUF_UNLOCK(bp); 2626 bp = TAILQ_NEXT(bp, b_freelist); 2627 continue; 2628 } 2629 2630 if (bp->b_flags & B_INVAL) { 2631 _bremfree(bp); 2632 spin_unlock(&bufqspin); 2633 spun = 0; 2634 brelse(bp); 2635 ++r; 2636 break; 2637 } 2638 2639 spin_unlock(&bufqspin); 2640 lwkt_yield(); 2641 spun = 0; 2642 2643 if (LIST_FIRST(&bp->b_dep) != NULL && 2644 (bp->b_flags & B_DEFERRED) == 0 && 2645 buf_countdeps(bp, 0)) { 2646 spin_lock(&bufqspin); 2647 spun = 1; 2648 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist); 2649 TAILQ_INSERT_TAIL(&bufqueues[q], bp, b_freelist); 2650 bp->b_flags |= B_DEFERRED; 2651 BUF_UNLOCK(bp); 2652 bp = TAILQ_FIRST(&bufqueues[q]); 2653 continue; 2654 } 2655 2656 /* 2657 * If the buffer has a dependancy, buf_checkwrite() must 2658 * also return 0 for us to be able to initate the write. 2659 * 2660 * If the buffer is flagged B_ERROR it may be requeued 2661 * over and over again, we try to avoid a live lock. 2662 * 2663 * NOTE: buf_checkwrite is MPSAFE. 2664 */ 2665 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) { 2666 bremfree(bp); 2667 brelse(bp); 2668 } else if (bp->b_flags & B_ERROR) { 2669 tsleep(bp, 0, "bioer", 1); 2670 bp->b_flags &= ~B_AGE; 2671 vfs_bio_awrite(bp); 2672 } else { 2673 bp->b_flags |= B_AGE; 2674 vfs_bio_awrite(bp); 2675 } 2676 ++r; 2677 break; 2678 } 2679 if (spun) 2680 spin_unlock(&bufqspin); 2681 return (r); 2682 } 2683 2684 /* 2685 * inmem: 2686 * 2687 * Returns true if no I/O is needed to access the associated VM object. 2688 * This is like findblk except it also hunts around in the VM system for 2689 * the data. 2690 * 2691 * Note that we ignore vm_page_free() races from interrupts against our 2692 * lookup, since if the caller is not protected our return value will not 2693 * be any more valid then otherwise once we exit the critical section. 2694 */ 2695 int 2696 inmem(struct vnode *vp, off_t loffset) 2697 { 2698 vm_object_t obj; 2699 vm_offset_t toff, tinc, size; 2700 vm_page_t m; 2701 int res = 1; 2702 2703 if (findblk(vp, loffset, FINDBLK_TEST)) 2704 return 1; 2705 if (vp->v_mount == NULL) 2706 return 0; 2707 if ((obj = vp->v_object) == NULL) 2708 return 0; 2709 2710 size = PAGE_SIZE; 2711 if (size > vp->v_mount->mnt_stat.f_iosize) 2712 size = vp->v_mount->mnt_stat.f_iosize; 2713 2714 vm_object_hold(obj); 2715 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) { 2716 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff)); 2717 if (m == NULL) { 2718 res = 0; 2719 break; 2720 } 2721 tinc = size; 2722 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK)) 2723 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK); 2724 if (vm_page_is_valid(m, 2725 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0) { 2726 res = 0; 2727 break; 2728 } 2729 } 2730 vm_object_drop(obj); 2731 return (res); 2732 } 2733 2734 /* 2735 * findblk: 2736 * 2737 * Locate and return the specified buffer. Unless flagged otherwise, 2738 * a locked buffer will be returned if it exists or NULL if it does not. 2739 * 2740 * findblk()'d buffers are still on the bufqueues and if you intend 2741 * to use your (locked NON-TEST) buffer you need to bremfree(bp) 2742 * and possibly do other stuff to it. 2743 * 2744 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible 2745 * for locking the buffer and ensuring that it remains 2746 * the desired buffer after locking. 2747 * 2748 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable 2749 * to acquire the lock we return NULL, even if the 2750 * buffer exists. 2751 * 2752 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal 2753 * reuse by getnewbuf() but does not prevent 2754 * disassociation (B_INVAL). Used to avoid deadlocks 2755 * against random (vp,loffset)s due to reassignment. 2756 * 2757 * (0) - Lock the buffer blocking. 2758 * 2759 * MPSAFE 2760 */ 2761 struct buf * 2762 findblk(struct vnode *vp, off_t loffset, int flags) 2763 { 2764 struct buf *bp; 2765 int lkflags; 2766 2767 lkflags = LK_EXCLUSIVE; 2768 if (flags & FINDBLK_NBLOCK) 2769 lkflags |= LK_NOWAIT; 2770 2771 for (;;) { 2772 /* 2773 * Lookup. Ref the buf while holding v_token to prevent 2774 * reuse (but does not prevent diassociation). 2775 */ 2776 lwkt_gettoken_shared(&vp->v_token); 2777 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset); 2778 if (bp == NULL) { 2779 lwkt_reltoken(&vp->v_token); 2780 return(NULL); 2781 } 2782 bqhold(bp); 2783 lwkt_reltoken(&vp->v_token); 2784 2785 /* 2786 * If testing only break and return bp, do not lock. 2787 */ 2788 if (flags & FINDBLK_TEST) 2789 break; 2790 2791 /* 2792 * Lock the buffer, return an error if the lock fails. 2793 * (only FINDBLK_NBLOCK can cause the lock to fail). 2794 */ 2795 if (BUF_LOCK(bp, lkflags)) { 2796 atomic_subtract_int(&bp->b_refs, 1); 2797 /* bp = NULL; not needed */ 2798 return(NULL); 2799 } 2800 2801 /* 2802 * Revalidate the locked buf before allowing it to be 2803 * returned. 2804 */ 2805 if (bp->b_vp == vp && bp->b_loffset == loffset) 2806 break; 2807 atomic_subtract_int(&bp->b_refs, 1); 2808 BUF_UNLOCK(bp); 2809 } 2810 2811 /* 2812 * Success 2813 */ 2814 if ((flags & FINDBLK_REF) == 0) 2815 atomic_subtract_int(&bp->b_refs, 1); 2816 return(bp); 2817 } 2818 2819 /* 2820 * getcacheblk: 2821 * 2822 * Similar to getblk() except only returns the buffer if it is 2823 * B_CACHE and requires no other manipulation. Otherwise NULL 2824 * is returned. 2825 * 2826 * If B_RAM is set the buffer might be just fine, but we return 2827 * NULL anyway because we want the code to fall through to the 2828 * cluster read. Otherwise read-ahead breaks. 2829 * 2830 * If blksize is 0 the buffer cache buffer must already be fully 2831 * cached. 2832 * 2833 * If blksize is non-zero getblk() will be used, allowing a buffer 2834 * to be reinstantiated from its VM backing store. The buffer must 2835 * still be fully cached after reinstantiation to be returned. 2836 */ 2837 struct buf * 2838 getcacheblk(struct vnode *vp, off_t loffset, int blksize) 2839 { 2840 struct buf *bp; 2841 2842 if (blksize) { 2843 bp = getblk(vp, loffset, blksize, 0, 0); 2844 if (bp) { 2845 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) == 2846 B_CACHE) { 2847 bp->b_flags &= ~B_AGE; 2848 } else { 2849 brelse(bp); 2850 bp = NULL; 2851 } 2852 } 2853 } else { 2854 bp = findblk(vp, loffset, 0); 2855 if (bp) { 2856 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) == 2857 B_CACHE) { 2858 bp->b_flags &= ~B_AGE; 2859 bremfree(bp); 2860 } else { 2861 BUF_UNLOCK(bp); 2862 bp = NULL; 2863 } 2864 } 2865 } 2866 return (bp); 2867 } 2868 2869 /* 2870 * getblk: 2871 * 2872 * Get a block given a specified block and offset into a file/device. 2873 * B_INVAL may or may not be set on return. The caller should clear 2874 * B_INVAL prior to initiating a READ. 2875 * 2876 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE 2877 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ, 2878 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer 2879 * without doing any of those things the system will likely believe 2880 * the buffer to be valid (especially if it is not B_VMIO), and the 2881 * next getblk() will return the buffer with B_CACHE set. 2882 * 2883 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for 2884 * an existing buffer. 2885 * 2886 * For a VMIO buffer, B_CACHE is modified according to the backing VM. 2887 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set 2888 * and then cleared based on the backing VM. If the previous buffer is 2889 * non-0-sized but invalid, B_CACHE will be cleared. 2890 * 2891 * If getblk() must create a new buffer, the new buffer is returned with 2892 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which 2893 * case it is returned with B_INVAL clear and B_CACHE set based on the 2894 * backing VM. 2895 * 2896 * getblk() also forces a bwrite() for any B_DELWRI buffer whos 2897 * B_CACHE bit is clear. 2898 * 2899 * What this means, basically, is that the caller should use B_CACHE to 2900 * determine whether the buffer is fully valid or not and should clear 2901 * B_INVAL prior to issuing a read. If the caller intends to validate 2902 * the buffer by loading its data area with something, the caller needs 2903 * to clear B_INVAL. If the caller does this without issuing an I/O, 2904 * the caller should set B_CACHE ( as an optimization ), else the caller 2905 * should issue the I/O and biodone() will set B_CACHE if the I/O was 2906 * a write attempt or if it was a successfull read. If the caller 2907 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR 2908 * prior to issuing the READ. biodone() will *not* clear B_INVAL. 2909 * 2910 * getblk flags: 2911 * 2912 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return 2913 * GETBLK_BHEAVY - heavy-weight buffer cache buffer 2914 * 2915 * MPALMOSTSAFE 2916 */ 2917 struct buf * 2918 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo) 2919 { 2920 struct buf *bp; 2921 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0; 2922 int error; 2923 int lkflags; 2924 2925 if (size > MAXBSIZE) 2926 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE); 2927 if (vp->v_object == NULL) 2928 panic("getblk: vnode %p has no object!", vp); 2929 2930 loop: 2931 if ((bp = findblk(vp, loffset, FINDBLK_REF | FINDBLK_TEST)) != NULL) { 2932 /* 2933 * The buffer was found in the cache, but we need to lock it. 2934 * We must acquire a ref on the bp to prevent reuse, but 2935 * this will not prevent disassociation (brelvp()) so we 2936 * must recheck (vp,loffset) after acquiring the lock. 2937 * 2938 * Without the ref the buffer could potentially be reused 2939 * before we acquire the lock and create a deadlock 2940 * situation between the thread trying to reuse the buffer 2941 * and us due to the fact that we would wind up blocking 2942 * on a random (vp,loffset). 2943 */ 2944 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) { 2945 if (blkflags & GETBLK_NOWAIT) { 2946 bqdrop(bp); 2947 return(NULL); 2948 } 2949 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL; 2950 if (blkflags & GETBLK_PCATCH) 2951 lkflags |= LK_PCATCH; 2952 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo); 2953 if (error) { 2954 bqdrop(bp); 2955 if (error == ENOLCK) 2956 goto loop; 2957 return (NULL); 2958 } 2959 /* buffer may have changed on us */ 2960 } 2961 bqdrop(bp); 2962 2963 /* 2964 * Once the buffer has been locked, make sure we didn't race 2965 * a buffer recyclement. Buffers that are no longer hashed 2966 * will have b_vp == NULL, so this takes care of that check 2967 * as well. 2968 */ 2969 if (bp->b_vp != vp || bp->b_loffset != loffset) { 2970 kprintf("Warning buffer %p (vp %p loffset %lld) " 2971 "was recycled\n", 2972 bp, vp, (long long)loffset); 2973 BUF_UNLOCK(bp); 2974 goto loop; 2975 } 2976 2977 /* 2978 * If SZMATCH any pre-existing buffer must be of the requested 2979 * size or NULL is returned. The caller absolutely does not 2980 * want getblk() to bwrite() the buffer on a size mismatch. 2981 */ 2982 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) { 2983 BUF_UNLOCK(bp); 2984 return(NULL); 2985 } 2986 2987 /* 2988 * All vnode-based buffers must be backed by a VM object. 2989 */ 2990 KKASSERT(bp->b_flags & B_VMIO); 2991 KKASSERT(bp->b_cmd == BUF_CMD_DONE); 2992 bp->b_flags &= ~B_AGE; 2993 2994 /* 2995 * Make sure that B_INVAL buffers do not have a cached 2996 * block number translation. 2997 */ 2998 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) { 2999 kprintf("Warning invalid buffer %p (vp %p loffset %lld)" 3000 " did not have cleared bio_offset cache\n", 3001 bp, vp, (long long)loffset); 3002 clearbiocache(&bp->b_bio2); 3003 } 3004 3005 /* 3006 * The buffer is locked. B_CACHE is cleared if the buffer is 3007 * invalid. 3008 */ 3009 if (bp->b_flags & B_INVAL) 3010 bp->b_flags &= ~B_CACHE; 3011 bremfree(bp); 3012 3013 /* 3014 * Any size inconsistancy with a dirty buffer or a buffer 3015 * with a softupdates dependancy must be resolved. Resizing 3016 * the buffer in such circumstances can lead to problems. 3017 * 3018 * Dirty or dependant buffers are written synchronously. 3019 * Other types of buffers are simply released and 3020 * reconstituted as they may be backed by valid, dirty VM 3021 * pages (but not marked B_DELWRI). 3022 * 3023 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized 3024 * and may be left over from a prior truncation (and thus 3025 * no longer represent the actual EOF point), so we 3026 * definitely do not want to B_NOCACHE the backing store. 3027 */ 3028 if (size != bp->b_bcount) { 3029 if (bp->b_flags & B_DELWRI) { 3030 bp->b_flags |= B_RELBUF; 3031 bwrite(bp); 3032 } else if (LIST_FIRST(&bp->b_dep)) { 3033 bp->b_flags |= B_RELBUF; 3034 bwrite(bp); 3035 } else { 3036 bp->b_flags |= B_RELBUF; 3037 brelse(bp); 3038 } 3039 goto loop; 3040 } 3041 KKASSERT(size <= bp->b_kvasize); 3042 KASSERT(bp->b_loffset != NOOFFSET, 3043 ("getblk: no buffer offset")); 3044 3045 /* 3046 * A buffer with B_DELWRI set and B_CACHE clear must 3047 * be committed before we can return the buffer in 3048 * order to prevent the caller from issuing a read 3049 * ( due to B_CACHE not being set ) and overwriting 3050 * it. 3051 * 3052 * Most callers, including NFS and FFS, need this to 3053 * operate properly either because they assume they 3054 * can issue a read if B_CACHE is not set, or because 3055 * ( for example ) an uncached B_DELWRI might loop due 3056 * to softupdates re-dirtying the buffer. In the latter 3057 * case, B_CACHE is set after the first write completes, 3058 * preventing further loops. 3059 * 3060 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE 3061 * above while extending the buffer, we cannot allow the 3062 * buffer to remain with B_CACHE set after the write 3063 * completes or it will represent a corrupt state. To 3064 * deal with this we set B_NOCACHE to scrap the buffer 3065 * after the write. 3066 * 3067 * XXX Should this be B_RELBUF instead of B_NOCACHE? 3068 * I'm not even sure this state is still possible 3069 * now that getblk() writes out any dirty buffers 3070 * on size changes. 3071 * 3072 * We might be able to do something fancy, like setting 3073 * B_CACHE in bwrite() except if B_DELWRI is already set, 3074 * so the below call doesn't set B_CACHE, but that gets real 3075 * confusing. This is much easier. 3076 */ 3077 3078 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) { 3079 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set " 3080 "and CACHE clear, b_flags %08x\n", 3081 bp, (intmax_t)bp->b_loffset, bp->b_flags); 3082 bp->b_flags |= B_NOCACHE; 3083 bwrite(bp); 3084 goto loop; 3085 } 3086 } else { 3087 /* 3088 * Buffer is not in-core, create new buffer. The buffer 3089 * returned by getnewbuf() is locked. Note that the returned 3090 * buffer is also considered valid (not marked B_INVAL). 3091 * 3092 * Calculating the offset for the I/O requires figuring out 3093 * the block size. We use DEV_BSIZE for VBLK or VCHR and 3094 * the mount's f_iosize otherwise. If the vnode does not 3095 * have an associated mount we assume that the passed size is 3096 * the block size. 3097 * 3098 * Note that vn_isdisk() cannot be used here since it may 3099 * return a failure for numerous reasons. Note that the 3100 * buffer size may be larger then the block size (the caller 3101 * will use block numbers with the proper multiple). Beware 3102 * of using any v_* fields which are part of unions. In 3103 * particular, in DragonFly the mount point overloading 3104 * mechanism uses the namecache only and the underlying 3105 * directory vnode is not a special case. 3106 */ 3107 int bsize, maxsize; 3108 3109 if (vp->v_type == VBLK || vp->v_type == VCHR) 3110 bsize = DEV_BSIZE; 3111 else if (vp->v_mount) 3112 bsize = vp->v_mount->mnt_stat.f_iosize; 3113 else 3114 bsize = size; 3115 3116 maxsize = size + (loffset & PAGE_MASK); 3117 maxsize = imax(maxsize, bsize); 3118 3119 bp = getnewbuf(blkflags, slptimeo, size, maxsize); 3120 if (bp == NULL) { 3121 if (slpflags || slptimeo) 3122 return NULL; 3123 goto loop; 3124 } 3125 3126 /* 3127 * Atomically insert the buffer into the hash, so that it can 3128 * be found by findblk(). 3129 * 3130 * If bgetvp() returns non-zero a collision occured, and the 3131 * bp will not be associated with the vnode. 3132 * 3133 * Make sure the translation layer has been cleared. 3134 */ 3135 bp->b_loffset = loffset; 3136 bp->b_bio2.bio_offset = NOOFFSET; 3137 /* bp->b_bio2.bio_next = NULL; */ 3138 3139 if (bgetvp(vp, bp, size)) { 3140 bp->b_flags |= B_INVAL; 3141 brelse(bp); 3142 goto loop; 3143 } 3144 3145 /* 3146 * All vnode-based buffers must be backed by a VM object. 3147 */ 3148 KKASSERT(vp->v_object != NULL); 3149 bp->b_flags |= B_VMIO; 3150 KKASSERT(bp->b_cmd == BUF_CMD_DONE); 3151 3152 allocbuf(bp, size); 3153 } 3154 KKASSERT(dsched_is_clear_buf_priv(bp)); 3155 return (bp); 3156 } 3157 3158 /* 3159 * regetblk(bp) 3160 * 3161 * Reacquire a buffer that was previously released to the locked queue, 3162 * or reacquire a buffer which is interlocked by having bioops->io_deallocate 3163 * set B_LOCKED (which handles the acquisition race). 3164 * 3165 * To this end, either B_LOCKED must be set or the dependancy list must be 3166 * non-empty. 3167 * 3168 * MPSAFE 3169 */ 3170 void 3171 regetblk(struct buf *bp) 3172 { 3173 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL); 3174 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY); 3175 bremfree(bp); 3176 } 3177 3178 /* 3179 * geteblk: 3180 * 3181 * Get an empty, disassociated buffer of given size. The buffer is 3182 * initially set to B_INVAL. 3183 * 3184 * critical section protection is not required for the allocbuf() 3185 * call because races are impossible here. 3186 * 3187 * MPALMOSTSAFE 3188 */ 3189 struct buf * 3190 geteblk(int size) 3191 { 3192 struct buf *bp; 3193 int maxsize; 3194 3195 maxsize = (size + BKVAMASK) & ~BKVAMASK; 3196 3197 while ((bp = getnewbuf(0, 0, size, maxsize)) == NULL) 3198 ; 3199 allocbuf(bp, size); 3200 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */ 3201 KKASSERT(dsched_is_clear_buf_priv(bp)); 3202 return (bp); 3203 } 3204 3205 3206 /* 3207 * allocbuf: 3208 * 3209 * This code constitutes the buffer memory from either anonymous system 3210 * memory (in the case of non-VMIO operations) or from an associated 3211 * VM object (in the case of VMIO operations). This code is able to 3212 * resize a buffer up or down. 3213 * 3214 * Note that this code is tricky, and has many complications to resolve 3215 * deadlock or inconsistant data situations. Tread lightly!!! 3216 * There are B_CACHE and B_DELWRI interactions that must be dealt with by 3217 * the caller. Calling this code willy nilly can result in the loss of 3218 * data. 3219 * 3220 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with 3221 * B_CACHE for the non-VMIO case. 3222 * 3223 * This routine does not need to be called from a critical section but you 3224 * must own the buffer. 3225 * 3226 * MPSAFE 3227 */ 3228 int 3229 allocbuf(struct buf *bp, int size) 3230 { 3231 int newbsize, mbsize; 3232 int i; 3233 3234 if (BUF_REFCNT(bp) == 0) 3235 panic("allocbuf: buffer not busy"); 3236 3237 if (bp->b_kvasize < size) 3238 panic("allocbuf: buffer too small"); 3239 3240 if ((bp->b_flags & B_VMIO) == 0) { 3241 caddr_t origbuf; 3242 int origbufsize; 3243 /* 3244 * Just get anonymous memory from the kernel. Don't 3245 * mess with B_CACHE. 3246 */ 3247 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1); 3248 if (bp->b_flags & B_MALLOC) 3249 newbsize = mbsize; 3250 else 3251 newbsize = round_page(size); 3252 3253 if (newbsize < bp->b_bufsize) { 3254 /* 3255 * Malloced buffers are not shrunk 3256 */ 3257 if (bp->b_flags & B_MALLOC) { 3258 if (newbsize) { 3259 bp->b_bcount = size; 3260 } else { 3261 kfree(bp->b_data, M_BIOBUF); 3262 if (bp->b_bufsize) { 3263 atomic_subtract_long(&bufmallocspace, bp->b_bufsize); 3264 bufspacewakeup(); 3265 bp->b_bufsize = 0; 3266 } 3267 bp->b_data = bp->b_kvabase; 3268 bp->b_bcount = 0; 3269 bp->b_flags &= ~B_MALLOC; 3270 } 3271 return 1; 3272 } 3273 vm_hold_free_pages( 3274 bp, 3275 (vm_offset_t) bp->b_data + newbsize, 3276 (vm_offset_t) bp->b_data + bp->b_bufsize); 3277 } else if (newbsize > bp->b_bufsize) { 3278 /* 3279 * We only use malloced memory on the first allocation. 3280 * and revert to page-allocated memory when the buffer 3281 * grows. 3282 */ 3283 if ((bufmallocspace < maxbufmallocspace) && 3284 (bp->b_bufsize == 0) && 3285 (mbsize <= PAGE_SIZE/2)) { 3286 3287 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK); 3288 bp->b_bufsize = mbsize; 3289 bp->b_bcount = size; 3290 bp->b_flags |= B_MALLOC; 3291 atomic_add_long(&bufmallocspace, mbsize); 3292 return 1; 3293 } 3294 origbuf = NULL; 3295 origbufsize = 0; 3296 /* 3297 * If the buffer is growing on its other-than-first 3298 * allocation, then we revert to the page-allocation 3299 * scheme. 3300 */ 3301 if (bp->b_flags & B_MALLOC) { 3302 origbuf = bp->b_data; 3303 origbufsize = bp->b_bufsize; 3304 bp->b_data = bp->b_kvabase; 3305 if (bp->b_bufsize) { 3306 atomic_subtract_long(&bufmallocspace, 3307 bp->b_bufsize); 3308 bufspacewakeup(); 3309 bp->b_bufsize = 0; 3310 } 3311 bp->b_flags &= ~B_MALLOC; 3312 newbsize = round_page(newbsize); 3313 } 3314 vm_hold_load_pages( 3315 bp, 3316 (vm_offset_t) bp->b_data + bp->b_bufsize, 3317 (vm_offset_t) bp->b_data + newbsize); 3318 if (origbuf) { 3319 bcopy(origbuf, bp->b_data, origbufsize); 3320 kfree(origbuf, M_BIOBUF); 3321 } 3322 } 3323 } else { 3324 vm_page_t m; 3325 int desiredpages; 3326 3327 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1); 3328 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) + 3329 newbsize + PAGE_MASK) >> PAGE_SHIFT; 3330 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES); 3331 3332 if (bp->b_flags & B_MALLOC) 3333 panic("allocbuf: VMIO buffer can't be malloced"); 3334 /* 3335 * Set B_CACHE initially if buffer is 0 length or will become 3336 * 0-length. 3337 */ 3338 if (size == 0 || bp->b_bufsize == 0) 3339 bp->b_flags |= B_CACHE; 3340 3341 if (newbsize < bp->b_bufsize) { 3342 /* 3343 * DEV_BSIZE aligned new buffer size is less then the 3344 * DEV_BSIZE aligned existing buffer size. Figure out 3345 * if we have to remove any pages. 3346 */ 3347 if (desiredpages < bp->b_xio.xio_npages) { 3348 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) { 3349 /* 3350 * the page is not freed here -- it 3351 * is the responsibility of 3352 * vnode_pager_setsize 3353 */ 3354 m = bp->b_xio.xio_pages[i]; 3355 KASSERT(m != bogus_page, 3356 ("allocbuf: bogus page found")); 3357 vm_page_busy_wait(m, TRUE, "biodep"); 3358 bp->b_xio.xio_pages[i] = NULL; 3359 vm_page_unwire(m, 0); 3360 vm_page_wakeup(m); 3361 } 3362 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) + 3363 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages)); 3364 bp->b_xio.xio_npages = desiredpages; 3365 } 3366 } else if (size > bp->b_bcount) { 3367 /* 3368 * We are growing the buffer, possibly in a 3369 * byte-granular fashion. 3370 */ 3371 struct vnode *vp; 3372 vm_object_t obj; 3373 vm_offset_t toff; 3374 vm_offset_t tinc; 3375 3376 /* 3377 * Step 1, bring in the VM pages from the object, 3378 * allocating them if necessary. We must clear 3379 * B_CACHE if these pages are not valid for the 3380 * range covered by the buffer. 3381 * 3382 * critical section protection is required to protect 3383 * against interrupts unbusying and freeing pages 3384 * between our vm_page_lookup() and our 3385 * busycheck/wiring call. 3386 */ 3387 vp = bp->b_vp; 3388 obj = vp->v_object; 3389 3390 vm_object_hold(obj); 3391 while (bp->b_xio.xio_npages < desiredpages) { 3392 vm_page_t m; 3393 vm_pindex_t pi; 3394 int error; 3395 3396 pi = OFF_TO_IDX(bp->b_loffset) + 3397 bp->b_xio.xio_npages; 3398 3399 /* 3400 * Blocking on m->busy might lead to a 3401 * deadlock: 3402 * 3403 * vm_fault->getpages->cluster_read->allocbuf 3404 */ 3405 m = vm_page_lookup_busy_try(obj, pi, FALSE, 3406 &error); 3407 if (error) { 3408 vm_page_sleep_busy(m, FALSE, "pgtblk"); 3409 continue; 3410 } 3411 if (m == NULL) { 3412 /* 3413 * note: must allocate system pages 3414 * since blocking here could intefere 3415 * with paging I/O, no matter which 3416 * process we are. 3417 */ 3418 m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages); 3419 if (m) { 3420 vm_page_wire(m); 3421 vm_page_flag_clear(m, PG_ZERO); 3422 vm_page_wakeup(m); 3423 bp->b_flags &= ~B_CACHE; 3424 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m; 3425 ++bp->b_xio.xio_npages; 3426 } 3427 continue; 3428 } 3429 3430 /* 3431 * We found a page and were able to busy it. 3432 */ 3433 vm_page_flag_clear(m, PG_ZERO); 3434 vm_page_wire(m); 3435 vm_page_wakeup(m); 3436 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m; 3437 ++bp->b_xio.xio_npages; 3438 if (bp->b_act_count < m->act_count) 3439 bp->b_act_count = m->act_count; 3440 } 3441 vm_object_drop(obj); 3442 3443 /* 3444 * Step 2. We've loaded the pages into the buffer, 3445 * we have to figure out if we can still have B_CACHE 3446 * set. Note that B_CACHE is set according to the 3447 * byte-granular range ( bcount and size ), not the 3448 * aligned range ( newbsize ). 3449 * 3450 * The VM test is against m->valid, which is DEV_BSIZE 3451 * aligned. Needless to say, the validity of the data 3452 * needs to also be DEV_BSIZE aligned. Note that this 3453 * fails with NFS if the server or some other client 3454 * extends the file's EOF. If our buffer is resized, 3455 * B_CACHE may remain set! XXX 3456 */ 3457 3458 toff = bp->b_bcount; 3459 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK); 3460 3461 while ((bp->b_flags & B_CACHE) && toff < size) { 3462 vm_pindex_t pi; 3463 3464 if (tinc > (size - toff)) 3465 tinc = size - toff; 3466 3467 pi = ((bp->b_loffset & PAGE_MASK) + toff) >> 3468 PAGE_SHIFT; 3469 3470 vfs_buf_test_cache( 3471 bp, 3472 bp->b_loffset, 3473 toff, 3474 tinc, 3475 bp->b_xio.xio_pages[pi] 3476 ); 3477 toff += tinc; 3478 tinc = PAGE_SIZE; 3479 } 3480 3481 /* 3482 * Step 3, fixup the KVM pmap. Remember that 3483 * bp->b_data is relative to bp->b_loffset, but 3484 * bp->b_loffset may be offset into the first page. 3485 */ 3486 3487 bp->b_data = (caddr_t) 3488 trunc_page((vm_offset_t)bp->b_data); 3489 pmap_qenter( 3490 (vm_offset_t)bp->b_data, 3491 bp->b_xio.xio_pages, 3492 bp->b_xio.xio_npages 3493 ); 3494 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 3495 (vm_offset_t)(bp->b_loffset & PAGE_MASK)); 3496 } 3497 } 3498 3499 /* adjust space use on already-dirty buffer */ 3500 if (bp->b_flags & B_DELWRI) { 3501 spin_lock(&bufcspin); 3502 dirtybufspace += newbsize - bp->b_bufsize; 3503 if (bp->b_flags & B_HEAVY) 3504 dirtybufspacehw += newbsize - bp->b_bufsize; 3505 spin_unlock(&bufcspin); 3506 } 3507 if (newbsize < bp->b_bufsize) 3508 bufspacewakeup(); 3509 bp->b_bufsize = newbsize; /* actual buffer allocation */ 3510 bp->b_bcount = size; /* requested buffer size */ 3511 return 1; 3512 } 3513 3514 /* 3515 * biowait: 3516 * 3517 * Wait for buffer I/O completion, returning error status. B_EINTR 3518 * is converted into an EINTR error but not cleared (since a chain 3519 * of biowait() calls may occur). 3520 * 3521 * On return bpdone() will have been called but the buffer will remain 3522 * locked and will not have been brelse()'d. 3523 * 3524 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is 3525 * likely still in progress on return. 3526 * 3527 * NOTE! This operation is on a BIO, not a BUF. 3528 * 3529 * NOTE! BIO_DONE is cleared by vn_strategy() 3530 * 3531 * MPSAFE 3532 */ 3533 static __inline int 3534 _biowait(struct bio *bio, const char *wmesg, int to) 3535 { 3536 struct buf *bp = bio->bio_buf; 3537 u_int32_t flags; 3538 u_int32_t nflags; 3539 int error; 3540 3541 KKASSERT(bio == &bp->b_bio1); 3542 for (;;) { 3543 flags = bio->bio_flags; 3544 if (flags & BIO_DONE) 3545 break; 3546 nflags = flags | BIO_WANT; 3547 tsleep_interlock(bio, 0); 3548 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) { 3549 if (wmesg) 3550 error = tsleep(bio, PINTERLOCKED, wmesg, to); 3551 else if (bp->b_cmd == BUF_CMD_READ) 3552 error = tsleep(bio, PINTERLOCKED, "biord", to); 3553 else 3554 error = tsleep(bio, PINTERLOCKED, "biowr", to); 3555 if (error) { 3556 kprintf("tsleep error biowait %d\n", error); 3557 return (error); 3558 } 3559 } 3560 } 3561 3562 /* 3563 * Finish up. 3564 */ 3565 KKASSERT(bp->b_cmd == BUF_CMD_DONE); 3566 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC); 3567 if (bp->b_flags & B_EINTR) 3568 return (EINTR); 3569 if (bp->b_flags & B_ERROR) 3570 return (bp->b_error ? bp->b_error : EIO); 3571 return (0); 3572 } 3573 3574 int 3575 biowait(struct bio *bio, const char *wmesg) 3576 { 3577 return(_biowait(bio, wmesg, 0)); 3578 } 3579 3580 int 3581 biowait_timeout(struct bio *bio, const char *wmesg, int to) 3582 { 3583 return(_biowait(bio, wmesg, to)); 3584 } 3585 3586 /* 3587 * This associates a tracking count with an I/O. vn_strategy() and 3588 * dev_dstrategy() do this automatically but there are a few cases 3589 * where a vnode or device layer is bypassed when a block translation 3590 * is cached. In such cases bio_start_transaction() may be called on 3591 * the bypassed layers so the system gets an I/O in progress indication 3592 * for those higher layers. 3593 */ 3594 void 3595 bio_start_transaction(struct bio *bio, struct bio_track *track) 3596 { 3597 bio->bio_track = track; 3598 if (dsched_is_clear_buf_priv(bio->bio_buf)) 3599 dsched_new_buf(bio->bio_buf); 3600 bio_track_ref(track); 3601 } 3602 3603 /* 3604 * Initiate I/O on a vnode. 3605 * 3606 * SWAPCACHE OPERATION: 3607 * 3608 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately 3609 * devfs also uses b_vp for fake buffers so we also have to check 3610 * that B_PAGING is 0. In this case the passed 'vp' is probably the 3611 * underlying block device. The swap assignments are related to the 3612 * buffer cache buffer's b_vp, not the passed vp. 3613 * 3614 * The passed vp == bp->b_vp only in the case where the strategy call 3615 * is made on the vp itself for its own buffers (a regular file or 3616 * block device vp). The filesystem usually then re-calls vn_strategy() 3617 * after translating the request to an underlying device. 3618 * 3619 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the 3620 * underlying buffer cache buffers. 3621 * 3622 * We can only deal with page-aligned buffers at the moment, because 3623 * we can't tell what the real dirty state for pages straddling a buffer 3624 * are. 3625 * 3626 * In order to call swap_pager_strategy() we must provide the VM object 3627 * and base offset for the underlying buffer cache pages so it can find 3628 * the swap blocks. 3629 */ 3630 void 3631 vn_strategy(struct vnode *vp, struct bio *bio) 3632 { 3633 struct bio_track *track; 3634 struct buf *bp = bio->bio_buf; 3635 3636 KKASSERT(bp->b_cmd != BUF_CMD_DONE); 3637 3638 /* 3639 * Set when an I/O is issued on the bp. Cleared by consumers 3640 * (aka HAMMER), allowing the consumer to determine if I/O had 3641 * actually occurred. 3642 */ 3643 bp->b_flags |= B_IODEBUG; 3644 3645 /* 3646 * Handle the swap cache intercept. 3647 */ 3648 if (vn_cache_strategy(vp, bio)) 3649 return; 3650 3651 /* 3652 * Otherwise do the operation through the filesystem 3653 */ 3654 if (bp->b_cmd == BUF_CMD_READ) 3655 track = &vp->v_track_read; 3656 else 3657 track = &vp->v_track_write; 3658 KKASSERT((bio->bio_flags & BIO_DONE) == 0); 3659 bio->bio_track = track; 3660 if (dsched_is_clear_buf_priv(bio->bio_buf)) 3661 dsched_new_buf(bio->bio_buf); 3662 bio_track_ref(track); 3663 vop_strategy(*vp->v_ops, vp, bio); 3664 } 3665 3666 static void vn_cache_strategy_callback(struct bio *bio); 3667 3668 int 3669 vn_cache_strategy(struct vnode *vp, struct bio *bio) 3670 { 3671 struct buf *bp = bio->bio_buf; 3672 struct bio *nbio; 3673 vm_object_t object; 3674 vm_page_t m; 3675 int i; 3676 3677 /* 3678 * Is this buffer cache buffer suitable for reading from 3679 * the swap cache? 3680 */ 3681 if (vm_swapcache_read_enable == 0 || 3682 bp->b_cmd != BUF_CMD_READ || 3683 ((bp->b_flags & B_CLUSTER) == 0 && 3684 (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) || 3685 ((int)bp->b_loffset & PAGE_MASK) != 0 || 3686 (bp->b_bcount & PAGE_MASK) != 0) { 3687 return(0); 3688 } 3689 3690 /* 3691 * Figure out the original VM object (it will match the underlying 3692 * VM pages). Note that swap cached data uses page indices relative 3693 * to that object, not relative to bio->bio_offset. 3694 */ 3695 if (bp->b_flags & B_CLUSTER) 3696 object = vp->v_object; 3697 else 3698 object = bp->b_vp->v_object; 3699 3700 /* 3701 * In order to be able to use the swap cache all underlying VM 3702 * pages must be marked as such, and we can't have any bogus pages. 3703 */ 3704 for (i = 0; i < bp->b_xio.xio_npages; ++i) { 3705 m = bp->b_xio.xio_pages[i]; 3706 if ((m->flags & PG_SWAPPED) == 0) 3707 break; 3708 if (m == bogus_page) 3709 break; 3710 } 3711 3712 /* 3713 * If we are good then issue the I/O using swap_pager_strategy(). 3714 * 3715 * We can only do this if the buffer actually supports object-backed 3716 * I/O. If it doesn't npages will be 0. 3717 */ 3718 if (i && i == bp->b_xio.xio_npages) { 3719 m = bp->b_xio.xio_pages[0]; 3720 nbio = push_bio(bio); 3721 nbio->bio_done = vn_cache_strategy_callback; 3722 nbio->bio_offset = ptoa(m->pindex); 3723 KKASSERT(m->object == object); 3724 swap_pager_strategy(object, nbio); 3725 return(1); 3726 } 3727 return(0); 3728 } 3729 3730 /* 3731 * This is a bit of a hack but since the vn_cache_strategy() function can 3732 * override a VFS's strategy function we must make sure that the bio, which 3733 * is probably bio2, doesn't leak an unexpected offset value back to the 3734 * filesystem. The filesystem (e.g. UFS) might otherwise assume that the 3735 * bio went through its own file strategy function and the the bio2 offset 3736 * is a cached disk offset when, in fact, it isn't. 3737 */ 3738 static void 3739 vn_cache_strategy_callback(struct bio *bio) 3740 { 3741 bio->bio_offset = NOOFFSET; 3742 biodone(pop_bio(bio)); 3743 } 3744 3745 /* 3746 * bpdone: 3747 * 3748 * Finish I/O on a buffer after all BIOs have been processed. 3749 * Called when the bio chain is exhausted or by biowait. If called 3750 * by biowait, elseit is typically 0. 3751 * 3752 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp. 3753 * In a non-VMIO bp, B_CACHE will be set on the next getblk() 3754 * assuming B_INVAL is clear. 3755 * 3756 * For the VMIO case, we set B_CACHE if the op was a read and no 3757 * read error occured, or if the op was a write. B_CACHE is never 3758 * set if the buffer is invalid or otherwise uncacheable. 3759 * 3760 * bpdone does not mess with B_INVAL, allowing the I/O routine or the 3761 * initiator to leave B_INVAL set to brelse the buffer out of existance 3762 * in the biodone routine. 3763 */ 3764 void 3765 bpdone(struct buf *bp, int elseit) 3766 { 3767 buf_cmd_t cmd; 3768 3769 KASSERT(BUF_REFCNTNB(bp) > 0, 3770 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp))); 3771 KASSERT(bp->b_cmd != BUF_CMD_DONE, 3772 ("biodone: bp %p already done!", bp)); 3773 3774 /* 3775 * No more BIOs are left. All completion functions have been dealt 3776 * with, now we clean up the buffer. 3777 */ 3778 cmd = bp->b_cmd; 3779 bp->b_cmd = BUF_CMD_DONE; 3780 3781 /* 3782 * Only reads and writes are processed past this point. 3783 */ 3784 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) { 3785 if (cmd == BUF_CMD_FREEBLKS) 3786 bp->b_flags |= B_NOCACHE; 3787 if (elseit) 3788 brelse(bp); 3789 return; 3790 } 3791 3792 /* 3793 * Warning: softupdates may re-dirty the buffer, and HAMMER can do 3794 * a lot worse. XXX - move this above the clearing of b_cmd 3795 */ 3796 if (LIST_FIRST(&bp->b_dep) != NULL) 3797 buf_complete(bp); /* MPSAFE */ 3798 3799 /* 3800 * A failed write must re-dirty the buffer unless B_INVAL 3801 * was set. Only applicable to normal buffers (with VPs). 3802 * vinum buffers may not have a vp. 3803 */ 3804 if (cmd == BUF_CMD_WRITE && 3805 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) { 3806 bp->b_flags &= ~B_NOCACHE; 3807 if (bp->b_vp) 3808 bdirty(bp); 3809 } 3810 3811 if (bp->b_flags & B_VMIO) { 3812 int i; 3813 vm_ooffset_t foff; 3814 vm_page_t m; 3815 vm_object_t obj; 3816 int iosize; 3817 struct vnode *vp = bp->b_vp; 3818 3819 obj = vp->v_object; 3820 3821 #if defined(VFS_BIO_DEBUG) 3822 if (vp->v_auxrefs == 0) 3823 panic("biodone: zero vnode hold count"); 3824 if ((vp->v_flag & VOBJBUF) == 0) 3825 panic("biodone: vnode is not setup for merged cache"); 3826 #endif 3827 3828 foff = bp->b_loffset; 3829 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset")); 3830 KASSERT(obj != NULL, ("biodone: missing VM object")); 3831 3832 #if defined(VFS_BIO_DEBUG) 3833 if (obj->paging_in_progress < bp->b_xio.xio_npages) { 3834 kprintf("biodone: paging in progress(%d) < " 3835 "bp->b_xio.xio_npages(%d)\n", 3836 obj->paging_in_progress, 3837 bp->b_xio.xio_npages); 3838 } 3839 #endif 3840 3841 /* 3842 * Set B_CACHE if the op was a normal read and no error 3843 * occured. B_CACHE is set for writes in the b*write() 3844 * routines. 3845 */ 3846 iosize = bp->b_bcount - bp->b_resid; 3847 if (cmd == BUF_CMD_READ && 3848 (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) { 3849 bp->b_flags |= B_CACHE; 3850 } 3851 3852 vm_object_hold(obj); 3853 for (i = 0; i < bp->b_xio.xio_npages; i++) { 3854 int bogusflag = 0; 3855 int resid; 3856 3857 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff; 3858 if (resid > iosize) 3859 resid = iosize; 3860 3861 /* 3862 * cleanup bogus pages, restoring the originals. Since 3863 * the originals should still be wired, we don't have 3864 * to worry about interrupt/freeing races destroying 3865 * the VM object association. 3866 */ 3867 m = bp->b_xio.xio_pages[i]; 3868 if (m == bogus_page) { 3869 bogusflag = 1; 3870 m = vm_page_lookup(obj, OFF_TO_IDX(foff)); 3871 if (m == NULL) 3872 panic("biodone: page disappeared"); 3873 bp->b_xio.xio_pages[i] = m; 3874 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 3875 bp->b_xio.xio_pages, bp->b_xio.xio_npages); 3876 } 3877 #if defined(VFS_BIO_DEBUG) 3878 if (OFF_TO_IDX(foff) != m->pindex) { 3879 kprintf("biodone: foff(%lu)/m->pindex(%ld) " 3880 "mismatch\n", 3881 (unsigned long)foff, (long)m->pindex); 3882 } 3883 #endif 3884 3885 /* 3886 * In the write case, the valid and clean bits are 3887 * already changed correctly (see bdwrite()), so we 3888 * only need to do this here in the read case. 3889 */ 3890 vm_page_busy_wait(m, FALSE, "bpdpgw"); 3891 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) { 3892 vfs_clean_one_page(bp, i, m); 3893 } 3894 vm_page_flag_clear(m, PG_ZERO); 3895 3896 /* 3897 * when debugging new filesystems or buffer I/O 3898 * methods, this is the most common error that pops 3899 * up. if you see this, you have not set the page 3900 * busy flag correctly!!! 3901 */ 3902 if (m->busy == 0) { 3903 kprintf("biodone: page busy < 0, " 3904 "pindex: %d, foff: 0x(%x,%x), " 3905 "resid: %d, index: %d\n", 3906 (int) m->pindex, (int)(foff >> 32), 3907 (int) foff & 0xffffffff, resid, i); 3908 if (!vn_isdisk(vp, NULL)) 3909 kprintf(" iosize: %ld, loffset: %lld, " 3910 "flags: 0x%08x, npages: %d\n", 3911 bp->b_vp->v_mount->mnt_stat.f_iosize, 3912 (long long)bp->b_loffset, 3913 bp->b_flags, bp->b_xio.xio_npages); 3914 else 3915 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n", 3916 (long long)bp->b_loffset, 3917 bp->b_flags, bp->b_xio.xio_npages); 3918 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n", 3919 m->valid, m->dirty, m->wire_count); 3920 panic("biodone: page busy < 0"); 3921 } 3922 vm_page_io_finish(m); 3923 vm_page_wakeup(m); 3924 vm_object_pip_wakeup(obj); 3925 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK; 3926 iosize -= resid; 3927 } 3928 bp->b_flags &= ~B_HASBOGUS; 3929 vm_object_drop(obj); 3930 } 3931 3932 /* 3933 * Finish up by releasing the buffer. There are no more synchronous 3934 * or asynchronous completions, those were handled by bio_done 3935 * callbacks. 3936 */ 3937 if (elseit) { 3938 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF)) 3939 brelse(bp); 3940 else 3941 bqrelse(bp); 3942 } 3943 } 3944 3945 /* 3946 * Normal biodone. 3947 */ 3948 void 3949 biodone(struct bio *bio) 3950 { 3951 struct buf *bp = bio->bio_buf; 3952 3953 runningbufwakeup(bp); 3954 3955 /* 3956 * Run up the chain of BIO's. Leave b_cmd intact for the duration. 3957 */ 3958 while (bio) { 3959 biodone_t *done_func; 3960 struct bio_track *track; 3961 3962 /* 3963 * BIO tracking. Most but not all BIOs are tracked. 3964 */ 3965 if ((track = bio->bio_track) != NULL) { 3966 bio_track_rel(track); 3967 bio->bio_track = NULL; 3968 } 3969 3970 /* 3971 * A bio_done function terminates the loop. The function 3972 * will be responsible for any further chaining and/or 3973 * buffer management. 3974 * 3975 * WARNING! The done function can deallocate the buffer! 3976 */ 3977 if ((done_func = bio->bio_done) != NULL) { 3978 bio->bio_done = NULL; 3979 done_func(bio); 3980 return; 3981 } 3982 bio = bio->bio_prev; 3983 } 3984 3985 /* 3986 * If we've run out of bio's do normal [a]synchronous completion. 3987 */ 3988 bpdone(bp, 1); 3989 } 3990 3991 /* 3992 * Synchronous biodone - this terminates a synchronous BIO. 3993 * 3994 * bpdone() is called with elseit=FALSE, leaving the buffer completed 3995 * but still locked. The caller must brelse() the buffer after waiting 3996 * for completion. 3997 */ 3998 void 3999 biodone_sync(struct bio *bio) 4000 { 4001 struct buf *bp = bio->bio_buf; 4002 int flags; 4003 int nflags; 4004 4005 KKASSERT(bio == &bp->b_bio1); 4006 bpdone(bp, 0); 4007 4008 for (;;) { 4009 flags = bio->bio_flags; 4010 nflags = (flags | BIO_DONE) & ~BIO_WANT; 4011 4012 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) { 4013 if (flags & BIO_WANT) 4014 wakeup(bio); 4015 break; 4016 } 4017 } 4018 } 4019 4020 /* 4021 * vfs_unbusy_pages: 4022 * 4023 * This routine is called in lieu of iodone in the case of 4024 * incomplete I/O. This keeps the busy status for pages 4025 * consistant. 4026 */ 4027 void 4028 vfs_unbusy_pages(struct buf *bp) 4029 { 4030 int i; 4031 4032 runningbufwakeup(bp); 4033 4034 if (bp->b_flags & B_VMIO) { 4035 struct vnode *vp = bp->b_vp; 4036 vm_object_t obj; 4037 4038 obj = vp->v_object; 4039 vm_object_hold(obj); 4040 4041 for (i = 0; i < bp->b_xio.xio_npages; i++) { 4042 vm_page_t m = bp->b_xio.xio_pages[i]; 4043 4044 /* 4045 * When restoring bogus changes the original pages 4046 * should still be wired, so we are in no danger of 4047 * losing the object association and do not need 4048 * critical section protection particularly. 4049 */ 4050 if (m == bogus_page) { 4051 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i); 4052 if (!m) { 4053 panic("vfs_unbusy_pages: page missing"); 4054 } 4055 bp->b_xio.xio_pages[i] = m; 4056 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 4057 bp->b_xio.xio_pages, bp->b_xio.xio_npages); 4058 } 4059 vm_page_busy_wait(m, FALSE, "bpdpgw"); 4060 vm_page_flag_clear(m, PG_ZERO); 4061 vm_page_io_finish(m); 4062 vm_page_wakeup(m); 4063 vm_object_pip_wakeup(obj); 4064 } 4065 bp->b_flags &= ~B_HASBOGUS; 4066 vm_object_drop(obj); 4067 } 4068 } 4069 4070 /* 4071 * vfs_busy_pages: 4072 * 4073 * This routine is called before a device strategy routine. 4074 * It is used to tell the VM system that paging I/O is in 4075 * progress, and treat the pages associated with the buffer 4076 * almost as being PG_BUSY. Also the object 'paging_in_progress' 4077 * flag is handled to make sure that the object doesn't become 4078 * inconsistant. 4079 * 4080 * Since I/O has not been initiated yet, certain buffer flags 4081 * such as B_ERROR or B_INVAL may be in an inconsistant state 4082 * and should be ignored. 4083 * 4084 * MPSAFE 4085 */ 4086 void 4087 vfs_busy_pages(struct vnode *vp, struct buf *bp) 4088 { 4089 int i, bogus; 4090 struct lwp *lp = curthread->td_lwp; 4091 4092 /* 4093 * The buffer's I/O command must already be set. If reading, 4094 * B_CACHE must be 0 (double check against callers only doing 4095 * I/O when B_CACHE is 0). 4096 */ 4097 KKASSERT(bp->b_cmd != BUF_CMD_DONE); 4098 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0); 4099 4100 if (bp->b_flags & B_VMIO) { 4101 vm_object_t obj; 4102 4103 obj = vp->v_object; 4104 KASSERT(bp->b_loffset != NOOFFSET, 4105 ("vfs_busy_pages: no buffer offset")); 4106 4107 /* 4108 * Busy all the pages. We have to busy them all at once 4109 * to avoid deadlocks. 4110 */ 4111 retry: 4112 for (i = 0; i < bp->b_xio.xio_npages; i++) { 4113 vm_page_t m = bp->b_xio.xio_pages[i]; 4114 4115 if (vm_page_busy_try(m, FALSE)) { 4116 vm_page_sleep_busy(m, FALSE, "vbpage"); 4117 while (--i >= 0) 4118 vm_page_wakeup(bp->b_xio.xio_pages[i]); 4119 goto retry; 4120 } 4121 } 4122 4123 /* 4124 * Setup for I/O, soft-busy the page right now because 4125 * the next loop may block. 4126 */ 4127 for (i = 0; i < bp->b_xio.xio_npages; i++) { 4128 vm_page_t m = bp->b_xio.xio_pages[i]; 4129 4130 vm_page_flag_clear(m, PG_ZERO); 4131 if ((bp->b_flags & B_CLUSTER) == 0) { 4132 vm_object_pip_add(obj, 1); 4133 vm_page_io_start(m); 4134 } 4135 } 4136 4137 /* 4138 * Adjust protections for I/O and do bogus-page mapping. 4139 * Assume that vm_page_protect() can block (it can block 4140 * if VM_PROT_NONE, don't take any chances regardless). 4141 * 4142 * In particular note that for writes we must incorporate 4143 * page dirtyness from the VM system into the buffer's 4144 * dirty range. 4145 * 4146 * For reads we theoretically must incorporate page dirtyness 4147 * from the VM system to determine if the page needs bogus 4148 * replacement, but we shortcut the test by simply checking 4149 * that all m->valid bits are set, indicating that the page 4150 * is fully valid and does not need to be re-read. For any 4151 * VM system dirtyness the page will also be fully valid 4152 * since it was mapped at one point. 4153 */ 4154 bogus = 0; 4155 for (i = 0; i < bp->b_xio.xio_npages; i++) { 4156 vm_page_t m = bp->b_xio.xio_pages[i]; 4157 4158 vm_page_flag_clear(m, PG_ZERO); /* XXX */ 4159 if (bp->b_cmd == BUF_CMD_WRITE) { 4160 /* 4161 * When readying a vnode-backed buffer for 4162 * a write we must zero-fill any invalid 4163 * portions of the backing VM pages, mark 4164 * it valid and clear related dirty bits. 4165 * 4166 * vfs_clean_one_page() incorporates any 4167 * VM dirtyness and updates the b_dirtyoff 4168 * range (after we've made the page RO). 4169 * 4170 * It is also expected that the pmap modified 4171 * bit has already been cleared by the 4172 * vm_page_protect(). We may not be able 4173 * to clear all dirty bits for a page if it 4174 * was also memory mapped (NFS). 4175 * 4176 * Finally be sure to unassign any swap-cache 4177 * backing store as it is now stale. 4178 */ 4179 vm_page_protect(m, VM_PROT_READ); 4180 vfs_clean_one_page(bp, i, m); 4181 swap_pager_unswapped(m); 4182 } else if (m->valid == VM_PAGE_BITS_ALL) { 4183 /* 4184 * When readying a vnode-backed buffer for 4185 * read we must replace any dirty pages with 4186 * a bogus page so dirty data is not destroyed 4187 * when filling gaps. 4188 * 4189 * To avoid testing whether the page is 4190 * dirty we instead test that the page was 4191 * at some point mapped (m->valid fully 4192 * valid) with the understanding that 4193 * this also covers the dirty case. 4194 */ 4195 bp->b_xio.xio_pages[i] = bogus_page; 4196 bp->b_flags |= B_HASBOGUS; 4197 bogus++; 4198 } else if (m->valid & m->dirty) { 4199 /* 4200 * This case should not occur as partial 4201 * dirtyment can only happen if the buffer 4202 * is B_CACHE, and this code is not entered 4203 * if the buffer is B_CACHE. 4204 */ 4205 kprintf("Warning: vfs_busy_pages - page not " 4206 "fully valid! loff=%jx bpf=%08x " 4207 "idx=%d val=%02x dir=%02x\n", 4208 (intmax_t)bp->b_loffset, bp->b_flags, 4209 i, m->valid, m->dirty); 4210 vm_page_protect(m, VM_PROT_NONE); 4211 } else { 4212 /* 4213 * The page is not valid and can be made 4214 * part of the read. 4215 */ 4216 vm_page_protect(m, VM_PROT_NONE); 4217 } 4218 vm_page_wakeup(m); 4219 } 4220 if (bogus) { 4221 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), 4222 bp->b_xio.xio_pages, bp->b_xio.xio_npages); 4223 } 4224 } 4225 4226 /* 4227 * This is the easiest place to put the process accounting for the I/O 4228 * for now. 4229 */ 4230 if (lp != NULL) { 4231 if (bp->b_cmd == BUF_CMD_READ) 4232 lp->lwp_ru.ru_inblock++; 4233 else 4234 lp->lwp_ru.ru_oublock++; 4235 } 4236 } 4237 4238 /* 4239 * Tell the VM system that the pages associated with this buffer 4240 * are clean. This is used for delayed writes where the data is 4241 * going to go to disk eventually without additional VM intevention. 4242 * 4243 * NOTE: While we only really need to clean through to b_bcount, we 4244 * just go ahead and clean through to b_bufsize. 4245 */ 4246 static void 4247 vfs_clean_pages(struct buf *bp) 4248 { 4249 vm_page_t m; 4250 int i; 4251 4252 if ((bp->b_flags & B_VMIO) == 0) 4253 return; 4254 4255 KASSERT(bp->b_loffset != NOOFFSET, 4256 ("vfs_clean_pages: no buffer offset")); 4257 4258 for (i = 0; i < bp->b_xio.xio_npages; i++) { 4259 m = bp->b_xio.xio_pages[i]; 4260 vfs_clean_one_page(bp, i, m); 4261 } 4262 } 4263 4264 /* 4265 * vfs_clean_one_page: 4266 * 4267 * Set the valid bits and clear the dirty bits in a page within a 4268 * buffer. The range is restricted to the buffer's size and the 4269 * buffer's logical offset might index into the first page. 4270 * 4271 * The caller has busied or soft-busied the page and it is not mapped, 4272 * test and incorporate the dirty bits into b_dirtyoff/end before 4273 * clearing them. Note that we need to clear the pmap modified bits 4274 * after determining the the page was dirty, vm_page_set_validclean() 4275 * does not do it for us. 4276 * 4277 * This routine is typically called after a read completes (dirty should 4278 * be zero in that case as we are not called on bogus-replace pages), 4279 * or before a write is initiated. 4280 */ 4281 static void 4282 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m) 4283 { 4284 int bcount; 4285 int xoff; 4286 int soff; 4287 int eoff; 4288 4289 /* 4290 * Calculate offset range within the page but relative to buffer's 4291 * loffset. loffset might be offset into the first page. 4292 */ 4293 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */ 4294 bcount = bp->b_bcount + xoff; /* offset adjusted */ 4295 4296 if (pageno == 0) { 4297 soff = xoff; 4298 eoff = PAGE_SIZE; 4299 } else { 4300 soff = (pageno << PAGE_SHIFT); 4301 eoff = soff + PAGE_SIZE; 4302 } 4303 if (eoff > bcount) 4304 eoff = bcount; 4305 if (soff >= eoff) 4306 return; 4307 4308 /* 4309 * Test dirty bits and adjust b_dirtyoff/end. 4310 * 4311 * If dirty pages are incorporated into the bp any prior 4312 * B_NEEDCOMMIT state (NFS) must be cleared because the 4313 * caller has not taken into account the new dirty data. 4314 * 4315 * If the page was memory mapped the dirty bits might go beyond the 4316 * end of the buffer, but we can't really make the assumption that 4317 * a file EOF straddles the buffer (even though this is the case for 4318 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing 4319 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer. 4320 * This also saves some console spam. 4321 * 4322 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK, 4323 * NFS can handle huge commits but not huge writes. 4324 */ 4325 vm_page_test_dirty(m); 4326 if (m->dirty) { 4327 if ((bp->b_flags & B_NEEDCOMMIT) && 4328 (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) { 4329 if (debug_commit) 4330 kprintf("Warning: vfs_clean_one_page: bp %p " 4331 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT" 4332 " cmd %d vd %02x/%02x x/s/e %d %d %d " 4333 "doff/end %d %d\n", 4334 bp, (intmax_t)bp->b_loffset, bp->b_bcount, 4335 bp->b_flags, bp->b_cmd, 4336 m->valid, m->dirty, xoff, soff, eoff, 4337 bp->b_dirtyoff, bp->b_dirtyend); 4338 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK); 4339 if (debug_commit) 4340 print_backtrace(-1); 4341 } 4342 /* 4343 * Only clear the pmap modified bits if ALL the dirty bits 4344 * are set, otherwise the system might mis-clear portions 4345 * of a page. 4346 */ 4347 if (m->dirty == VM_PAGE_BITS_ALL && 4348 (bp->b_flags & B_NEEDCOMMIT) == 0) { 4349 pmap_clear_modify(m); 4350 } 4351 if (bp->b_dirtyoff > soff - xoff) 4352 bp->b_dirtyoff = soff - xoff; 4353 if (bp->b_dirtyend < eoff - xoff) 4354 bp->b_dirtyend = eoff - xoff; 4355 } 4356 4357 /* 4358 * Set related valid bits, clear related dirty bits. 4359 * Does not mess with the pmap modified bit. 4360 * 4361 * WARNING! We cannot just clear all of m->dirty here as the 4362 * buffer cache buffers may use a DEV_BSIZE'd aligned 4363 * block size, or have an odd size (e.g. NFS at file EOF). 4364 * The putpages code can clear m->dirty to 0. 4365 * 4366 * If a VOP_WRITE generates a buffer cache buffer which 4367 * covers the same space as mapped writable pages the 4368 * buffer flush might not be able to clear all the dirty 4369 * bits and still require a putpages from the VM system 4370 * to finish it off. 4371 * 4372 * WARNING! vm_page_set_validclean() currently assumes vm_token 4373 * is held. The page might not be busied (bdwrite() case). 4374 * XXX remove this comment once we've validated that this 4375 * is no longer an issue. 4376 */ 4377 vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff); 4378 } 4379 4380 /* 4381 * Similar to vfs_clean_one_page() but sets the bits to valid and dirty. 4382 * The page data is assumed to be valid (there is no zeroing here). 4383 */ 4384 static void 4385 vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m) 4386 { 4387 int bcount; 4388 int xoff; 4389 int soff; 4390 int eoff; 4391 4392 /* 4393 * Calculate offset range within the page but relative to buffer's 4394 * loffset. loffset might be offset into the first page. 4395 */ 4396 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */ 4397 bcount = bp->b_bcount + xoff; /* offset adjusted */ 4398 4399 if (pageno == 0) { 4400 soff = xoff; 4401 eoff = PAGE_SIZE; 4402 } else { 4403 soff = (pageno << PAGE_SHIFT); 4404 eoff = soff + PAGE_SIZE; 4405 } 4406 if (eoff > bcount) 4407 eoff = bcount; 4408 if (soff >= eoff) 4409 return; 4410 vm_page_set_validdirty(m, soff & PAGE_MASK, eoff - soff); 4411 } 4412 4413 /* 4414 * vfs_bio_clrbuf: 4415 * 4416 * Clear a buffer. This routine essentially fakes an I/O, so we need 4417 * to clear B_ERROR and B_INVAL. 4418 * 4419 * Note that while we only theoretically need to clear through b_bcount, 4420 * we go ahead and clear through b_bufsize. 4421 */ 4422 4423 void 4424 vfs_bio_clrbuf(struct buf *bp) 4425 { 4426 int i, mask = 0; 4427 caddr_t sa, ea; 4428 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) { 4429 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR); 4430 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) && 4431 (bp->b_loffset & PAGE_MASK) == 0) { 4432 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1; 4433 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) { 4434 bp->b_resid = 0; 4435 return; 4436 } 4437 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) && 4438 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) { 4439 bzero(bp->b_data, bp->b_bufsize); 4440 bp->b_xio.xio_pages[0]->valid |= mask; 4441 bp->b_resid = 0; 4442 return; 4443 } 4444 } 4445 sa = bp->b_data; 4446 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) { 4447 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE; 4448 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE); 4449 ea = (caddr_t)(vm_offset_t)ulmin( 4450 (u_long)(vm_offset_t)ea, 4451 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize); 4452 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j; 4453 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask) 4454 continue; 4455 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) { 4456 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) { 4457 bzero(sa, ea - sa); 4458 } 4459 } else { 4460 for (; sa < ea; sa += DEV_BSIZE, j++) { 4461 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) && 4462 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0) 4463 bzero(sa, DEV_BSIZE); 4464 } 4465 } 4466 bp->b_xio.xio_pages[i]->valid |= mask; 4467 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO); 4468 } 4469 bp->b_resid = 0; 4470 } else { 4471 clrbuf(bp); 4472 } 4473 } 4474 4475 /* 4476 * vm_hold_load_pages: 4477 * 4478 * Load pages into the buffer's address space. The pages are 4479 * allocated from the kernel object in order to reduce interference 4480 * with the any VM paging I/O activity. The range of loaded 4481 * pages will be wired. 4482 * 4483 * If a page cannot be allocated, the 'pagedaemon' is woken up to 4484 * retrieve the full range (to - from) of pages. 4485 * 4486 * MPSAFE 4487 */ 4488 void 4489 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to) 4490 { 4491 vm_offset_t pg; 4492 vm_page_t p; 4493 int index; 4494 4495 to = round_page(to); 4496 from = round_page(from); 4497 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT; 4498 4499 pg = from; 4500 while (pg < to) { 4501 /* 4502 * Note: must allocate system pages since blocking here 4503 * could intefere with paging I/O, no matter which 4504 * process we are. 4505 */ 4506 vm_object_hold(&kernel_object); 4507 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT, 4508 (vm_pindex_t)((to - pg) >> PAGE_SHIFT)); 4509 vm_object_drop(&kernel_object); 4510 if (p) { 4511 vm_page_wire(p); 4512 p->valid = VM_PAGE_BITS_ALL; 4513 vm_page_flag_clear(p, PG_ZERO); 4514 pmap_kenter(pg, VM_PAGE_TO_PHYS(p)); 4515 bp->b_xio.xio_pages[index] = p; 4516 vm_page_wakeup(p); 4517 4518 pg += PAGE_SIZE; 4519 ++index; 4520 } 4521 } 4522 bp->b_xio.xio_npages = index; 4523 } 4524 4525 /* 4526 * Allocate a page for a buffer cache buffer. 4527 * 4528 * If NULL is returned the caller is expected to retry (typically check if 4529 * the page already exists on retry before trying to allocate one). 4530 * 4531 * NOTE! Low-memory handling is dealt with in b[q]relse(), not here. This 4532 * function will use the system reserve with the hope that the page 4533 * allocations can be returned to PQ_CACHE/PQ_FREE when the caller 4534 * is done with the buffer. 4535 */ 4536 static 4537 vm_page_t 4538 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit) 4539 { 4540 int vmflags = VM_ALLOC_NORMAL | VM_ALLOC_NULL_OK; 4541 vm_page_t p; 4542 4543 ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj)); 4544 4545 /* 4546 * Try a normal allocation first. 4547 */ 4548 p = vm_page_alloc(obj, pg, vmflags); 4549 if (p) 4550 return(p); 4551 if (vm_page_lookup(obj, pg)) 4552 return(NULL); 4553 vm_pageout_deficit += deficit; 4554 4555 /* 4556 * Try again, digging into the system reserve. 4557 * 4558 * Trying to recover pages from the buffer cache here can deadlock 4559 * against other threads trying to busy underlying pages so we 4560 * depend on the code in brelse() and bqrelse() to free/cache the 4561 * underlying buffer cache pages when memory is low. 4562 */ 4563 if (curthread->td_flags & TDF_SYSTHREAD) 4564 vmflags |= VM_ALLOC_SYSTEM | VM_ALLOC_INTERRUPT; 4565 else 4566 vmflags |= VM_ALLOC_SYSTEM; 4567 4568 /*recoverbufpages();*/ 4569 p = vm_page_alloc(obj, pg, vmflags); 4570 if (p) 4571 return(p); 4572 if (vm_page_lookup(obj, pg)) 4573 return(NULL); 4574 4575 /* 4576 * Wait for memory to free up and try again 4577 */ 4578 if (vm_page_count_severe()) 4579 ++lowmempgallocs; 4580 vm_wait(hz / 20 + 1); 4581 4582 p = vm_page_alloc(obj, pg, vmflags); 4583 if (p) 4584 return(p); 4585 if (vm_page_lookup(obj, pg)) 4586 return(NULL); 4587 4588 /* 4589 * Ok, now we are really in trouble. 4590 */ 4591 { 4592 static struct krate biokrate = { .freq = 1 }; 4593 krateprintf(&biokrate, 4594 "Warning: bio_page_alloc: memory exhausted " 4595 "during bufcache page allocation from %s\n", 4596 curthread->td_comm); 4597 } 4598 if (curthread->td_flags & TDF_SYSTHREAD) 4599 vm_wait(hz / 20 + 1); 4600 else 4601 vm_wait(hz / 2 + 1); 4602 return (NULL); 4603 } 4604 4605 /* 4606 * vm_hold_free_pages: 4607 * 4608 * Return pages associated with the buffer back to the VM system. 4609 * 4610 * The range of pages underlying the buffer's address space will 4611 * be unmapped and un-wired. 4612 * 4613 * MPSAFE 4614 */ 4615 void 4616 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to) 4617 { 4618 vm_offset_t pg; 4619 vm_page_t p; 4620 int index, newnpages; 4621 4622 from = round_page(from); 4623 to = round_page(to); 4624 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT; 4625 newnpages = index; 4626 4627 for (pg = from; pg < to; pg += PAGE_SIZE, index++) { 4628 p = bp->b_xio.xio_pages[index]; 4629 if (p && (index < bp->b_xio.xio_npages)) { 4630 if (p->busy) { 4631 kprintf("vm_hold_free_pages: doffset: %lld, " 4632 "loffset: %lld\n", 4633 (long long)bp->b_bio2.bio_offset, 4634 (long long)bp->b_loffset); 4635 } 4636 bp->b_xio.xio_pages[index] = NULL; 4637 pmap_kremove(pg); 4638 vm_page_busy_wait(p, FALSE, "vmhldpg"); 4639 vm_page_unwire(p, 0); 4640 vm_page_free(p); 4641 } 4642 } 4643 bp->b_xio.xio_npages = newnpages; 4644 } 4645 4646 /* 4647 * vmapbuf: 4648 * 4649 * Map a user buffer into KVM via a pbuf. On return the buffer's 4650 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array 4651 * initialized. 4652 */ 4653 int 4654 vmapbuf(struct buf *bp, caddr_t udata, int bytes) 4655 { 4656 caddr_t addr; 4657 vm_offset_t va; 4658 vm_page_t m; 4659 int vmprot; 4660 int error; 4661 int pidx; 4662 int i; 4663 4664 /* 4665 * bp had better have a command and it better be a pbuf. 4666 */ 4667 KKASSERT(bp->b_cmd != BUF_CMD_DONE); 4668 KKASSERT(bp->b_flags & B_PAGING); 4669 KKASSERT(bp->b_kvabase); 4670 4671 if (bytes < 0) 4672 return (-1); 4673 4674 /* 4675 * Map the user data into KVM. Mappings have to be page-aligned. 4676 */ 4677 addr = (caddr_t)trunc_page((vm_offset_t)udata); 4678 pidx = 0; 4679 4680 vmprot = VM_PROT_READ; 4681 if (bp->b_cmd == BUF_CMD_READ) 4682 vmprot |= VM_PROT_WRITE; 4683 4684 while (addr < udata + bytes) { 4685 /* 4686 * Do the vm_fault if needed; do the copy-on-write thing 4687 * when reading stuff off device into memory. 4688 * 4689 * vm_fault_page*() returns a held VM page. 4690 */ 4691 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata; 4692 va = trunc_page(va); 4693 4694 m = vm_fault_page_quick(va, vmprot, &error); 4695 if (m == NULL) { 4696 for (i = 0; i < pidx; ++i) { 4697 vm_page_unhold(bp->b_xio.xio_pages[i]); 4698 bp->b_xio.xio_pages[i] = NULL; 4699 } 4700 return(-1); 4701 } 4702 bp->b_xio.xio_pages[pidx] = m; 4703 addr += PAGE_SIZE; 4704 ++pidx; 4705 } 4706 4707 /* 4708 * Map the page array and set the buffer fields to point to 4709 * the mapped data buffer. 4710 */ 4711 if (pidx > btoc(MAXPHYS)) 4712 panic("vmapbuf: mapped more than MAXPHYS"); 4713 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx); 4714 4715 bp->b_xio.xio_npages = pidx; 4716 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK); 4717 bp->b_bcount = bytes; 4718 bp->b_bufsize = bytes; 4719 return(0); 4720 } 4721 4722 /* 4723 * vunmapbuf: 4724 * 4725 * Free the io map PTEs associated with this IO operation. 4726 * We also invalidate the TLB entries and restore the original b_addr. 4727 */ 4728 void 4729 vunmapbuf(struct buf *bp) 4730 { 4731 int pidx; 4732 int npages; 4733 4734 KKASSERT(bp->b_flags & B_PAGING); 4735 4736 npages = bp->b_xio.xio_npages; 4737 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages); 4738 for (pidx = 0; pidx < npages; ++pidx) { 4739 vm_page_unhold(bp->b_xio.xio_pages[pidx]); 4740 bp->b_xio.xio_pages[pidx] = NULL; 4741 } 4742 bp->b_xio.xio_npages = 0; 4743 bp->b_data = bp->b_kvabase; 4744 } 4745 4746 /* 4747 * Scan all buffers in the system and issue the callback. 4748 */ 4749 int 4750 scan_all_buffers(int (*callback)(struct buf *, void *), void *info) 4751 { 4752 int count = 0; 4753 int error; 4754 int n; 4755 4756 for (n = 0; n < nbuf; ++n) { 4757 if ((error = callback(&buf[n], info)) < 0) { 4758 count = error; 4759 break; 4760 } 4761 count += error; 4762 } 4763 return (count); 4764 } 4765 4766 /* 4767 * nestiobuf_iodone: biodone callback for nested buffers and propagate 4768 * completion to the master buffer. 4769 */ 4770 static void 4771 nestiobuf_iodone(struct bio *bio) 4772 { 4773 struct bio *mbio; 4774 struct buf *mbp, *bp; 4775 struct devstat *stats; 4776 int error; 4777 int donebytes; 4778 4779 bp = bio->bio_buf; 4780 mbio = bio->bio_caller_info1.ptr; 4781 stats = bio->bio_caller_info2.ptr; 4782 mbp = mbio->bio_buf; 4783 4784 KKASSERT(bp->b_bcount <= bp->b_bufsize); 4785 KKASSERT(mbp != bp); 4786 4787 error = bp->b_error; 4788 if (bp->b_error == 0 && 4789 (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) { 4790 /* 4791 * Not all got transfered, raise an error. We have no way to 4792 * propagate these conditions to mbp. 4793 */ 4794 error = EIO; 4795 } 4796 4797 donebytes = bp->b_bufsize; 4798 4799 relpbuf(bp, NULL); 4800 4801 nestiobuf_done(mbio, donebytes, error, stats); 4802 } 4803 4804 void 4805 nestiobuf_done(struct bio *mbio, int donebytes, int error, struct devstat *stats) 4806 { 4807 struct buf *mbp; 4808 4809 mbp = mbio->bio_buf; 4810 4811 KKASSERT((int)(intptr_t)mbio->bio_driver_info > 0); 4812 4813 /* 4814 * If an error occured, propagate it to the master buffer. 4815 * 4816 * Several biodone()s may wind up running concurrently so 4817 * use an atomic op to adjust b_flags. 4818 */ 4819 if (error) { 4820 mbp->b_error = error; 4821 atomic_set_int(&mbp->b_flags, B_ERROR); 4822 } 4823 4824 /* 4825 * Decrement the operations in progress counter and terminate the 4826 * I/O if this was the last bit. 4827 */ 4828 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) { 4829 mbp->b_resid = 0; 4830 if (stats) 4831 devstat_end_transaction_buf(stats, mbp); 4832 biodone(mbio); 4833 } 4834 } 4835 4836 /* 4837 * Initialize a nestiobuf for use. Set an initial count of 1 to prevent 4838 * the mbio from being biodone()'d while we are still adding sub-bios to 4839 * it. 4840 */ 4841 void 4842 nestiobuf_init(struct bio *bio) 4843 { 4844 bio->bio_driver_info = (void *)1; 4845 } 4846 4847 /* 4848 * The BIOs added to the nestedio have already been started, remove the 4849 * count that placeheld our mbio and biodone() it if the count would 4850 * transition to 0. 4851 */ 4852 void 4853 nestiobuf_start(struct bio *mbio) 4854 { 4855 struct buf *mbp = mbio->bio_buf; 4856 4857 /* 4858 * Decrement the operations in progress counter and terminate the 4859 * I/O if this was the last bit. 4860 */ 4861 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) { 4862 if (mbp->b_flags & B_ERROR) 4863 mbp->b_resid = mbp->b_bcount; 4864 else 4865 mbp->b_resid = 0; 4866 biodone(mbio); 4867 } 4868 } 4869 4870 /* 4871 * Set an intermediate error prior to calling nestiobuf_start() 4872 */ 4873 void 4874 nestiobuf_error(struct bio *mbio, int error) 4875 { 4876 struct buf *mbp = mbio->bio_buf; 4877 4878 if (error) { 4879 mbp->b_error = error; 4880 atomic_set_int(&mbp->b_flags, B_ERROR); 4881 } 4882 } 4883 4884 /* 4885 * nestiobuf_add: setup a "nested" buffer. 4886 * 4887 * => 'mbp' is a "master" buffer which is being divided into sub pieces. 4888 * => 'bp' should be a buffer allocated by getiobuf. 4889 * => 'offset' is a byte offset in the master buffer. 4890 * => 'size' is a size in bytes of this nested buffer. 4891 */ 4892 void 4893 nestiobuf_add(struct bio *mbio, struct buf *bp, int offset, size_t size, struct devstat *stats) 4894 { 4895 struct buf *mbp = mbio->bio_buf; 4896 struct vnode *vp = mbp->b_vp; 4897 4898 KKASSERT(mbp->b_bcount >= offset + size); 4899 4900 atomic_add_int((int *)&mbio->bio_driver_info, 1); 4901 4902 /* kernel needs to own the lock for it to be released in biodone */ 4903 BUF_KERNPROC(bp); 4904 bp->b_vp = vp; 4905 bp->b_cmd = mbp->b_cmd; 4906 bp->b_bio1.bio_done = nestiobuf_iodone; 4907 bp->b_data = (char *)mbp->b_data + offset; 4908 bp->b_resid = bp->b_bcount = size; 4909 bp->b_bufsize = bp->b_bcount; 4910 4911 bp->b_bio1.bio_track = NULL; 4912 bp->b_bio1.bio_caller_info1.ptr = mbio; 4913 bp->b_bio1.bio_caller_info2.ptr = stats; 4914 } 4915 4916 /* 4917 * print out statistics from the current status of the buffer pool 4918 * this can be toggeled by the system control option debug.syncprt 4919 */ 4920 #ifdef DEBUG 4921 void 4922 vfs_bufstats(void) 4923 { 4924 int i, j, count; 4925 struct buf *bp; 4926 struct bqueues *dp; 4927 int counts[(MAXBSIZE / PAGE_SIZE) + 1]; 4928 static char *bname[3] = { "LOCKED", "LRU", "AGE" }; 4929 4930 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) { 4931 count = 0; 4932 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++) 4933 counts[j] = 0; 4934 4935 spin_lock(&bufqspin); 4936 TAILQ_FOREACH(bp, dp, b_freelist) { 4937 counts[bp->b_bufsize/PAGE_SIZE]++; 4938 count++; 4939 } 4940 spin_unlock(&bufqspin); 4941 4942 kprintf("%s: total-%d", bname[i], count); 4943 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++) 4944 if (counts[j] != 0) 4945 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]); 4946 kprintf("\n"); 4947 } 4948 } 4949 #endif 4950 4951 #ifdef DDB 4952 4953 DB_SHOW_COMMAND(buffer, db_show_buffer) 4954 { 4955 /* get args */ 4956 struct buf *bp = (struct buf *)addr; 4957 4958 if (!have_addr) { 4959 db_printf("usage: show buffer <addr>\n"); 4960 return; 4961 } 4962 4963 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS); 4964 db_printf("b_cmd = %d\n", bp->b_cmd); 4965 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, " 4966 "b_resid = %d\n, b_data = %p, " 4967 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n", 4968 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid, 4969 bp->b_data, 4970 (long long)bp->b_bio2.bio_offset, 4971 (long long)(bp->b_bio2.bio_next ? 4972 bp->b_bio2.bio_next->bio_offset : (off_t)-1)); 4973 if (bp->b_xio.xio_npages) { 4974 int i; 4975 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ", 4976 bp->b_xio.xio_npages); 4977 for (i = 0; i < bp->b_xio.xio_npages; i++) { 4978 vm_page_t m; 4979 m = bp->b_xio.xio_pages[i]; 4980 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object, 4981 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m)); 4982 if ((i + 1) < bp->b_xio.xio_npages) 4983 db_printf(","); 4984 } 4985 db_printf("\n"); 4986 } 4987 } 4988 #endif /* DDB */ 4989