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