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