2 * Copyright (c) 1994,1997 John S. Dyson
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
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.7 2003/06/27 01:53:25 dillon Exp $
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.
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.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.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>
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>
58 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
60 struct bio_ops bioops; /* I/O operation notification */
62 struct buf *buf; /* buffer header pool */
63 struct swqueue bswlist;
65 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
67 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
69 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
70 int pageno, vm_page_t m);
71 static void vfs_clean_pages(struct buf * bp);
72 static void vfs_setdirty(struct buf *bp);
73 static void vfs_vmio_release(struct buf *bp);
74 static void vfs_backgroundwritedone(struct buf *bp);
75 static int flushbufqueues(void);
77 static int bd_request;
79 static void buf_daemon __P((void));
81 * bogus page -- for I/O to/from partially complete buffers
82 * this is a temporary solution to the problem, but it is not
83 * really that bad. it would be better to split the buffer
84 * for input in the case of buffers partially already in memory,
85 * but the code is intricate enough already.
88 int vmiodirenable = TRUE;
90 static vm_offset_t bogus_offset;
92 static int bufspace, maxbufspace,
93 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
94 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
95 static int needsbuffer;
96 static int lorunningspace, hirunningspace, runningbufreq;
97 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
98 static int numfreebuffers, lofreebuffers, hifreebuffers;
99 static int getnewbufcalls;
100 static int getnewbufrestarts;
102 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
103 &numdirtybuffers, 0, "");
104 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
105 &lodirtybuffers, 0, "");
106 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
107 &hidirtybuffers, 0, "");
108 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
109 &numfreebuffers, 0, "");
110 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
111 &lofreebuffers, 0, "");
112 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
113 &hifreebuffers, 0, "");
114 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
115 &runningbufspace, 0, "");
116 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW,
117 &lorunningspace, 0, "");
118 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW,
119 &hirunningspace, 0, "");
120 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD,
121 &maxbufspace, 0, "");
122 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
124 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD,
126 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
128 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
129 &maxbufmallocspace, 0, "");
130 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
131 &bufmallocspace, 0, "");
132 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW,
133 &getnewbufcalls, 0, "");
134 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW,
135 &getnewbufrestarts, 0, "");
136 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW,
137 &vmiodirenable, 0, "");
138 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW,
139 &bufdefragcnt, 0, "");
140 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW,
141 &buffreekvacnt, 0, "");
142 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW,
143 &bufreusecnt, 0, "");
145 static int bufhashmask;
146 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
147 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
148 char *buf_wmesg = BUF_WMESG;
150 extern int vm_swap_size;
152 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
153 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
154 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
155 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
158 * Buffer hash table code. Note that the logical block scans linearly, which
159 * gives us some L1 cache locality.
164 bufhash(struct vnode *vnp, daddr_t bn)
166 return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
172 * If someone is blocked due to there being too many dirty buffers,
173 * and numdirtybuffers is now reasonable, wake them up.
177 numdirtywakeup(int level)
179 if (numdirtybuffers <= level) {
180 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
181 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
182 wakeup(&needsbuffer);
190 * Called when buffer space is potentially available for recovery.
191 * getnewbuf() will block on this flag when it is unable to free
192 * sufficient buffer space. Buffer space becomes recoverable when
193 * bp's get placed back in the queues.
200 * If someone is waiting for BUF space, wake them up. Even
201 * though we haven't freed the kva space yet, the waiting
202 * process will be able to now.
204 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
205 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
206 wakeup(&needsbuffer);
211 * runningbufwakeup() - in-progress I/O accounting.
215 runningbufwakeup(struct buf *bp)
217 if (bp->b_runningbufspace) {
218 runningbufspace -= bp->b_runningbufspace;
219 bp->b_runningbufspace = 0;
220 if (runningbufreq && runningbufspace <= lorunningspace) {
222 wakeup(&runningbufreq);
230 * Called when a buffer has been added to one of the free queues to
231 * account for the buffer and to wakeup anyone waiting for free buffers.
232 * This typically occurs when large amounts of metadata are being handled
233 * by the buffer cache ( else buffer space runs out first, usually ).
241 needsbuffer &= ~VFS_BIO_NEED_ANY;
242 if (numfreebuffers >= hifreebuffers)
243 needsbuffer &= ~VFS_BIO_NEED_FREE;
244 wakeup(&needsbuffer);
249 * waitrunningbufspace()
251 * runningbufspace is a measure of the amount of I/O currently
252 * running. This routine is used in async-write situations to
253 * prevent creating huge backups of pending writes to a device.
254 * Only asynchronous writes are governed by this function.
256 * Reads will adjust runningbufspace, but will not block based on it.
257 * The read load has a side effect of reducing the allowed write load.
259 * This does NOT turn an async write into a sync write. It waits
260 * for earlier writes to complete and generally returns before the
261 * caller's write has reached the device.
264 waitrunningbufspace(void)
266 while (runningbufspace > hirunningspace) {
269 s = splbio(); /* fix race against interrupt/biodone() */
271 tsleep(&runningbufreq, PVM, "wdrain", 0);
277 * vfs_buf_test_cache:
279 * Called when a buffer is extended. This function clears the B_CACHE
280 * bit if the newly extended portion of the buffer does not contain
285 vfs_buf_test_cache(struct buf *bp,
286 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
289 if (bp->b_flags & B_CACHE) {
290 int base = (foff + off) & PAGE_MASK;
291 if (vm_page_is_valid(m, base, size) == 0)
292 bp->b_flags &= ~B_CACHE;
298 bd_wakeup(int dirtybuflevel)
300 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
307 * bd_speedup - speedup the buffer cache flushing code
318 * Initialize buffer headers and related structures.
322 bufhashinit(caddr_t vaddr)
324 /* first, make a null hash table */
325 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
327 bufhashtbl = (void *)vaddr;
328 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
339 TAILQ_INIT(&bswlist);
340 LIST_INIT(&invalhash);
341 simple_lock_init(&buftimelock);
343 for (i = 0; i <= bufhashmask; i++)
344 LIST_INIT(&bufhashtbl[i]);
346 /* next, make a null set of free lists */
347 for (i = 0; i < BUFFER_QUEUES; i++)
348 TAILQ_INIT(&bufqueues[i]);
350 /* finally, initialize each buffer header and stick on empty q */
351 for (i = 0; i < nbuf; i++) {
353 bzero(bp, sizeof *bp);
354 bp->b_flags = B_INVAL; /* we're just an empty header */
356 bp->b_qindex = QUEUE_EMPTY;
358 LIST_INIT(&bp->b_dep);
360 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
361 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
365 * maxbufspace is the absolute maximum amount of buffer space we are
366 * allowed to reserve in KVM and in real terms. The absolute maximum
367 * is nominally used by buf_daemon. hibufspace is the nominal maximum
368 * used by most other processes. The differential is required to
369 * ensure that buf_daemon is able to run when other processes might
370 * be blocked waiting for buffer space.
372 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
373 * this may result in KVM fragmentation which is not handled optimally
376 maxbufspace = nbuf * BKVASIZE;
377 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
378 lobufspace = hibufspace - MAXBSIZE;
380 lorunningspace = 512 * 1024;
381 hirunningspace = 1024 * 1024;
384 * Limit the amount of malloc memory since it is wired permanently into
385 * the kernel space. Even though this is accounted for in the buffer
386 * allocation, we don't want the malloced region to grow uncontrolled.
387 * The malloc scheme improves memory utilization significantly on average
388 * (small) directories.
390 maxbufmallocspace = hibufspace / 20;
393 * Reduce the chance of a deadlock occuring by limiting the number
394 * of delayed-write dirty buffers we allow to stack up.
396 hidirtybuffers = nbuf / 4 + 20;
399 * To support extreme low-memory systems, make sure hidirtybuffers cannot
400 * eat up all available buffer space. This occurs when our minimum cannot
401 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
402 * BKVASIZE'd (8K) buffers.
404 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
405 hidirtybuffers >>= 1;
407 lodirtybuffers = hidirtybuffers / 2;
410 * Try to keep the number of free buffers in the specified range,
411 * and give special processes (e.g. like buf_daemon) access to an
414 lofreebuffers = nbuf / 18 + 5;
415 hifreebuffers = 2 * lofreebuffers;
416 numfreebuffers = nbuf;
419 * Maximum number of async ops initiated per buf_daemon loop. This is
420 * somewhat of a hack at the moment, we really need to limit ourselves
421 * based on the number of bytes of I/O in-transit that were initiated
425 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
426 bogus_page = vm_page_alloc(kernel_object,
427 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
434 * bfreekva() - free the kva allocation for a buffer.
436 * Must be called at splbio() or higher as this is the only locking for
439 * Since this call frees up buffer space, we call bufspacewakeup().
442 bfreekva(struct buf * bp)
446 vm_map_lock(buffer_map);
447 bufspace -= bp->b_kvasize;
448 vm_map_delete(buffer_map,
449 (vm_offset_t) bp->b_kvabase,
450 (vm_offset_t) bp->b_kvabase + bp->b_kvasize
452 vm_map_unlock(buffer_map);
461 * Remove the buffer from the appropriate free list.
464 bremfree(struct buf * bp)
467 int old_qindex = bp->b_qindex;
469 if (bp->b_qindex != QUEUE_NONE) {
470 KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
471 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
472 bp->b_qindex = QUEUE_NONE;
474 if (BUF_REFCNT(bp) <= 1)
475 panic("bremfree: removing a buffer not on a queue");
479 * Fixup numfreebuffers count. If the buffer is invalid or not
480 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
481 * the buffer was free and we must decrement numfreebuffers.
483 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
500 * Get a buffer with the specified data. Look in the cache first. We
501 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
502 * is set, the buffer is valid and we do not have to do anything ( see
506 bread(struct vnode * vp, daddr_t blkno, int size, struct buf ** bpp)
510 bp = getblk(vp, blkno, size, 0, 0);
513 /* if not found in cache, do some I/O */
514 if ((bp->b_flags & B_CACHE) == 0) {
515 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
516 bp->b_flags |= B_READ;
517 bp->b_flags &= ~(B_ERROR | B_INVAL);
518 vfs_busy_pages(bp, 0);
519 VOP_STRATEGY(vp, bp);
520 return (biowait(bp));
526 * Operates like bread, but also starts asynchronous I/O on
527 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
528 * to initiating I/O . If B_CACHE is set, the buffer is valid
529 * and we do not have to do anything.
532 breadn(struct vnode * vp, daddr_t blkno, int size, daddr_t * rablkno,
533 int *rabsize, int cnt, struct buf ** bpp)
535 struct buf *bp, *rabp;
537 int rv = 0, readwait = 0;
539 *bpp = bp = getblk(vp, blkno, size, 0, 0);
541 /* if not found in cache, do some I/O */
542 if ((bp->b_flags & B_CACHE) == 0) {
543 bp->b_flags |= B_READ;
544 bp->b_flags &= ~(B_ERROR | B_INVAL);
545 vfs_busy_pages(bp, 0);
546 VOP_STRATEGY(vp, bp);
550 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
551 if (inmem(vp, *rablkno))
553 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
555 if ((rabp->b_flags & B_CACHE) == 0) {
556 rabp->b_flags |= B_READ | B_ASYNC;
557 rabp->b_flags &= ~(B_ERROR | B_INVAL);
558 vfs_busy_pages(rabp, 0);
560 VOP_STRATEGY(vp, rabp);
573 * Write, release buffer on completion. (Done by iodone
574 * if async). Do not bother writing anything if the buffer
577 * Note that we set B_CACHE here, indicating that buffer is
578 * fully valid and thus cacheable. This is true even of NFS
579 * now so we set it generally. This could be set either here
580 * or in biodone() since the I/O is synchronous. We put it
584 bwrite(struct buf * bp)
589 if (bp->b_flags & B_INVAL) {
594 oldflags = bp->b_flags;
596 if (BUF_REFCNT(bp) == 0)
597 panic("bwrite: buffer is not busy???");
600 * If a background write is already in progress, delay
601 * writing this block if it is asynchronous. Otherwise
602 * wait for the background write to complete.
604 if (bp->b_xflags & BX_BKGRDINPROG) {
605 if (bp->b_flags & B_ASYNC) {
610 bp->b_xflags |= BX_BKGRDWAIT;
611 tsleep(&bp->b_xflags, PRIBIO, "biord", 0);
612 if (bp->b_xflags & BX_BKGRDINPROG)
613 panic("bwrite: still writing");
616 /* Mark the buffer clean */
620 * If this buffer is marked for background writing and we
621 * do not have to wait for it, make a copy and write the
622 * copy so as to leave this buffer ready for further use.
624 * This optimization eats a lot of memory. If we have a page
625 * or buffer shortfull we can't do it.
627 if ((bp->b_xflags & BX_BKGRDWRITE) &&
628 (bp->b_flags & B_ASYNC) &&
629 !vm_page_count_severe() &&
630 !buf_dirty_count_severe()) {
631 if (bp->b_flags & B_CALL)
632 panic("bwrite: need chained iodone");
634 /* get a new block */
635 newbp = geteblk(bp->b_bufsize);
637 /* set it to be identical to the old block */
638 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
639 bgetvp(bp->b_vp, newbp);
640 newbp->b_lblkno = bp->b_lblkno;
641 newbp->b_blkno = bp->b_blkno;
642 newbp->b_offset = bp->b_offset;
643 newbp->b_iodone = vfs_backgroundwritedone;
644 newbp->b_flags |= B_ASYNC | B_CALL;
645 newbp->b_flags &= ~B_INVAL;
647 /* move over the dependencies */
648 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
649 (*bioops.io_movedeps)(bp, newbp);
652 * Initiate write on the copy, release the original to
653 * the B_LOCKED queue so that it cannot go away until
654 * the background write completes. If not locked it could go
655 * away and then be reconstituted while it was being written.
656 * If the reconstituted buffer were written, we could end up
657 * with two background copies being written at the same time.
659 bp->b_xflags |= BX_BKGRDINPROG;
660 bp->b_flags |= B_LOCKED;
665 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
666 bp->b_flags |= B_WRITEINPROG | B_CACHE;
668 bp->b_vp->v_numoutput++;
669 vfs_busy_pages(bp, 1);
672 * Normal bwrites pipeline writes
674 bp->b_runningbufspace = bp->b_bufsize;
675 runningbufspace += bp->b_runningbufspace;
678 if (oldflags & B_ASYNC)
680 VOP_STRATEGY(bp->b_vp, bp);
682 if ((oldflags & B_ASYNC) == 0) {
683 int rtval = biowait(bp);
686 } else if ((oldflags & B_NOWDRAIN) == 0) {
688 * don't allow the async write to saturate the I/O
689 * system. Deadlocks can occur only if a device strategy
690 * routine (like in VN) turns around and issues another
691 * high-level write, in which case B_NOWDRAIN is expected
692 * to be set. Otherwise we will not deadlock here because
693 * we are blocking waiting for I/O that is already in-progress
696 waitrunningbufspace();
703 * Complete a background write started from bwrite.
706 vfs_backgroundwritedone(bp)
712 * Find the original buffer that we are writing.
714 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
715 panic("backgroundwritedone: lost buffer");
717 * Process dependencies then return any unfinished ones.
719 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
720 (*bioops.io_complete)(bp);
721 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
722 (*bioops.io_movedeps)(bp, origbp);
724 * Clear the BX_BKGRDINPROG flag in the original buffer
725 * and awaken it if it is waiting for the write to complete.
726 * If BX_BKGRDINPROG is not set in the original buffer it must
727 * have been released and re-instantiated - which is not legal.
729 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
730 origbp->b_xflags &= ~BX_BKGRDINPROG;
731 if (origbp->b_xflags & BX_BKGRDWAIT) {
732 origbp->b_xflags &= ~BX_BKGRDWAIT;
733 wakeup(&origbp->b_xflags);
736 * Clear the B_LOCKED flag and remove it from the locked
737 * queue if it currently resides there.
739 origbp->b_flags &= ~B_LOCKED;
740 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
745 * This buffer is marked B_NOCACHE, so when it is released
746 * by biodone, it will be tossed. We mark it with B_READ
747 * to avoid biodone doing a second vwakeup.
749 bp->b_flags |= B_NOCACHE | B_READ;
750 bp->b_flags &= ~(B_CACHE | B_CALL | B_DONE);
756 * Delayed write. (Buffer is marked dirty). Do not bother writing
757 * anything if the buffer is marked invalid.
759 * Note that since the buffer must be completely valid, we can safely
760 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
761 * biodone() in order to prevent getblk from writing the buffer
765 bdwrite(struct buf * bp)
767 if (BUF_REFCNT(bp) == 0)
768 panic("bdwrite: buffer is not busy");
770 if (bp->b_flags & B_INVAL) {
777 * Set B_CACHE, indicating that the buffer is fully valid. This is
778 * true even of NFS now.
780 bp->b_flags |= B_CACHE;
783 * This bmap keeps the system from needing to do the bmap later,
784 * perhaps when the system is attempting to do a sync. Since it
785 * is likely that the indirect block -- or whatever other datastructure
786 * that the filesystem needs is still in memory now, it is a good
787 * thing to do this. Note also, that if the pageout daemon is
788 * requesting a sync -- there might not be enough memory to do
789 * the bmap then... So, this is important to do.
791 if (bp->b_lblkno == bp->b_blkno) {
792 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
796 * Set the *dirty* buffer range based upon the VM system dirty pages.
801 * We need to do this here to satisfy the vnode_pager and the
802 * pageout daemon, so that it thinks that the pages have been
803 * "cleaned". Note that since the pages are in a delayed write
804 * buffer -- the VFS layer "will" see that the pages get written
805 * out on the next sync, or perhaps the cluster will be completed.
811 * Wakeup the buffer flushing daemon if we have a lot of dirty
812 * buffers (midpoint between our recovery point and our stall
815 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
818 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
819 * due to the softdep code.
826 * Turn buffer into delayed write request. We must clear B_READ and
827 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
828 * itself to properly update it in the dirty/clean lists. We mark it
829 * B_DONE to ensure that any asynchronization of the buffer properly
830 * clears B_DONE ( else a panic will occur later ).
832 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
833 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
834 * should only be called if the buffer is known-good.
836 * Since the buffer is not on a queue, we do not update the numfreebuffers
839 * Must be called at splbio().
840 * The buffer must be on QUEUE_NONE.
846 KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
847 bp->b_flags &= ~(B_READ|B_RELBUF);
849 if ((bp->b_flags & B_DELWRI) == 0) {
850 bp->b_flags |= B_DONE | B_DELWRI;
851 reassignbuf(bp, bp->b_vp);
853 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
860 * Clear B_DELWRI for buffer.
862 * Since the buffer is not on a queue, we do not update the numfreebuffers
865 * Must be called at splbio().
866 * The buffer must be on QUEUE_NONE.
873 KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
875 if (bp->b_flags & B_DELWRI) {
876 bp->b_flags &= ~B_DELWRI;
877 reassignbuf(bp, bp->b_vp);
879 numdirtywakeup(lodirtybuffers);
882 * Since it is now being written, we can clear its deferred write flag.
884 bp->b_flags &= ~B_DEFERRED;
890 * Asynchronous write. Start output on a buffer, but do not wait for
891 * it to complete. The buffer is released when the output completes.
893 * bwrite() ( or the VOP routine anyway ) is responsible for handling
894 * B_INVAL buffers. Not us.
897 bawrite(struct buf * bp)
899 bp->b_flags |= B_ASYNC;
900 (void) VOP_BWRITE(bp->b_vp, bp);
906 * Ordered write. Start output on a buffer, and flag it so that the
907 * device will write it in the order it was queued. The buffer is
908 * released when the output completes. bwrite() ( or the VOP routine
909 * anyway ) is responsible for handling B_INVAL buffers.
912 bowrite(struct buf * bp)
914 bp->b_flags |= B_ORDERED | B_ASYNC;
915 return (VOP_BWRITE(bp->b_vp, bp));
921 * Called prior to the locking of any vnodes when we are expecting to
922 * write. We do not want to starve the buffer cache with too many
923 * dirty buffers so we block here. By blocking prior to the locking
924 * of any vnodes we attempt to avoid the situation where a locked vnode
925 * prevents the various system daemons from flushing related buffers.
931 if (numdirtybuffers >= hidirtybuffers) {
935 while (numdirtybuffers >= hidirtybuffers) {
937 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
938 tsleep(&needsbuffer, (PRIBIO + 4), "flswai", 0);
945 * Return true if we have too many dirty buffers.
948 buf_dirty_count_severe(void)
950 return(numdirtybuffers >= hidirtybuffers);
956 * Release a busy buffer and, if requested, free its resources. The
957 * buffer will be stashed in the appropriate bufqueue[] allowing it
958 * to be accessed later as a cache entity or reused for other purposes.
961 brelse(struct buf * bp)
965 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
969 if (bp->b_flags & B_LOCKED)
970 bp->b_flags &= ~B_ERROR;
972 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
974 * Failed write, redirty. Must clear B_ERROR to prevent
975 * pages from being scrapped. If B_INVAL is set then
976 * this case is not run and the next case is run to
977 * destroy the buffer. B_INVAL can occur if the buffer
978 * is outside the range supported by the underlying device.
980 bp->b_flags &= ~B_ERROR;
982 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
983 (bp->b_bufsize <= 0)) {
985 * Either a failed I/O or we were asked to free or not
988 bp->b_flags |= B_INVAL;
989 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
990 (*bioops.io_deallocate)(bp);
991 if (bp->b_flags & B_DELWRI) {
993 numdirtywakeup(lodirtybuffers);
995 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
996 if ((bp->b_flags & B_VMIO) == 0) {
1005 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1006 * is called with B_DELWRI set, the underlying pages may wind up
1007 * getting freed causing a previous write (bdwrite()) to get 'lost'
1008 * because pages associated with a B_DELWRI bp are marked clean.
1010 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1011 * if B_DELWRI is set.
1013 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1014 * on pages to return pages to the VM page queues.
1016 if (bp->b_flags & B_DELWRI)
1017 bp->b_flags &= ~B_RELBUF;
1018 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1019 bp->b_flags |= B_RELBUF;
1022 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1023 * constituted, not even NFS buffers now. Two flags effect this. If
1024 * B_INVAL, the struct buf is invalidated but the VM object is kept
1025 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1027 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1028 * invalidated. B_ERROR cannot be set for a failed write unless the
1029 * buffer is also B_INVAL because it hits the re-dirtying code above.
1031 * Normally we can do this whether a buffer is B_DELWRI or not. If
1032 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1033 * the commit state and we cannot afford to lose the buffer. If the
1034 * buffer has a background write in progress, we need to keep it
1035 * around to prevent it from being reconstituted and starting a second
1038 if ((bp->b_flags & B_VMIO)
1039 && !(bp->b_vp->v_tag == VT_NFS &&
1040 !vn_isdisk(bp->b_vp, NULL) &&
1041 (bp->b_flags & B_DELWRI))
1054 * Get the base offset and length of the buffer. Note that
1055 * in the VMIO case if the buffer block size is not
1056 * page-aligned then b_data pointer may not be page-aligned.
1057 * But our b_pages[] array *IS* page aligned.
1059 * block sizes less then DEV_BSIZE (usually 512) are not
1060 * supported due to the page granularity bits (m->valid,
1061 * m->dirty, etc...).
1063 * See man buf(9) for more information
1066 resid = bp->b_bufsize;
1067 foff = bp->b_offset;
1069 for (i = 0; i < bp->b_npages; i++) {
1071 vm_page_flag_clear(m, PG_ZERO);
1073 * If we hit a bogus page, fixup *all* of them
1076 if (m == bogus_page) {
1077 VOP_GETVOBJECT(vp, &obj);
1078 poff = OFF_TO_IDX(bp->b_offset);
1080 for (j = i; j < bp->b_npages; j++) {
1083 mtmp = bp->b_pages[j];
1084 if (mtmp == bogus_page) {
1085 mtmp = vm_page_lookup(obj, poff + j);
1087 panic("brelse: page missing\n");
1089 bp->b_pages[j] = mtmp;
1093 if ((bp->b_flags & B_INVAL) == 0) {
1094 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1098 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1099 int poffset = foff & PAGE_MASK;
1100 int presid = resid > (PAGE_SIZE - poffset) ?
1101 (PAGE_SIZE - poffset) : resid;
1103 KASSERT(presid >= 0, ("brelse: extra page"));
1104 vm_page_set_invalid(m, poffset, presid);
1106 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1107 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1110 if (bp->b_flags & (B_INVAL | B_RELBUF))
1111 vfs_vmio_release(bp);
1113 } else if (bp->b_flags & B_VMIO) {
1115 if (bp->b_flags & (B_INVAL | B_RELBUF))
1116 vfs_vmio_release(bp);
1120 if (bp->b_qindex != QUEUE_NONE)
1121 panic("brelse: free buffer onto another queue???");
1122 if (BUF_REFCNT(bp) > 1) {
1123 /* Temporary panic to verify exclusive locking */
1124 /* This panic goes away when we allow shared refs */
1125 panic("brelse: multiple refs");
1126 /* do not release to free list */
1134 /* buffers with no memory */
1135 if (bp->b_bufsize == 0) {
1136 bp->b_flags |= B_INVAL;
1137 bp->b_xflags &= ~BX_BKGRDWRITE;
1138 if (bp->b_xflags & BX_BKGRDINPROG)
1139 panic("losing buffer 1");
1140 if (bp->b_kvasize) {
1141 bp->b_qindex = QUEUE_EMPTYKVA;
1143 bp->b_qindex = QUEUE_EMPTY;
1145 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1146 LIST_REMOVE(bp, b_hash);
1147 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1149 /* buffers with junk contents */
1150 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1151 bp->b_flags |= B_INVAL;
1152 bp->b_xflags &= ~BX_BKGRDWRITE;
1153 if (bp->b_xflags & BX_BKGRDINPROG)
1154 panic("losing buffer 2");
1155 bp->b_qindex = QUEUE_CLEAN;
1156 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1157 LIST_REMOVE(bp, b_hash);
1158 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1161 /* buffers that are locked */
1162 } else if (bp->b_flags & B_LOCKED) {
1163 bp->b_qindex = QUEUE_LOCKED;
1164 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1166 /* remaining buffers */
1168 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1169 case B_DELWRI | B_AGE:
1170 bp->b_qindex = QUEUE_DIRTY;
1171 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1174 bp->b_qindex = QUEUE_DIRTY;
1175 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1178 bp->b_qindex = QUEUE_CLEAN;
1179 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1182 bp->b_qindex = QUEUE_CLEAN;
1183 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1189 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1190 * on the correct queue.
1192 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1196 * Fixup numfreebuffers count. The bp is on an appropriate queue
1197 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1198 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1199 * if B_INVAL is set ).
1202 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1206 * Something we can maybe free or reuse
1208 if (bp->b_bufsize || bp->b_kvasize)
1213 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1214 B_DIRECT | B_NOWDRAIN);
1219 * Release a buffer back to the appropriate queue but do not try to free
1220 * it. The buffer is expected to be used again soon.
1222 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1223 * biodone() to requeue an async I/O on completion. It is also used when
1224 * known good buffers need to be requeued but we think we may need the data
1227 * XXX we should be able to leave the B_RELBUF hint set on completion.
1230 bqrelse(struct buf * bp)
1236 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1238 if (bp->b_qindex != QUEUE_NONE)
1239 panic("bqrelse: free buffer onto another queue???");
1240 if (BUF_REFCNT(bp) > 1) {
1241 /* do not release to free list */
1242 panic("bqrelse: multiple refs");
1247 if (bp->b_flags & B_LOCKED) {
1248 bp->b_flags &= ~B_ERROR;
1249 bp->b_qindex = QUEUE_LOCKED;
1250 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1251 /* buffers with stale but valid contents */
1252 } else if (bp->b_flags & B_DELWRI) {
1253 bp->b_qindex = QUEUE_DIRTY;
1254 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1255 } else if (vm_page_count_severe()) {
1257 * We are too low on memory, we have to try to free the
1258 * buffer (most importantly: the wired pages making up its
1259 * backing store) *now*.
1265 bp->b_qindex = QUEUE_CLEAN;
1266 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1269 if ((bp->b_flags & B_LOCKED) == 0 &&
1270 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1275 * Something we can maybe free or reuse.
1277 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1282 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1287 vfs_vmio_release(bp)
1294 for (i = 0; i < bp->b_npages; i++) {
1296 bp->b_pages[i] = NULL;
1298 * In order to keep page LRU ordering consistent, put
1299 * everything on the inactive queue.
1301 vm_page_unwire(m, 0);
1303 * We don't mess with busy pages, it is
1304 * the responsibility of the process that
1305 * busied the pages to deal with them.
1307 if ((m->flags & PG_BUSY) || (m->busy != 0))
1310 if (m->wire_count == 0) {
1311 vm_page_flag_clear(m, PG_ZERO);
1313 * Might as well free the page if we can and it has
1314 * no valid data. We also free the page if the
1315 * buffer was used for direct I/O.
1317 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1319 vm_page_protect(m, VM_PROT_NONE);
1321 } else if (bp->b_flags & B_DIRECT) {
1322 vm_page_try_to_free(m);
1323 } else if (vm_page_count_severe()) {
1324 vm_page_try_to_cache(m);
1329 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1330 if (bp->b_bufsize) {
1335 bp->b_flags &= ~B_VMIO;
1341 * Check to see if a block is currently memory resident.
1344 gbincore(struct vnode * vp, daddr_t blkno)
1347 struct bufhashhdr *bh;
1349 bh = bufhash(vp, blkno);
1351 /* Search hash chain */
1352 LIST_FOREACH(bp, bh, b_hash) {
1354 if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1355 (bp->b_flags & B_INVAL) == 0) {
1365 * Implement clustered async writes for clearing out B_DELWRI buffers.
1366 * This is much better then the old way of writing only one buffer at
1367 * a time. Note that we may not be presented with the buffers in the
1368 * correct order, so we search for the cluster in both directions.
1371 vfs_bio_awrite(struct buf * bp)
1375 daddr_t lblkno = bp->b_lblkno;
1376 struct vnode *vp = bp->b_vp;
1386 * right now we support clustered writing only to regular files. If
1387 * we find a clusterable block we could be in the middle of a cluster
1388 * rather then at the beginning.
1390 if ((vp->v_type == VREG) &&
1391 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1392 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1394 size = vp->v_mount->mnt_stat.f_iosize;
1395 maxcl = MAXPHYS / size;
1397 for (i = 1; i < maxcl; i++) {
1398 if ((bpa = gbincore(vp, lblkno + i)) &&
1399 BUF_REFCNT(bpa) == 0 &&
1400 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1401 (B_DELWRI | B_CLUSTEROK)) &&
1402 (bpa->b_bufsize == size)) {
1403 if ((bpa->b_blkno == bpa->b_lblkno) ||
1405 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1411 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1412 if ((bpa = gbincore(vp, lblkno - j)) &&
1413 BUF_REFCNT(bpa) == 0 &&
1414 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1415 (B_DELWRI | B_CLUSTEROK)) &&
1416 (bpa->b_bufsize == size)) {
1417 if ((bpa->b_blkno == bpa->b_lblkno) ||
1419 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1428 * this is a possible cluster write
1431 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1437 BUF_LOCK(bp, LK_EXCLUSIVE);
1439 bp->b_flags |= B_ASYNC;
1443 * default (old) behavior, writing out only one block
1445 * XXX returns b_bufsize instead of b_bcount for nwritten?
1447 nwritten = bp->b_bufsize;
1448 (void) VOP_BWRITE(bp->b_vp, bp);
1456 * Find and initialize a new buffer header, freeing up existing buffers
1457 * in the bufqueues as necessary. The new buffer is returned locked.
1459 * Important: B_INVAL is not set. If the caller wishes to throw the
1460 * buffer away, the caller must set B_INVAL prior to calling brelse().
1463 * We have insufficient buffer headers
1464 * We have insufficient buffer space
1465 * buffer_map is too fragmented ( space reservation fails )
1466 * If we have to flush dirty buffers ( but we try to avoid this )
1468 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1469 * Instead we ask the buf daemon to do it for us. We attempt to
1470 * avoid piecemeal wakeups of the pageout daemon.
1474 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1480 static int flushingbufs;
1483 * We can't afford to block since we might be holding a vnode lock,
1484 * which may prevent system daemons from running. We deal with
1485 * low-memory situations by proactively returning memory and running
1486 * async I/O rather then sync I/O.
1490 --getnewbufrestarts;
1492 ++getnewbufrestarts;
1495 * Setup for scan. If we do not have enough free buffers,
1496 * we setup a degenerate case that immediately fails. Note
1497 * that if we are specially marked process, we are allowed to
1498 * dip into our reserves.
1500 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1502 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1503 * However, there are a number of cases (defragging, reusing, ...)
1504 * where we cannot backup.
1506 nqindex = QUEUE_EMPTYKVA;
1507 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1511 * If no EMPTYKVA buffers and we are either
1512 * defragging or reusing, locate a CLEAN buffer
1513 * to free or reuse. If bufspace useage is low
1514 * skip this step so we can allocate a new buffer.
1516 if (defrag || bufspace >= lobufspace) {
1517 nqindex = QUEUE_CLEAN;
1518 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1522 * If we could not find or were not allowed to reuse a
1523 * CLEAN buffer, check to see if it is ok to use an EMPTY
1524 * buffer. We can only use an EMPTY buffer if allocating
1525 * its KVA would not otherwise run us out of buffer space.
1527 if (nbp == NULL && defrag == 0 &&
1528 bufspace + maxsize < hibufspace) {
1529 nqindex = QUEUE_EMPTY;
1530 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1535 * Run scan, possibly freeing data and/or kva mappings on the fly
1539 while ((bp = nbp) != NULL) {
1540 int qindex = nqindex;
1543 * Calculate next bp ( we can only use it if we do not block
1544 * or do other fancy things ).
1546 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1549 nqindex = QUEUE_EMPTYKVA;
1550 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1553 case QUEUE_EMPTYKVA:
1554 nqindex = QUEUE_CLEAN;
1555 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1569 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1572 * Note: we no longer distinguish between VMIO and non-VMIO
1576 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1579 * If we are defragging then we need a buffer with
1580 * b_kvasize != 0. XXX this situation should no longer
1581 * occur, if defrag is non-zero the buffer's b_kvasize
1582 * should also be non-zero at this point. XXX
1584 if (defrag && bp->b_kvasize == 0) {
1585 printf("Warning: defrag empty buffer %p\n", bp);
1590 * Start freeing the bp. This is somewhat involved. nbp
1591 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1594 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1595 panic("getnewbuf: locked buf");
1598 if (qindex == QUEUE_CLEAN) {
1599 if (bp->b_flags & B_VMIO) {
1600 bp->b_flags &= ~B_ASYNC;
1601 vfs_vmio_release(bp);
1608 * NOTE: nbp is now entirely invalid. We can only restart
1609 * the scan from this point on.
1611 * Get the rest of the buffer freed up. b_kva* is still
1612 * valid after this operation.
1615 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1616 (*bioops.io_deallocate)(bp);
1617 if (bp->b_xflags & BX_BKGRDINPROG)
1618 panic("losing buffer 3");
1619 LIST_REMOVE(bp, b_hash);
1620 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1629 bp->b_blkno = bp->b_lblkno = 0;
1630 bp->b_offset = NOOFFSET;
1636 bp->b_dirtyoff = bp->b_dirtyend = 0;
1638 LIST_INIT(&bp->b_dep);
1641 * If we are defragging then free the buffer.
1644 bp->b_flags |= B_INVAL;
1652 * If we are overcomitted then recover the buffer and its
1653 * KVM space. This occurs in rare situations when multiple
1654 * processes are blocked in getnewbuf() or allocbuf().
1656 if (bufspace >= hibufspace)
1658 if (flushingbufs && bp->b_kvasize != 0) {
1659 bp->b_flags |= B_INVAL;
1664 if (bufspace < lobufspace)
1670 * If we exhausted our list, sleep as appropriate. We may have to
1671 * wakeup various daemons and write out some dirty buffers.
1673 * Generally we are sleeping due to insufficient buffer space.
1681 flags = VFS_BIO_NEED_BUFSPACE;
1683 } else if (bufspace >= hibufspace) {
1685 flags = VFS_BIO_NEED_BUFSPACE;
1688 flags = VFS_BIO_NEED_ANY;
1691 bd_speedup(); /* heeeelp */
1693 needsbuffer |= flags;
1694 while (needsbuffer & flags) {
1695 if (tsleep(&needsbuffer, (PRIBIO + 4) | slpflag,
1701 * We finally have a valid bp. We aren't quite out of the
1702 * woods, we still have to reserve kva space. In order
1703 * to keep fragmentation sane we only allocate kva in
1706 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1708 if (maxsize != bp->b_kvasize) {
1709 vm_offset_t addr = 0;
1713 vm_map_lock(buffer_map);
1715 if (vm_map_findspace(buffer_map,
1716 vm_map_min(buffer_map), maxsize, &addr)) {
1718 * Uh oh. Buffer map is to fragmented. We
1719 * must defragment the map.
1721 vm_map_unlock(buffer_map);
1724 bp->b_flags |= B_INVAL;
1729 vm_map_insert(buffer_map, NULL, 0,
1730 addr, addr + maxsize,
1731 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1733 bp->b_kvabase = (caddr_t) addr;
1734 bp->b_kvasize = maxsize;
1735 bufspace += bp->b_kvasize;
1738 vm_map_unlock(buffer_map);
1740 bp->b_data = bp->b_kvabase;
1748 * buffer flushing daemon. Buffers are normally flushed by the
1749 * update daemon but if it cannot keep up this process starts to
1750 * take the load in an attempt to prevent getnewbuf() from blocking.
1753 static struct thread *bufdaemonthread;
1755 static struct kproc_desc buf_kp = {
1760 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1768 * This process needs to be suspended prior to shutdown sync.
1770 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1771 bufdaemonthread, SHUTDOWN_PRI_LAST);
1774 * This process is allowed to take the buffer cache to the limit
1779 kproc_suspend_loop();
1782 * Do the flush. Limit the amount of in-transit I/O we
1783 * allow to build up, otherwise we would completely saturate
1784 * the I/O system. Wakeup any waiting processes before we
1785 * normally would so they can run in parallel with our drain.
1787 while (numdirtybuffers > lodirtybuffers) {
1788 if (flushbufqueues() == 0)
1790 waitrunningbufspace();
1791 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1795 * Only clear bd_request if we have reached our low water
1796 * mark. The buf_daemon normally waits 5 seconds and
1797 * then incrementally flushes any dirty buffers that have
1798 * built up, within reason.
1800 * If we were unable to hit our low water mark and couldn't
1801 * find any flushable buffers, we sleep half a second.
1802 * Otherwise we loop immediately.
1804 if (numdirtybuffers <= lodirtybuffers) {
1806 * We reached our low water mark, reset the
1807 * request and sleep until we are needed again.
1808 * The sleep is just so the suspend code works.
1811 tsleep(&bd_request, PVM, "psleep", hz);
1814 * We couldn't find any flushable dirty buffers but
1815 * still have too many dirty buffers, we
1816 * have to sleep and try again. (rare)
1818 tsleep(&bd_request, PVM, "qsleep", hz / 2);
1826 * Try to flush a buffer in the dirty queue. We must be careful to
1827 * free up B_INVAL buffers instead of write them, which NFS is
1828 * particularly sensitive to.
1832 flushbufqueues(void)
1837 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1840 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1841 if ((bp->b_flags & B_DELWRI) != 0 &&
1842 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1843 if (bp->b_flags & B_INVAL) {
1844 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1845 panic("flushbufqueues: locked buf");
1851 if (LIST_FIRST(&bp->b_dep) != NULL &&
1852 bioops.io_countdeps &&
1853 (bp->b_flags & B_DEFERRED) == 0 &&
1854 (*bioops.io_countdeps)(bp, 0)) {
1855 TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
1857 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
1859 bp->b_flags |= B_DEFERRED;
1860 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1867 bp = TAILQ_NEXT(bp, b_freelist);
1873 * Check to see if a block is currently memory resident.
1876 incore(struct vnode * vp, daddr_t blkno)
1881 bp = gbincore(vp, blkno);
1887 * Returns true if no I/O is needed to access the
1888 * associated VM object. This is like incore except
1889 * it also hunts around in the VM system for the data.
1893 inmem(struct vnode * vp, daddr_t blkno)
1896 vm_offset_t toff, tinc, size;
1900 if (incore(vp, blkno))
1902 if (vp->v_mount == NULL)
1904 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
1908 if (size > vp->v_mount->mnt_stat.f_iosize)
1909 size = vp->v_mount->mnt_stat.f_iosize;
1910 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
1912 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1913 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1917 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
1918 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
1919 if (vm_page_is_valid(m,
1920 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
1929 * Sets the dirty range for a buffer based on the status of the dirty
1930 * bits in the pages comprising the buffer.
1932 * The range is limited to the size of the buffer.
1934 * This routine is primarily used by NFS, but is generalized for the
1938 vfs_setdirty(struct buf *bp)
1944 * Degenerate case - empty buffer
1947 if (bp->b_bufsize == 0)
1951 * We qualify the scan for modified pages on whether the
1952 * object has been flushed yet. The OBJ_WRITEABLE flag
1953 * is not cleared simply by protecting pages off.
1956 if ((bp->b_flags & B_VMIO) == 0)
1959 object = bp->b_pages[0]->object;
1961 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
1962 printf("Warning: object %p writeable but not mightbedirty\n", object);
1963 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
1964 printf("Warning: object %p mightbedirty but not writeable\n", object);
1966 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
1967 vm_offset_t boffset;
1968 vm_offset_t eoffset;
1971 * test the pages to see if they have been modified directly
1972 * by users through the VM system.
1974 for (i = 0; i < bp->b_npages; i++) {
1975 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
1976 vm_page_test_dirty(bp->b_pages[i]);
1980 * Calculate the encompassing dirty range, boffset and eoffset,
1981 * (eoffset - boffset) bytes.
1984 for (i = 0; i < bp->b_npages; i++) {
1985 if (bp->b_pages[i]->dirty)
1988 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
1990 for (i = bp->b_npages - 1; i >= 0; --i) {
1991 if (bp->b_pages[i]->dirty) {
1995 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
1998 * Fit it to the buffer.
2001 if (eoffset > bp->b_bcount)
2002 eoffset = bp->b_bcount;
2005 * If we have a good dirty range, merge with the existing
2009 if (boffset < eoffset) {
2010 if (bp->b_dirtyoff > boffset)
2011 bp->b_dirtyoff = boffset;
2012 if (bp->b_dirtyend < eoffset)
2013 bp->b_dirtyend = eoffset;
2021 * Get a block given a specified block and offset into a file/device.
2022 * The buffers B_DONE bit will be cleared on return, making it almost
2023 * ready for an I/O initiation. B_INVAL may or may not be set on
2024 * return. The caller should clear B_INVAL prior to initiating a
2027 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2028 * an existing buffer.
2030 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2031 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2032 * and then cleared based on the backing VM. If the previous buffer is
2033 * non-0-sized but invalid, B_CACHE will be cleared.
2035 * If getblk() must create a new buffer, the new buffer is returned with
2036 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2037 * case it is returned with B_INVAL clear and B_CACHE set based on the
2040 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2041 * B_CACHE bit is clear.
2043 * What this means, basically, is that the caller should use B_CACHE to
2044 * determine whether the buffer is fully valid or not and should clear
2045 * B_INVAL prior to issuing a read. If the caller intends to validate
2046 * the buffer by loading its data area with something, the caller needs
2047 * to clear B_INVAL. If the caller does this without issuing an I/O,
2048 * the caller should set B_CACHE ( as an optimization ), else the caller
2049 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2050 * a write attempt or if it was a successfull read. If the caller
2051 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2052 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2055 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2059 struct bufhashhdr *bh;
2061 if (size > MAXBSIZE)
2062 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2067 * Block if we are low on buffers. Certain processes are allowed
2068 * to completely exhaust the buffer cache.
2070 * If this check ever becomes a bottleneck it may be better to
2071 * move it into the else, when gbincore() fails. At the moment
2072 * it isn't a problem.
2074 * XXX remove, we cannot afford to block anywhere if holding a vnode
2075 * lock in low-memory situation, so take it to the max.
2077 if (numfreebuffers == 0) {
2080 needsbuffer |= VFS_BIO_NEED_ANY;
2081 tsleep(&needsbuffer, (PRIBIO + 4) | slpflag, "newbuf",
2085 if ((bp = gbincore(vp, blkno))) {
2087 * Buffer is in-core. If the buffer is not busy, it must
2091 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2092 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2093 "getblk", slpflag, slptimeo) == ENOLCK)
2096 return (struct buf *) NULL;
2100 * The buffer is locked. B_CACHE is cleared if the buffer is
2101 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2102 * and for a VMIO buffer B_CACHE is adjusted according to the
2105 if (bp->b_flags & B_INVAL)
2106 bp->b_flags &= ~B_CACHE;
2107 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2108 bp->b_flags |= B_CACHE;
2112 * check for size inconsistancies for non-VMIO case.
2115 if (bp->b_bcount != size) {
2116 if ((bp->b_flags & B_VMIO) == 0 ||
2117 (size > bp->b_kvasize)) {
2118 if (bp->b_flags & B_DELWRI) {
2119 bp->b_flags |= B_NOCACHE;
2120 VOP_BWRITE(bp->b_vp, bp);
2122 if ((bp->b_flags & B_VMIO) &&
2123 (LIST_FIRST(&bp->b_dep) == NULL)) {
2124 bp->b_flags |= B_RELBUF;
2127 bp->b_flags |= B_NOCACHE;
2128 VOP_BWRITE(bp->b_vp, bp);
2136 * If the size is inconsistant in the VMIO case, we can resize
2137 * the buffer. This might lead to B_CACHE getting set or
2138 * cleared. If the size has not changed, B_CACHE remains
2139 * unchanged from its previous state.
2142 if (bp->b_bcount != size)
2145 KASSERT(bp->b_offset != NOOFFSET,
2146 ("getblk: no buffer offset"));
2149 * A buffer with B_DELWRI set and B_CACHE clear must
2150 * be committed before we can return the buffer in
2151 * order to prevent the caller from issuing a read
2152 * ( due to B_CACHE not being set ) and overwriting
2155 * Most callers, including NFS and FFS, need this to
2156 * operate properly either because they assume they
2157 * can issue a read if B_CACHE is not set, or because
2158 * ( for example ) an uncached B_DELWRI might loop due
2159 * to softupdates re-dirtying the buffer. In the latter
2160 * case, B_CACHE is set after the first write completes,
2161 * preventing further loops.
2163 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2164 * above while extending the buffer, we cannot allow the
2165 * buffer to remain with B_CACHE set after the write
2166 * completes or it will represent a corrupt state. To
2167 * deal with this we set B_NOCACHE to scrap the buffer
2170 * We might be able to do something fancy, like setting
2171 * B_CACHE in bwrite() except if B_DELWRI is already set,
2172 * so the below call doesn't set B_CACHE, but that gets real
2173 * confusing. This is much easier.
2176 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2177 bp->b_flags |= B_NOCACHE;
2178 VOP_BWRITE(bp->b_vp, bp);
2183 bp->b_flags &= ~B_DONE;
2186 * Buffer is not in-core, create new buffer. The buffer
2187 * returned by getnewbuf() is locked. Note that the returned
2188 * buffer is also considered valid (not marked B_INVAL).
2190 int bsize, maxsize, vmio;
2193 if (vn_isdisk(vp, NULL))
2195 else if (vp->v_mountedhere)
2196 bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2197 else if (vp->v_mount)
2198 bsize = vp->v_mount->mnt_stat.f_iosize;
2202 offset = (off_t)blkno * bsize;
2203 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2204 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2205 maxsize = imax(maxsize, bsize);
2207 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2208 if (slpflag || slptimeo) {
2216 * This code is used to make sure that a buffer is not
2217 * created while the getnewbuf routine is blocked.
2218 * This can be a problem whether the vnode is locked or not.
2219 * If the buffer is created out from under us, we have to
2220 * throw away the one we just created. There is now window
2221 * race because we are safely running at splbio() from the
2222 * point of the duplicate buffer creation through to here,
2223 * and we've locked the buffer.
2225 if (gbincore(vp, blkno)) {
2226 bp->b_flags |= B_INVAL;
2232 * Insert the buffer into the hash, so that it can
2233 * be found by incore.
2235 bp->b_blkno = bp->b_lblkno = blkno;
2236 bp->b_offset = offset;
2239 LIST_REMOVE(bp, b_hash);
2240 bh = bufhash(vp, blkno);
2241 LIST_INSERT_HEAD(bh, bp, b_hash);
2244 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2245 * buffer size starts out as 0, B_CACHE will be set by
2246 * allocbuf() for the VMIO case prior to it testing the
2247 * backing store for validity.
2251 bp->b_flags |= B_VMIO;
2252 #if defined(VFS_BIO_DEBUG)
2253 if (vp->v_type != VREG && vp->v_type != VBLK)
2254 printf("getblk: vmioing file type %d???\n", vp->v_type);
2257 bp->b_flags &= ~B_VMIO;
2263 bp->b_flags &= ~B_DONE;
2269 * Get an empty, disassociated buffer of given size. The buffer is initially
2279 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2282 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2285 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2291 * This code constitutes the buffer memory from either anonymous system
2292 * memory (in the case of non-VMIO operations) or from an associated
2293 * VM object (in the case of VMIO operations). This code is able to
2294 * resize a buffer up or down.
2296 * Note that this code is tricky, and has many complications to resolve
2297 * deadlock or inconsistant data situations. Tread lightly!!!
2298 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2299 * the caller. Calling this code willy nilly can result in the loss of data.
2301 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2302 * B_CACHE for the non-VMIO case.
2306 allocbuf(struct buf *bp, int size)
2308 int newbsize, mbsize;
2311 if (BUF_REFCNT(bp) == 0)
2312 panic("allocbuf: buffer not busy");
2314 if (bp->b_kvasize < size)
2315 panic("allocbuf: buffer too small");
2317 if ((bp->b_flags & B_VMIO) == 0) {
2321 * Just get anonymous memory from the kernel. Don't
2322 * mess with B_CACHE.
2324 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2325 #if !defined(NO_B_MALLOC)
2326 if (bp->b_flags & B_MALLOC)
2330 newbsize = round_page(size);
2332 if (newbsize < bp->b_bufsize) {
2333 #if !defined(NO_B_MALLOC)
2335 * malloced buffers are not shrunk
2337 if (bp->b_flags & B_MALLOC) {
2339 bp->b_bcount = size;
2341 free(bp->b_data, M_BIOBUF);
2342 if (bp->b_bufsize) {
2343 bufmallocspace -= bp->b_bufsize;
2347 bp->b_data = bp->b_kvabase;
2349 bp->b_flags &= ~B_MALLOC;
2356 (vm_offset_t) bp->b_data + newbsize,
2357 (vm_offset_t) bp->b_data + bp->b_bufsize);
2358 } else if (newbsize > bp->b_bufsize) {
2359 #if !defined(NO_B_MALLOC)
2361 * We only use malloced memory on the first allocation.
2362 * and revert to page-allocated memory when the buffer
2365 if ( (bufmallocspace < maxbufmallocspace) &&
2366 (bp->b_bufsize == 0) &&
2367 (mbsize <= PAGE_SIZE/2)) {
2369 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2370 bp->b_bufsize = mbsize;
2371 bp->b_bcount = size;
2372 bp->b_flags |= B_MALLOC;
2373 bufmallocspace += mbsize;
2379 #if !defined(NO_B_MALLOC)
2381 * If the buffer is growing on its other-than-first allocation,
2382 * then we revert to the page-allocation scheme.
2384 if (bp->b_flags & B_MALLOC) {
2385 origbuf = bp->b_data;
2386 origbufsize = bp->b_bufsize;
2387 bp->b_data = bp->b_kvabase;
2388 if (bp->b_bufsize) {
2389 bufmallocspace -= bp->b_bufsize;
2393 bp->b_flags &= ~B_MALLOC;
2394 newbsize = round_page(newbsize);
2399 (vm_offset_t) bp->b_data + bp->b_bufsize,
2400 (vm_offset_t) bp->b_data + newbsize);
2401 #if !defined(NO_B_MALLOC)
2403 bcopy(origbuf, bp->b_data, origbufsize);
2404 free(origbuf, M_BIOBUF);
2412 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2413 desiredpages = (size == 0) ? 0 :
2414 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2416 #if !defined(NO_B_MALLOC)
2417 if (bp->b_flags & B_MALLOC)
2418 panic("allocbuf: VMIO buffer can't be malloced");
2421 * Set B_CACHE initially if buffer is 0 length or will become
2424 if (size == 0 || bp->b_bufsize == 0)
2425 bp->b_flags |= B_CACHE;
2427 if (newbsize < bp->b_bufsize) {
2429 * DEV_BSIZE aligned new buffer size is less then the
2430 * DEV_BSIZE aligned existing buffer size. Figure out
2431 * if we have to remove any pages.
2433 if (desiredpages < bp->b_npages) {
2434 for (i = desiredpages; i < bp->b_npages; i++) {
2436 * the page is not freed here -- it
2437 * is the responsibility of
2438 * vnode_pager_setsize
2441 KASSERT(m != bogus_page,
2442 ("allocbuf: bogus page found"));
2443 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2446 bp->b_pages[i] = NULL;
2447 vm_page_unwire(m, 0);
2449 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2450 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2451 bp->b_npages = desiredpages;
2453 } else if (size > bp->b_bcount) {
2455 * We are growing the buffer, possibly in a
2456 * byte-granular fashion.
2464 * Step 1, bring in the VM pages from the object,
2465 * allocating them if necessary. We must clear
2466 * B_CACHE if these pages are not valid for the
2467 * range covered by the buffer.
2471 VOP_GETVOBJECT(vp, &obj);
2473 while (bp->b_npages < desiredpages) {
2477 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2478 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2480 * note: must allocate system pages
2481 * since blocking here could intefere
2482 * with paging I/O, no matter which
2485 m = vm_page_alloc(obj, pi, VM_ALLOC_SYSTEM);
2488 vm_pageout_deficit += desiredpages - bp->b_npages;
2492 bp->b_flags &= ~B_CACHE;
2493 bp->b_pages[bp->b_npages] = m;
2500 * We found a page. If we have to sleep on it,
2501 * retry because it might have gotten freed out
2504 * We can only test PG_BUSY here. Blocking on
2505 * m->busy might lead to a deadlock:
2507 * vm_fault->getpages->cluster_read->allocbuf
2511 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2515 * We have a good page. Should we wakeup the
2518 if ((curthread != pagethread) &&
2519 ((m->queue - m->pc) == PQ_CACHE) &&
2520 ((cnt.v_free_count + cnt.v_cache_count) <
2521 (cnt.v_free_min + cnt.v_cache_min))) {
2522 pagedaemon_wakeup();
2524 vm_page_flag_clear(m, PG_ZERO);
2526 bp->b_pages[bp->b_npages] = m;
2531 * Step 2. We've loaded the pages into the buffer,
2532 * we have to figure out if we can still have B_CACHE
2533 * set. Note that B_CACHE is set according to the
2534 * byte-granular range ( bcount and size ), new the
2535 * aligned range ( newbsize ).
2537 * The VM test is against m->valid, which is DEV_BSIZE
2538 * aligned. Needless to say, the validity of the data
2539 * needs to also be DEV_BSIZE aligned. Note that this
2540 * fails with NFS if the server or some other client
2541 * extends the file's EOF. If our buffer is resized,
2542 * B_CACHE may remain set! XXX
2545 toff = bp->b_bcount;
2546 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2548 while ((bp->b_flags & B_CACHE) && toff < size) {
2551 if (tinc > (size - toff))
2554 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2569 * Step 3, fixup the KVM pmap. Remember that
2570 * bp->b_data is relative to bp->b_offset, but
2571 * bp->b_offset may be offset into the first page.
2574 bp->b_data = (caddr_t)
2575 trunc_page((vm_offset_t)bp->b_data);
2577 (vm_offset_t)bp->b_data,
2581 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2582 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2585 if (newbsize < bp->b_bufsize)
2587 bp->b_bufsize = newbsize; /* actual buffer allocation */
2588 bp->b_bcount = size; /* requested buffer size */
2595 * Wait for buffer I/O completion, returning error status. The buffer
2596 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2597 * error and cleared.
2600 biowait(register struct buf * bp)
2605 while ((bp->b_flags & B_DONE) == 0) {
2606 #if defined(NO_SCHEDULE_MODS)
2607 tsleep(bp, PRIBIO, "biowait", 0);
2609 if (bp->b_flags & B_READ)
2610 tsleep(bp, PRIBIO, "biord", 0);
2612 tsleep(bp, PRIBIO, "biowr", 0);
2616 if (bp->b_flags & B_EINTR) {
2617 bp->b_flags &= ~B_EINTR;
2620 if (bp->b_flags & B_ERROR) {
2621 return (bp->b_error ? bp->b_error : EIO);
2630 * Finish I/O on a buffer, optionally calling a completion function.
2631 * This is usually called from an interrupt so process blocking is
2634 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2635 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2636 * assuming B_INVAL is clear.
2638 * For the VMIO case, we set B_CACHE if the op was a read and no
2639 * read error occured, or if the op was a write. B_CACHE is never
2640 * set if the buffer is invalid or otherwise uncacheable.
2642 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2643 * initiator to leave B_INVAL set to brelse the buffer out of existance
2644 * in the biodone routine.
2647 biodone(register struct buf * bp)
2653 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2654 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2656 bp->b_flags |= B_DONE;
2657 runningbufwakeup(bp);
2659 if (bp->b_flags & B_FREEBUF) {
2665 if ((bp->b_flags & B_READ) == 0) {
2669 /* call optional completion function if requested */
2670 if (bp->b_flags & B_CALL) {
2671 bp->b_flags &= ~B_CALL;
2672 (*bp->b_iodone) (bp);
2676 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2677 (*bioops.io_complete)(bp);
2679 if (bp->b_flags & B_VMIO) {
2685 struct vnode *vp = bp->b_vp;
2687 error = VOP_GETVOBJECT(vp, &obj);
2689 #if defined(VFS_BIO_DEBUG)
2690 if (vp->v_usecount == 0) {
2691 panic("biodone: zero vnode ref count");
2695 panic("biodone: missing VM object");
2698 if ((vp->v_flag & VOBJBUF) == 0) {
2699 panic("biodone: vnode is not setup for merged cache");
2703 foff = bp->b_offset;
2704 KASSERT(bp->b_offset != NOOFFSET,
2705 ("biodone: no buffer offset"));
2708 panic("biodone: no object");
2710 #if defined(VFS_BIO_DEBUG)
2711 if (obj->paging_in_progress < bp->b_npages) {
2712 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2713 obj->paging_in_progress, bp->b_npages);
2718 * Set B_CACHE if the op was a normal read and no error
2719 * occured. B_CACHE is set for writes in the b*write()
2722 iosize = bp->b_bcount - bp->b_resid;
2723 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2724 bp->b_flags |= B_CACHE;
2727 for (i = 0; i < bp->b_npages; i++) {
2731 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2736 * cleanup bogus pages, restoring the originals
2739 if (m == bogus_page) {
2741 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2743 panic("biodone: page disappeared");
2745 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2747 #if defined(VFS_BIO_DEBUG)
2748 if (OFF_TO_IDX(foff) != m->pindex) {
2750 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2751 (unsigned long)foff, m->pindex);
2756 * In the write case, the valid and clean bits are
2757 * already changed correctly ( see bdwrite() ), so we
2758 * only need to do this here in the read case.
2760 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2761 vfs_page_set_valid(bp, foff, i, m);
2763 vm_page_flag_clear(m, PG_ZERO);
2766 * when debugging new filesystems or buffer I/O methods, this
2767 * is the most common error that pops up. if you see this, you
2768 * have not set the page busy flag correctly!!!
2771 printf("biodone: page busy < 0, "
2772 "pindex: %d, foff: 0x(%x,%x), "
2773 "resid: %d, index: %d\n",
2774 (int) m->pindex, (int)(foff >> 32),
2775 (int) foff & 0xffffffff, resid, i);
2776 if (!vn_isdisk(vp, NULL))
2777 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2778 bp->b_vp->v_mount->mnt_stat.f_iosize,
2780 bp->b_flags, bp->b_npages);
2782 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2784 bp->b_flags, bp->b_npages);
2785 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2786 m->valid, m->dirty, m->wire_count);
2787 panic("biodone: page busy < 0\n");
2789 vm_page_io_finish(m);
2790 vm_object_pip_subtract(obj, 1);
2791 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2795 vm_object_pip_wakeupn(obj, 0);
2799 * For asynchronous completions, release the buffer now. The brelse
2800 * will do a wakeup there if necessary - so no need to do a wakeup
2801 * here in the async case. The sync case always needs to do a wakeup.
2804 if (bp->b_flags & B_ASYNC) {
2805 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2816 * This routine is called in lieu of iodone in the case of
2817 * incomplete I/O. This keeps the busy status for pages
2821 vfs_unbusy_pages(struct buf * bp)
2825 runningbufwakeup(bp);
2826 if (bp->b_flags & B_VMIO) {
2827 struct vnode *vp = bp->b_vp;
2830 VOP_GETVOBJECT(vp, &obj);
2832 for (i = 0; i < bp->b_npages; i++) {
2833 vm_page_t m = bp->b_pages[i];
2835 if (m == bogus_page) {
2836 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2838 panic("vfs_unbusy_pages: page missing\n");
2841 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2843 vm_object_pip_subtract(obj, 1);
2844 vm_page_flag_clear(m, PG_ZERO);
2845 vm_page_io_finish(m);
2847 vm_object_pip_wakeupn(obj, 0);
2852 * vfs_page_set_valid:
2854 * Set the valid bits in a page based on the supplied offset. The
2855 * range is restricted to the buffer's size.
2857 * This routine is typically called after a read completes.
2860 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2862 vm_ooffset_t soff, eoff;
2865 * Start and end offsets in buffer. eoff - soff may not cross a
2866 * page boundry or cross the end of the buffer. The end of the
2867 * buffer, in this case, is our file EOF, not the allocation size
2871 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2872 if (eoff > bp->b_offset + bp->b_bcount)
2873 eoff = bp->b_offset + bp->b_bcount;
2876 * Set valid range. This is typically the entire buffer and thus the
2880 vm_page_set_validclean(
2882 (vm_offset_t) (soff & PAGE_MASK),
2883 (vm_offset_t) (eoff - soff)
2889 * This routine is called before a device strategy routine.
2890 * It is used to tell the VM system that paging I/O is in
2891 * progress, and treat the pages associated with the buffer
2892 * almost as being PG_BUSY. Also the object paging_in_progress
2893 * flag is handled to make sure that the object doesn't become
2896 * Since I/O has not been initiated yet, certain buffer flags
2897 * such as B_ERROR or B_INVAL may be in an inconsistant state
2898 * and should be ignored.
2901 vfs_busy_pages(struct buf * bp, int clear_modify)
2905 if (bp->b_flags & B_VMIO) {
2906 struct vnode *vp = bp->b_vp;
2910 VOP_GETVOBJECT(vp, &obj);
2911 foff = bp->b_offset;
2912 KASSERT(bp->b_offset != NOOFFSET,
2913 ("vfs_busy_pages: no buffer offset"));
2917 for (i = 0; i < bp->b_npages; i++) {
2918 vm_page_t m = bp->b_pages[i];
2919 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
2924 for (i = 0; i < bp->b_npages; i++) {
2925 vm_page_t m = bp->b_pages[i];
2927 vm_page_flag_clear(m, PG_ZERO);
2928 if ((bp->b_flags & B_CLUSTER) == 0) {
2929 vm_object_pip_add(obj, 1);
2930 vm_page_io_start(m);
2934 * When readying a buffer for a read ( i.e
2935 * clear_modify == 0 ), it is important to do
2936 * bogus_page replacement for valid pages in
2937 * partially instantiated buffers. Partially
2938 * instantiated buffers can, in turn, occur when
2939 * reconstituting a buffer from its VM backing store
2940 * base. We only have to do this if B_CACHE is
2941 * clear ( which causes the I/O to occur in the
2942 * first place ). The replacement prevents the read
2943 * I/O from overwriting potentially dirty VM-backed
2944 * pages. XXX bogus page replacement is, uh, bogus.
2945 * It may not work properly with small-block devices.
2946 * We need to find a better way.
2949 vm_page_protect(m, VM_PROT_NONE);
2951 vfs_page_set_valid(bp, foff, i, m);
2952 else if (m->valid == VM_PAGE_BITS_ALL &&
2953 (bp->b_flags & B_CACHE) == 0) {
2954 bp->b_pages[i] = bogus_page;
2957 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2960 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2964 * This is the easiest place to put the process accounting for the I/O
2970 if ((p = curthread->td_proc) != NULL) {
2971 if (bp->b_flags & B_READ)
2972 p->p_stats->p_ru.ru_inblock++;
2974 p->p_stats->p_ru.ru_oublock++;
2980 * Tell the VM system that the pages associated with this buffer
2981 * are clean. This is used for delayed writes where the data is
2982 * going to go to disk eventually without additional VM intevention.
2984 * Note that while we only really need to clean through to b_bcount, we
2985 * just go ahead and clean through to b_bufsize.
2988 vfs_clean_pages(struct buf * bp)
2992 if (bp->b_flags & B_VMIO) {
2995 foff = bp->b_offset;
2996 KASSERT(bp->b_offset != NOOFFSET,
2997 ("vfs_clean_pages: no buffer offset"));
2998 for (i = 0; i < bp->b_npages; i++) {
2999 vm_page_t m = bp->b_pages[i];
3000 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3001 vm_ooffset_t eoff = noff;
3003 if (eoff > bp->b_offset + bp->b_bufsize)
3004 eoff = bp->b_offset + bp->b_bufsize;
3005 vfs_page_set_valid(bp, foff, i, m);
3006 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3013 * vfs_bio_set_validclean:
3015 * Set the range within the buffer to valid and clean. The range is
3016 * relative to the beginning of the buffer, b_offset. Note that b_offset
3017 * itself may be offset from the beginning of the first page.
3021 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3023 if (bp->b_flags & B_VMIO) {
3028 * Fixup base to be relative to beginning of first page.
3029 * Set initial n to be the maximum number of bytes in the
3030 * first page that can be validated.
3033 base += (bp->b_offset & PAGE_MASK);
3034 n = PAGE_SIZE - (base & PAGE_MASK);
3036 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3037 vm_page_t m = bp->b_pages[i];
3042 vm_page_set_validclean(m, base & PAGE_MASK, n);
3053 * clear a buffer. This routine essentially fakes an I/O, so we need
3054 * to clear B_ERROR and B_INVAL.
3056 * Note that while we only theoretically need to clear through b_bcount,
3057 * we go ahead and clear through b_bufsize.
3061 vfs_bio_clrbuf(struct buf *bp)
3065 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3066 bp->b_flags &= ~(B_INVAL|B_ERROR);
3067 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3068 (bp->b_offset & PAGE_MASK) == 0) {
3069 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3070 if ((bp->b_pages[0]->valid & mask) == mask) {
3074 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3075 ((bp->b_pages[0]->valid & mask) == 0)) {
3076 bzero(bp->b_data, bp->b_bufsize);
3077 bp->b_pages[0]->valid |= mask;
3082 ea = sa = bp->b_data;
3083 for(i=0;i<bp->b_npages;i++,sa=ea) {
3084 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3085 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3086 ea = (caddr_t)(vm_offset_t)ulmin(
3087 (u_long)(vm_offset_t)ea,
3088 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3089 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3090 if ((bp->b_pages[i]->valid & mask) == mask)
3092 if ((bp->b_pages[i]->valid & mask) == 0) {
3093 if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3097 for (; sa < ea; sa += DEV_BSIZE, j++) {
3098 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3099 (bp->b_pages[i]->valid & (1<<j)) == 0)
3100 bzero(sa, DEV_BSIZE);
3103 bp->b_pages[i]->valid |= mask;
3104 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3113 * vm_hold_load_pages and vm_hold_unload pages get pages into
3114 * a buffers address space. The pages are anonymous and are
3115 * not associated with a file object.
3118 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3124 to = round_page(to);
3125 from = round_page(from);
3126 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3128 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3133 * note: must allocate system pages since blocking here
3134 * could intefere with paging I/O, no matter which
3137 p = vm_page_alloc(kernel_object,
3138 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3141 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3146 p->valid = VM_PAGE_BITS_ALL;
3147 vm_page_flag_clear(p, PG_ZERO);
3148 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3149 bp->b_pages[index] = p;
3152 bp->b_npages = index;
3156 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3160 int index, newnpages;
3162 from = round_page(from);
3163 to = round_page(to);
3164 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3166 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3167 p = bp->b_pages[index];
3168 if (p && (index < bp->b_npages)) {
3170 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3171 bp->b_blkno, bp->b_lblkno);
3173 bp->b_pages[index] = NULL;
3176 vm_page_unwire(p, 0);
3180 bp->b_npages = newnpages;
3184 * Map an IO request into kernel virtual address space.
3186 * All requests are (re)mapped into kernel VA space.
3187 * Notice that we use b_bufsize for the size of the buffer
3188 * to be mapped. b_bcount might be modified by the driver.
3191 vmapbuf(struct buf *bp)
3193 caddr_t addr, v, kva;
3199 if ((bp->b_flags & B_PHYS) == 0)
3201 if (bp->b_bufsize < 0)
3203 for (v = bp->b_saveaddr,
3204 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3206 addr < bp->b_data + bp->b_bufsize;
3207 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3209 * Do the vm_fault if needed; do the copy-on-write thing
3210 * when reading stuff off device into memory.
3213 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3214 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3216 for (i = 0; i < pidx; ++i) {
3217 vm_page_unhold(bp->b_pages[i]);
3218 bp->b_pages[i] = NULL;
3224 * WARNING! If sparc support is MFCd in the future this will
3225 * have to be changed from pmap_kextract() to pmap_extract()
3229 #error "If MFCing sparc support use pmap_extract"
3231 pa = pmap_kextract((vm_offset_t)addr);
3233 printf("vmapbuf: warning, race against user address during I/O");
3236 m = PHYS_TO_VM_PAGE(pa);
3238 bp->b_pages[pidx] = m;
3240 if (pidx > btoc(MAXPHYS))
3241 panic("vmapbuf: mapped more than MAXPHYS");
3242 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3244 kva = bp->b_saveaddr;
3245 bp->b_npages = pidx;
3246 bp->b_saveaddr = bp->b_data;
3247 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3252 * Free the io map PTEs associated with this IO operation.
3253 * We also invalidate the TLB entries and restore the original b_addr.
3257 register struct buf *bp;
3263 if ((bp->b_flags & B_PHYS) == 0)
3266 npages = bp->b_npages;
3267 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3270 for (pidx = 0; pidx < npages; pidx++)
3271 vm_page_unhold(*m++);
3273 bp->b_data = bp->b_saveaddr;
3276 #include "opt_ddb.h"
3278 #include <ddb/ddb.h>
3280 DB_SHOW_COMMAND(buffer, db_show_buffer)
3283 struct buf *bp = (struct buf *)addr;
3286 db_printf("usage: show buffer <addr>\n");
3290 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3291 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3292 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3293 "b_blkno = %d, b_pblkno = %d\n",
3294 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3295 major(bp->b_dev), minor(bp->b_dev),
3296 bp->b_data, bp->b_blkno, bp->b_pblkno);
3299 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3300 for (i = 0; i < bp->b_npages; i++) {
3303 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3304 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3305 if ((i + 1) < bp->b_npages)