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