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