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