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.11 2003/07/26 19:42:11 rob 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>
57 #include <vm/vm_page2.h>
59 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
61 struct bio_ops bioops; /* I/O operation notification */
63 struct buf *buf; /* buffer header pool */
64 struct swqueue bswlist;
66 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
68 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
70 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
71 int pageno, vm_page_t m);
72 static void vfs_clean_pages(struct buf * bp);
73 static void vfs_setdirty(struct buf *bp);
74 static void vfs_vmio_release(struct buf *bp);
75 static void vfs_backgroundwritedone(struct buf *bp);
76 static int flushbufqueues(void);
78 static int bd_request;
80 static void buf_daemon __P((void));
82 * bogus page -- for I/O to/from partially complete buffers
83 * this is a temporary solution to the problem, but it is not
84 * really that bad. it would be better to split the buffer
85 * for input in the case of buffers partially already in memory,
86 * but the code is intricate enough already.
89 int vmiodirenable = TRUE;
91 static vm_offset_t bogus_offset;
93 static int bufspace, maxbufspace,
94 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
95 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
96 static int needsbuffer;
97 static int lorunningspace, hirunningspace, runningbufreq;
98 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
99 static int numfreebuffers, lofreebuffers, hifreebuffers;
100 static int getnewbufcalls;
101 static int getnewbufrestarts;
103 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
104 &numdirtybuffers, 0, "");
105 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
106 &lodirtybuffers, 0, "");
107 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
108 &hidirtybuffers, 0, "");
109 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
110 &numfreebuffers, 0, "");
111 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
112 &lofreebuffers, 0, "");
113 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
114 &hifreebuffers, 0, "");
115 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
116 &runningbufspace, 0, "");
117 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW,
118 &lorunningspace, 0, "");
119 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW,
120 &hirunningspace, 0, "");
121 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD,
122 &maxbufspace, 0, "");
123 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
125 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD,
127 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
129 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
130 &maxbufmallocspace, 0, "");
131 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
132 &bufmallocspace, 0, "");
133 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW,
134 &getnewbufcalls, 0, "");
135 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW,
136 &getnewbufrestarts, 0, "");
137 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW,
138 &vmiodirenable, 0, "");
139 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW,
140 &bufdefragcnt, 0, "");
141 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW,
142 &buffreekvacnt, 0, "");
143 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW,
144 &bufreusecnt, 0, "");
146 static int bufhashmask;
147 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
148 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
149 char *buf_wmesg = BUF_WMESG;
151 extern int vm_swap_size;
153 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
154 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
155 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
156 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
159 * Buffer hash table code. Note that the logical block scans linearly, which
160 * gives us some L1 cache locality.
165 bufhash(struct vnode *vnp, daddr_t bn)
167 return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
173 * If someone is blocked due to there being too many dirty buffers,
174 * and numdirtybuffers is now reasonable, wake them up.
178 numdirtywakeup(int level)
180 if (numdirtybuffers <= level) {
181 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
182 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
183 wakeup(&needsbuffer);
191 * Called when buffer space is potentially available for recovery.
192 * getnewbuf() will block on this flag when it is unable to free
193 * sufficient buffer space. Buffer space becomes recoverable when
194 * bp's get placed back in the queues.
201 * If someone is waiting for BUF space, wake them up. Even
202 * though we haven't freed the kva space yet, the waiting
203 * process will be able to now.
205 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
206 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
207 wakeup(&needsbuffer);
212 * runningbufwakeup() - in-progress I/O accounting.
216 runningbufwakeup(struct buf *bp)
218 if (bp->b_runningbufspace) {
219 runningbufspace -= bp->b_runningbufspace;
220 bp->b_runningbufspace = 0;
221 if (runningbufreq && runningbufspace <= lorunningspace) {
223 wakeup(&runningbufreq);
231 * Called when a buffer has been added to one of the free queues to
232 * account for the buffer and to wakeup anyone waiting for free buffers.
233 * This typically occurs when large amounts of metadata are being handled
234 * by the buffer cache ( else buffer space runs out first, usually ).
242 needsbuffer &= ~VFS_BIO_NEED_ANY;
243 if (numfreebuffers >= hifreebuffers)
244 needsbuffer &= ~VFS_BIO_NEED_FREE;
245 wakeup(&needsbuffer);
250 * waitrunningbufspace()
252 * runningbufspace is a measure of the amount of I/O currently
253 * running. This routine is used in async-write situations to
254 * prevent creating huge backups of pending writes to a device.
255 * Only asynchronous writes are governed by this function.
257 * Reads will adjust runningbufspace, but will not block based on it.
258 * The read load has a side effect of reducing the allowed write load.
260 * This does NOT turn an async write into a sync write. It waits
261 * for earlier writes to complete and generally returns before the
262 * caller's write has reached the device.
265 waitrunningbufspace(void)
267 while (runningbufspace > hirunningspace) {
270 s = splbio(); /* fix race against interrupt/biodone() */
272 tsleep(&runningbufreq, 0, "wdrain", 0);
278 * vfs_buf_test_cache:
280 * Called when a buffer is extended. This function clears the B_CACHE
281 * bit if the newly extended portion of the buffer does not contain
286 vfs_buf_test_cache(struct buf *bp,
287 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
290 if (bp->b_flags & B_CACHE) {
291 int base = (foff + off) & PAGE_MASK;
292 if (vm_page_is_valid(m, base, size) == 0)
293 bp->b_flags &= ~B_CACHE;
299 bd_wakeup(int dirtybuflevel)
301 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
308 * bd_speedup - speedup the buffer cache flushing code
319 * Initialize buffer headers and related structures.
323 bufhashinit(caddr_t vaddr)
325 /* first, make a null hash table */
326 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
328 bufhashtbl = (void *)vaddr;
329 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
340 TAILQ_INIT(&bswlist);
341 LIST_INIT(&invalhash);
342 lwkt_inittoken(&buftimetoken);
344 for (i = 0; i <= bufhashmask; i++)
345 LIST_INIT(&bufhashtbl[i]);
347 /* next, make a null set of free lists */
348 for (i = 0; i < BUFFER_QUEUES; i++)
349 TAILQ_INIT(&bufqueues[i]);
351 /* finally, initialize each buffer header and stick on empty q */
352 for (i = 0; i < nbuf; i++) {
354 bzero(bp, sizeof *bp);
355 bp->b_flags = B_INVAL; /* we're just an empty header */
357 bp->b_qindex = QUEUE_EMPTY;
359 LIST_INIT(&bp->b_dep);
361 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
362 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
366 * maxbufspace is the absolute maximum amount of buffer space we are
367 * allowed to reserve in KVM and in real terms. The absolute maximum
368 * is nominally used by buf_daemon. hibufspace is the nominal maximum
369 * used by most other processes. The differential is required to
370 * ensure that buf_daemon is able to run when other processes might
371 * be blocked waiting for buffer space.
373 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
374 * this may result in KVM fragmentation which is not handled optimally
377 maxbufspace = nbuf * BKVASIZE;
378 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
379 lobufspace = hibufspace - MAXBSIZE;
381 lorunningspace = 512 * 1024;
382 hirunningspace = 1024 * 1024;
385 * Limit the amount of malloc memory since it is wired permanently into
386 * the kernel space. Even though this is accounted for in the buffer
387 * allocation, we don't want the malloced region to grow uncontrolled.
388 * The malloc scheme improves memory utilization significantly on average
389 * (small) directories.
391 maxbufmallocspace = hibufspace / 20;
394 * Reduce the chance of a deadlock occuring by limiting the number
395 * of delayed-write dirty buffers we allow to stack up.
397 hidirtybuffers = nbuf / 4 + 20;
400 * To support extreme low-memory systems, make sure hidirtybuffers cannot
401 * eat up all available buffer space. This occurs when our minimum cannot
402 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
403 * BKVASIZE'd (8K) buffers.
405 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
406 hidirtybuffers >>= 1;
408 lodirtybuffers = hidirtybuffers / 2;
411 * Try to keep the number of free buffers in the specified range,
412 * and give special processes (e.g. like buf_daemon) access to an
415 lofreebuffers = nbuf / 18 + 5;
416 hifreebuffers = 2 * lofreebuffers;
417 numfreebuffers = nbuf;
420 * Maximum number of async ops initiated per buf_daemon loop. This is
421 * somewhat of a hack at the moment, we really need to limit ourselves
422 * based on the number of bytes of I/O in-transit that were initiated
426 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
427 bogus_page = vm_page_alloc(kernel_object,
428 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
430 vmstats.v_wire_count++;
435 * bfreekva() - free the kva allocation for a buffer.
437 * Must be called at splbio() or higher as this is the only locking for
440 * Since this call frees up buffer space, we call bufspacewakeup().
443 bfreekva(struct buf * bp)
447 vm_map_lock(buffer_map);
448 bufspace -= bp->b_kvasize;
449 vm_map_delete(buffer_map,
450 (vm_offset_t) bp->b_kvabase,
451 (vm_offset_t) bp->b_kvabase + bp->b_kvasize
453 vm_map_unlock(buffer_map);
462 * Remove the buffer from the appropriate free list.
465 bremfree(struct buf * bp)
468 int old_qindex = bp->b_qindex;
470 if (bp->b_qindex != QUEUE_NONE) {
471 KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
472 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
473 bp->b_qindex = QUEUE_NONE;
475 if (BUF_REFCNT(bp) <= 1)
476 panic("bremfree: removing a buffer not on a queue");
480 * Fixup numfreebuffers count. If the buffer is invalid or not
481 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
482 * the buffer was free and we must decrement numfreebuffers.
484 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
501 * Get a buffer with the specified data. Look in the cache first. We
502 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
503 * is set, the buffer is valid and we do not have to do anything ( see
507 bread(struct vnode * vp, daddr_t blkno, int size, struct buf ** bpp)
511 bp = getblk(vp, blkno, size, 0, 0);
514 /* if not found in cache, do some I/O */
515 if ((bp->b_flags & B_CACHE) == 0) {
516 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
517 bp->b_flags |= B_READ;
518 bp->b_flags &= ~(B_ERROR | B_INVAL);
519 vfs_busy_pages(bp, 0);
520 VOP_STRATEGY(vp, bp);
521 return (biowait(bp));
527 * Operates like bread, but also starts asynchronous I/O on
528 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
529 * to initiating I/O . If B_CACHE is set, the buffer is valid
530 * and we do not have to do anything.
533 breadn(struct vnode * vp, daddr_t blkno, int size, daddr_t * rablkno,
534 int *rabsize, int cnt, struct buf ** bpp)
536 struct buf *bp, *rabp;
538 int rv = 0, readwait = 0;
540 *bpp = bp = getblk(vp, blkno, size, 0, 0);
542 /* if not found in cache, do some I/O */
543 if ((bp->b_flags & B_CACHE) == 0) {
544 bp->b_flags |= B_READ;
545 bp->b_flags &= ~(B_ERROR | B_INVAL);
546 vfs_busy_pages(bp, 0);
547 VOP_STRATEGY(vp, bp);
551 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
552 if (inmem(vp, *rablkno))
554 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
556 if ((rabp->b_flags & B_CACHE) == 0) {
557 rabp->b_flags |= B_READ | B_ASYNC;
558 rabp->b_flags &= ~(B_ERROR | B_INVAL);
559 vfs_busy_pages(rabp, 0);
561 VOP_STRATEGY(vp, rabp);
574 * Write, release buffer on completion. (Done by iodone
575 * if async). Do not bother writing anything if the buffer
578 * Note that we set B_CACHE here, indicating that buffer is
579 * fully valid and thus cacheable. This is true even of NFS
580 * now so we set it generally. This could be set either here
581 * or in biodone() since the I/O is synchronous. We put it
585 bwrite(struct buf * bp)
590 if (bp->b_flags & B_INVAL) {
595 oldflags = bp->b_flags;
597 if (BUF_REFCNT(bp) == 0)
598 panic("bwrite: buffer is not busy???");
601 * If a background write is already in progress, delay
602 * writing this block if it is asynchronous. Otherwise
603 * wait for the background write to complete.
605 if (bp->b_xflags & BX_BKGRDINPROG) {
606 if (bp->b_flags & B_ASYNC) {
611 bp->b_xflags |= BX_BKGRDWAIT;
612 tsleep(&bp->b_xflags, 0, "biord", 0);
613 if (bp->b_xflags & BX_BKGRDINPROG)
614 panic("bwrite: still writing");
617 /* Mark the buffer clean */
621 * If this buffer is marked for background writing and we
622 * do not have to wait for it, make a copy and write the
623 * copy so as to leave this buffer ready for further use.
625 * This optimization eats a lot of memory. If we have a page
626 * or buffer shortfull we can't do it.
628 if ((bp->b_xflags & BX_BKGRDWRITE) &&
629 (bp->b_flags & B_ASYNC) &&
630 !vm_page_count_severe() &&
631 !buf_dirty_count_severe()) {
632 if (bp->b_flags & B_CALL)
633 panic("bwrite: need chained iodone");
635 /* get a new block */
636 newbp = geteblk(bp->b_bufsize);
638 /* set it to be identical to the old block */
639 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
640 bgetvp(bp->b_vp, newbp);
641 newbp->b_lblkno = bp->b_lblkno;
642 newbp->b_blkno = bp->b_blkno;
643 newbp->b_offset = bp->b_offset;
644 newbp->b_iodone = vfs_backgroundwritedone;
645 newbp->b_flags |= B_ASYNC | B_CALL;
646 newbp->b_flags &= ~B_INVAL;
648 /* move over the dependencies */
649 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
650 (*bioops.io_movedeps)(bp, newbp);
653 * Initiate write on the copy, release the original to
654 * the B_LOCKED queue so that it cannot go away until
655 * the background write completes. If not locked it could go
656 * away and then be reconstituted while it was being written.
657 * If the reconstituted buffer were written, we could end up
658 * with two background copies being written at the same time.
660 bp->b_xflags |= BX_BKGRDINPROG;
661 bp->b_flags |= B_LOCKED;
666 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
667 bp->b_flags |= B_WRITEINPROG | B_CACHE;
669 bp->b_vp->v_numoutput++;
670 vfs_busy_pages(bp, 1);
673 * Normal bwrites pipeline writes
675 bp->b_runningbufspace = bp->b_bufsize;
676 runningbufspace += bp->b_runningbufspace;
679 if (oldflags & B_ASYNC)
681 VOP_STRATEGY(bp->b_vp, bp);
683 if ((oldflags & B_ASYNC) == 0) {
684 int rtval = biowait(bp);
687 } else if ((oldflags & B_NOWDRAIN) == 0) {
689 * don't allow the async write to saturate the I/O
690 * system. Deadlocks can occur only if a device strategy
691 * routine (like in VN) turns around and issues another
692 * high-level write, in which case B_NOWDRAIN is expected
693 * to be set. Otherwise we will not deadlock here because
694 * we are blocking waiting for I/O that is already in-progress
697 waitrunningbufspace();
704 * Complete a background write started from bwrite.
707 vfs_backgroundwritedone(bp)
713 * Find the original buffer that we are writing.
715 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
716 panic("backgroundwritedone: lost buffer");
718 * Process dependencies then return any unfinished ones.
720 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
721 (*bioops.io_complete)(bp);
722 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
723 (*bioops.io_movedeps)(bp, origbp);
725 * Clear the BX_BKGRDINPROG flag in the original buffer
726 * and awaken it if it is waiting for the write to complete.
727 * If BX_BKGRDINPROG is not set in the original buffer it must
728 * have been released and re-instantiated - which is not legal.
730 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
731 origbp->b_xflags &= ~BX_BKGRDINPROG;
732 if (origbp->b_xflags & BX_BKGRDWAIT) {
733 origbp->b_xflags &= ~BX_BKGRDWAIT;
734 wakeup(&origbp->b_xflags);
737 * Clear the B_LOCKED flag and remove it from the locked
738 * queue if it currently resides there.
740 origbp->b_flags &= ~B_LOCKED;
741 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
746 * This buffer is marked B_NOCACHE, so when it is released
747 * by biodone, it will be tossed. We mark it with B_READ
748 * to avoid biodone doing a second vwakeup.
750 bp->b_flags |= B_NOCACHE | B_READ;
751 bp->b_flags &= ~(B_CACHE | B_CALL | B_DONE);
757 * Delayed write. (Buffer is marked dirty). Do not bother writing
758 * anything if the buffer is marked invalid.
760 * Note that since the buffer must be completely valid, we can safely
761 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
762 * biodone() in order to prevent getblk from writing the buffer
766 bdwrite(struct buf * bp)
768 if (BUF_REFCNT(bp) == 0)
769 panic("bdwrite: buffer is not busy");
771 if (bp->b_flags & B_INVAL) {
778 * Set B_CACHE, indicating that the buffer is fully valid. This is
779 * true even of NFS now.
781 bp->b_flags |= B_CACHE;
784 * This bmap keeps the system from needing to do the bmap later,
785 * perhaps when the system is attempting to do a sync. Since it
786 * is likely that the indirect block -- or whatever other datastructure
787 * that the filesystem needs is still in memory now, it is a good
788 * thing to do this. Note also, that if the pageout daemon is
789 * requesting a sync -- there might not be enough memory to do
790 * the bmap then... So, this is important to do.
792 if (bp->b_lblkno == bp->b_blkno) {
793 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
797 * Set the *dirty* buffer range based upon the VM system dirty pages.
802 * We need to do this here to satisfy the vnode_pager and the
803 * pageout daemon, so that it thinks that the pages have been
804 * "cleaned". Note that since the pages are in a delayed write
805 * buffer -- the VFS layer "will" see that the pages get written
806 * out on the next sync, or perhaps the cluster will be completed.
812 * Wakeup the buffer flushing daemon if we have a lot of dirty
813 * buffers (midpoint between our recovery point and our stall
816 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
819 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
820 * due to the softdep code.
827 * Turn buffer into delayed write request. We must clear B_READ and
828 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
829 * itself to properly update it in the dirty/clean lists. We mark it
830 * B_DONE to ensure that any asynchronization of the buffer properly
831 * clears B_DONE ( else a panic will occur later ).
833 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
834 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
835 * should only be called if the buffer is known-good.
837 * Since the buffer is not on a queue, we do not update the numfreebuffers
840 * Must be called at splbio().
841 * The buffer must be on QUEUE_NONE.
847 KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
848 bp->b_flags &= ~(B_READ|B_RELBUF);
850 if ((bp->b_flags & B_DELWRI) == 0) {
851 bp->b_flags |= B_DONE | B_DELWRI;
852 reassignbuf(bp, bp->b_vp);
854 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
861 * Clear B_DELWRI for buffer.
863 * Since the buffer is not on a queue, we do not update the numfreebuffers
866 * Must be called at splbio().
867 * The buffer must be on QUEUE_NONE.
874 KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
876 if (bp->b_flags & B_DELWRI) {
877 bp->b_flags &= ~B_DELWRI;
878 reassignbuf(bp, bp->b_vp);
880 numdirtywakeup(lodirtybuffers);
883 * Since it is now being written, we can clear its deferred write flag.
885 bp->b_flags &= ~B_DEFERRED;
891 * Asynchronous write. Start output on a buffer, but do not wait for
892 * it to complete. The buffer is released when the output completes.
894 * bwrite() ( or the VOP routine anyway ) is responsible for handling
895 * B_INVAL buffers. Not us.
898 bawrite(struct buf * bp)
900 bp->b_flags |= B_ASYNC;
901 (void) VOP_BWRITE(bp->b_vp, bp);
907 * Ordered write. Start output on a buffer, and flag it so that the
908 * device will write it in the order it was queued. The buffer is
909 * released when the output completes. bwrite() ( or the VOP routine
910 * anyway ) is responsible for handling B_INVAL buffers.
913 bowrite(struct buf * bp)
915 bp->b_flags |= B_ORDERED | B_ASYNC;
916 return (VOP_BWRITE(bp->b_vp, bp));
922 * Called prior to the locking of any vnodes when we are expecting to
923 * write. We do not want to starve the buffer cache with too many
924 * dirty buffers so we block here. By blocking prior to the locking
925 * of any vnodes we attempt to avoid the situation where a locked vnode
926 * prevents the various system daemons from flushing related buffers.
932 if (numdirtybuffers >= hidirtybuffers) {
936 while (numdirtybuffers >= hidirtybuffers) {
938 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
939 tsleep(&needsbuffer, 0, "flswai", 0);
946 * Return true if we have too many dirty buffers.
949 buf_dirty_count_severe(void)
951 return(numdirtybuffers >= hidirtybuffers);
957 * Release a busy buffer and, if requested, free its resources. The
958 * buffer will be stashed in the appropriate bufqueue[] allowing it
959 * to be accessed later as a cache entity or reused for other purposes.
962 brelse(struct buf * bp)
966 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
970 if (bp->b_flags & B_LOCKED)
971 bp->b_flags &= ~B_ERROR;
973 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
975 * Failed write, redirty. Must clear B_ERROR to prevent
976 * pages from being scrapped. If B_INVAL is set then
977 * this case is not run and the next case is run to
978 * destroy the buffer. B_INVAL can occur if the buffer
979 * is outside the range supported by the underlying device.
981 bp->b_flags &= ~B_ERROR;
983 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
984 (bp->b_bufsize <= 0)) {
986 * Either a failed I/O or we were asked to free or not
989 bp->b_flags |= B_INVAL;
990 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
991 (*bioops.io_deallocate)(bp);
992 if (bp->b_flags & B_DELWRI) {
994 numdirtywakeup(lodirtybuffers);
996 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
997 if ((bp->b_flags & B_VMIO) == 0) {
1006 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1007 * is called with B_DELWRI set, the underlying pages may wind up
1008 * getting freed causing a previous write (bdwrite()) to get 'lost'
1009 * because pages associated with a B_DELWRI bp are marked clean.
1011 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1012 * if B_DELWRI is set.
1014 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1015 * on pages to return pages to the VM page queues.
1017 if (bp->b_flags & B_DELWRI)
1018 bp->b_flags &= ~B_RELBUF;
1019 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1020 bp->b_flags |= B_RELBUF;
1023 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1024 * constituted, not even NFS buffers now. Two flags effect this. If
1025 * B_INVAL, the struct buf is invalidated but the VM object is kept
1026 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1028 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1029 * invalidated. B_ERROR cannot be set for a failed write unless the
1030 * buffer is also B_INVAL because it hits the re-dirtying code above.
1032 * Normally we can do this whether a buffer is B_DELWRI or not. If
1033 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1034 * the commit state and we cannot afford to lose the buffer. If the
1035 * buffer has a background write in progress, we need to keep it
1036 * around to prevent it from being reconstituted and starting a second
1039 if ((bp->b_flags & B_VMIO)
1040 && !(bp->b_vp->v_tag == VT_NFS &&
1041 !vn_isdisk(bp->b_vp, NULL) &&
1042 (bp->b_flags & B_DELWRI))
1055 * Get the base offset and length of the buffer. Note that
1056 * in the VMIO case if the buffer block size is not
1057 * page-aligned then b_data pointer may not be page-aligned.
1058 * But our b_pages[] array *IS* page aligned.
1060 * block sizes less then DEV_BSIZE (usually 512) are not
1061 * supported due to the page granularity bits (m->valid,
1062 * m->dirty, etc...).
1064 * See man buf(9) for more information
1067 resid = bp->b_bufsize;
1068 foff = bp->b_offset;
1070 for (i = 0; i < bp->b_npages; i++) {
1072 vm_page_flag_clear(m, PG_ZERO);
1074 * If we hit a bogus page, fixup *all* of them
1077 if (m == bogus_page) {
1078 VOP_GETVOBJECT(vp, &obj);
1079 poff = OFF_TO_IDX(bp->b_offset);
1081 for (j = i; j < bp->b_npages; j++) {
1084 mtmp = bp->b_pages[j];
1085 if (mtmp == bogus_page) {
1086 mtmp = vm_page_lookup(obj, poff + j);
1088 panic("brelse: page missing\n");
1090 bp->b_pages[j] = mtmp;
1094 if ((bp->b_flags & B_INVAL) == 0) {
1095 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1099 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1100 int poffset = foff & PAGE_MASK;
1101 int presid = resid > (PAGE_SIZE - poffset) ?
1102 (PAGE_SIZE - poffset) : resid;
1104 KASSERT(presid >= 0, ("brelse: extra page"));
1105 vm_page_set_invalid(m, poffset, presid);
1107 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1108 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1111 if (bp->b_flags & (B_INVAL | B_RELBUF))
1112 vfs_vmio_release(bp);
1114 } else if (bp->b_flags & B_VMIO) {
1116 if (bp->b_flags & (B_INVAL | B_RELBUF))
1117 vfs_vmio_release(bp);
1121 if (bp->b_qindex != QUEUE_NONE)
1122 panic("brelse: free buffer onto another queue???");
1123 if (BUF_REFCNT(bp) > 1) {
1124 /* Temporary panic to verify exclusive locking */
1125 /* This panic goes away when we allow shared refs */
1126 panic("brelse: multiple refs");
1127 /* do not release to free list */
1135 /* buffers with no memory */
1136 if (bp->b_bufsize == 0) {
1137 bp->b_flags |= B_INVAL;
1138 bp->b_xflags &= ~BX_BKGRDWRITE;
1139 if (bp->b_xflags & BX_BKGRDINPROG)
1140 panic("losing buffer 1");
1141 if (bp->b_kvasize) {
1142 bp->b_qindex = QUEUE_EMPTYKVA;
1144 bp->b_qindex = QUEUE_EMPTY;
1146 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1147 LIST_REMOVE(bp, b_hash);
1148 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1150 /* buffers with junk contents */
1151 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1152 bp->b_flags |= B_INVAL;
1153 bp->b_xflags &= ~BX_BKGRDWRITE;
1154 if (bp->b_xflags & BX_BKGRDINPROG)
1155 panic("losing buffer 2");
1156 bp->b_qindex = QUEUE_CLEAN;
1157 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1158 LIST_REMOVE(bp, b_hash);
1159 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1162 /* buffers that are locked */
1163 } else if (bp->b_flags & B_LOCKED) {
1164 bp->b_qindex = QUEUE_LOCKED;
1165 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1167 /* remaining buffers */
1169 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1170 case B_DELWRI | B_AGE:
1171 bp->b_qindex = QUEUE_DIRTY;
1172 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1175 bp->b_qindex = QUEUE_DIRTY;
1176 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1179 bp->b_qindex = QUEUE_CLEAN;
1180 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1183 bp->b_qindex = QUEUE_CLEAN;
1184 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1190 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1191 * on the correct queue.
1193 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1197 * Fixup numfreebuffers count. The bp is on an appropriate queue
1198 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1199 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1200 * if B_INVAL is set ).
1203 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1207 * Something we can maybe free or reuse
1209 if (bp->b_bufsize || bp->b_kvasize)
1214 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1215 B_DIRECT | B_NOWDRAIN);
1220 * Release a buffer back to the appropriate queue but do not try to free
1221 * it. The buffer is expected to be used again soon.
1223 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1224 * biodone() to requeue an async I/O on completion. It is also used when
1225 * known good buffers need to be requeued but we think we may need the data
1228 * XXX we should be able to leave the B_RELBUF hint set on completion.
1231 bqrelse(struct buf * bp)
1237 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1239 if (bp->b_qindex != QUEUE_NONE)
1240 panic("bqrelse: free buffer onto another queue???");
1241 if (BUF_REFCNT(bp) > 1) {
1242 /* do not release to free list */
1243 panic("bqrelse: multiple refs");
1248 if (bp->b_flags & B_LOCKED) {
1249 bp->b_flags &= ~B_ERROR;
1250 bp->b_qindex = QUEUE_LOCKED;
1251 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1252 /* buffers with stale but valid contents */
1253 } else if (bp->b_flags & B_DELWRI) {
1254 bp->b_qindex = QUEUE_DIRTY;
1255 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1256 } else if (vm_page_count_severe()) {
1258 * We are too low on memory, we have to try to free the
1259 * buffer (most importantly: the wired pages making up its
1260 * backing store) *now*.
1266 bp->b_qindex = QUEUE_CLEAN;
1267 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1270 if ((bp->b_flags & B_LOCKED) == 0 &&
1271 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1276 * Something we can maybe free or reuse.
1278 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1283 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1288 vfs_vmio_release(bp)
1295 for (i = 0; i < bp->b_npages; i++) {
1297 bp->b_pages[i] = NULL;
1299 * In order to keep page LRU ordering consistent, put
1300 * everything on the inactive queue.
1302 vm_page_unwire(m, 0);
1304 * We don't mess with busy pages, it is
1305 * the responsibility of the process that
1306 * busied the pages to deal with them.
1308 if ((m->flags & PG_BUSY) || (m->busy != 0))
1311 if (m->wire_count == 0) {
1312 vm_page_flag_clear(m, PG_ZERO);
1314 * Might as well free the page if we can and it has
1315 * no valid data. We also free the page if the
1316 * buffer was used for direct I/O.
1318 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1320 vm_page_protect(m, VM_PROT_NONE);
1322 } else if (bp->b_flags & B_DIRECT) {
1323 vm_page_try_to_free(m);
1324 } else if (vm_page_count_severe()) {
1325 vm_page_try_to_cache(m);
1330 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1331 if (bp->b_bufsize) {
1336 bp->b_flags &= ~B_VMIO;
1342 * Check to see if a block is currently memory resident.
1345 gbincore(struct vnode * vp, daddr_t blkno)
1348 struct bufhashhdr *bh;
1350 bh = bufhash(vp, blkno);
1352 /* Search hash chain */
1353 LIST_FOREACH(bp, bh, b_hash) {
1355 if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1356 (bp->b_flags & B_INVAL) == 0) {
1366 * Implement clustered async writes for clearing out B_DELWRI buffers.
1367 * This is much better then the old way of writing only one buffer at
1368 * a time. Note that we may not be presented with the buffers in the
1369 * correct order, so we search for the cluster in both directions.
1372 vfs_bio_awrite(struct buf * bp)
1376 daddr_t lblkno = bp->b_lblkno;
1377 struct vnode *vp = bp->b_vp;
1387 * right now we support clustered writing only to regular files. If
1388 * we find a clusterable block we could be in the middle of a cluster
1389 * rather then at the beginning.
1391 if ((vp->v_type == VREG) &&
1392 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1393 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1395 size = vp->v_mount->mnt_stat.f_iosize;
1396 maxcl = MAXPHYS / size;
1398 for (i = 1; i < maxcl; i++) {
1399 if ((bpa = gbincore(vp, lblkno + i)) &&
1400 BUF_REFCNT(bpa) == 0 &&
1401 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1402 (B_DELWRI | B_CLUSTEROK)) &&
1403 (bpa->b_bufsize == size)) {
1404 if ((bpa->b_blkno == bpa->b_lblkno) ||
1406 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1412 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1413 if ((bpa = gbincore(vp, lblkno - j)) &&
1414 BUF_REFCNT(bpa) == 0 &&
1415 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1416 (B_DELWRI | B_CLUSTEROK)) &&
1417 (bpa->b_bufsize == size)) {
1418 if ((bpa->b_blkno == bpa->b_lblkno) ||
1420 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1429 * this is a possible cluster write
1432 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1438 BUF_LOCK(bp, LK_EXCLUSIVE);
1440 bp->b_flags |= B_ASYNC;
1444 * default (old) behavior, writing out only one block
1446 * XXX returns b_bufsize instead of b_bcount for nwritten?
1448 nwritten = bp->b_bufsize;
1449 (void) VOP_BWRITE(bp->b_vp, bp);
1457 * Find and initialize a new buffer header, freeing up existing buffers
1458 * in the bufqueues as necessary. The new buffer is returned locked.
1460 * Important: B_INVAL is not set. If the caller wishes to throw the
1461 * buffer away, the caller must set B_INVAL prior to calling brelse().
1464 * We have insufficient buffer headers
1465 * We have insufficient buffer space
1466 * buffer_map is too fragmented ( space reservation fails )
1467 * If we have to flush dirty buffers ( but we try to avoid this )
1469 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1470 * Instead we ask the buf daemon to do it for us. We attempt to
1471 * avoid piecemeal wakeups of the pageout daemon.
1475 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1481 static int flushingbufs;
1484 * We can't afford to block since we might be holding a vnode lock,
1485 * which may prevent system daemons from running. We deal with
1486 * low-memory situations by proactively returning memory and running
1487 * async I/O rather then sync I/O.
1491 --getnewbufrestarts;
1493 ++getnewbufrestarts;
1496 * Setup for scan. If we do not have enough free buffers,
1497 * we setup a degenerate case that immediately fails. Note
1498 * that if we are specially marked process, we are allowed to
1499 * dip into our reserves.
1501 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1503 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1504 * However, there are a number of cases (defragging, reusing, ...)
1505 * where we cannot backup.
1507 nqindex = QUEUE_EMPTYKVA;
1508 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1512 * If no EMPTYKVA buffers and we are either
1513 * defragging or reusing, locate a CLEAN buffer
1514 * to free or reuse. If bufspace useage is low
1515 * skip this step so we can allocate a new buffer.
1517 if (defrag || bufspace >= lobufspace) {
1518 nqindex = QUEUE_CLEAN;
1519 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1523 * If we could not find or were not allowed to reuse a
1524 * CLEAN buffer, check to see if it is ok to use an EMPTY
1525 * buffer. We can only use an EMPTY buffer if allocating
1526 * its KVA would not otherwise run us out of buffer space.
1528 if (nbp == NULL && defrag == 0 &&
1529 bufspace + maxsize < hibufspace) {
1530 nqindex = QUEUE_EMPTY;
1531 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1536 * Run scan, possibly freeing data and/or kva mappings on the fly
1540 while ((bp = nbp) != NULL) {
1541 int qindex = nqindex;
1544 * Calculate next bp ( we can only use it if we do not block
1545 * or do other fancy things ).
1547 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1550 nqindex = QUEUE_EMPTYKVA;
1551 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1554 case QUEUE_EMPTYKVA:
1555 nqindex = QUEUE_CLEAN;
1556 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1570 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1573 * Note: we no longer distinguish between VMIO and non-VMIO
1577 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1580 * If we are defragging then we need a buffer with
1581 * b_kvasize != 0. XXX this situation should no longer
1582 * occur, if defrag is non-zero the buffer's b_kvasize
1583 * should also be non-zero at this point. XXX
1585 if (defrag && bp->b_kvasize == 0) {
1586 printf("Warning: defrag empty buffer %p\n", bp);
1591 * Start freeing the bp. This is somewhat involved. nbp
1592 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1595 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1596 panic("getnewbuf: locked buf");
1599 if (qindex == QUEUE_CLEAN) {
1600 if (bp->b_flags & B_VMIO) {
1601 bp->b_flags &= ~B_ASYNC;
1602 vfs_vmio_release(bp);
1609 * NOTE: nbp is now entirely invalid. We can only restart
1610 * the scan from this point on.
1612 * Get the rest of the buffer freed up. b_kva* is still
1613 * valid after this operation.
1616 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1617 (*bioops.io_deallocate)(bp);
1618 if (bp->b_xflags & BX_BKGRDINPROG)
1619 panic("losing buffer 3");
1620 LIST_REMOVE(bp, b_hash);
1621 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1630 bp->b_blkno = bp->b_lblkno = 0;
1631 bp->b_offset = NOOFFSET;
1637 bp->b_dirtyoff = bp->b_dirtyend = 0;
1639 LIST_INIT(&bp->b_dep);
1642 * If we are defragging then free the buffer.
1645 bp->b_flags |= B_INVAL;
1653 * If we are overcomitted then recover the buffer and its
1654 * KVM space. This occurs in rare situations when multiple
1655 * processes are blocked in getnewbuf() or allocbuf().
1657 if (bufspace >= hibufspace)
1659 if (flushingbufs && bp->b_kvasize != 0) {
1660 bp->b_flags |= B_INVAL;
1665 if (bufspace < lobufspace)
1671 * If we exhausted our list, sleep as appropriate. We may have to
1672 * wakeup various daemons and write out some dirty buffers.
1674 * Generally we are sleeping due to insufficient buffer space.
1682 flags = VFS_BIO_NEED_BUFSPACE;
1684 } else if (bufspace >= hibufspace) {
1686 flags = VFS_BIO_NEED_BUFSPACE;
1689 flags = VFS_BIO_NEED_ANY;
1692 bd_speedup(); /* heeeelp */
1694 needsbuffer |= flags;
1695 while (needsbuffer & flags) {
1696 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
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, 0, "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, 0, "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, slpflag, "newbuf", slptimeo);
2084 if ((bp = gbincore(vp, blkno))) {
2086 * Buffer is in-core. If the buffer is not busy, it must
2090 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2091 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2092 "getblk", slpflag, slptimeo) == ENOLCK)
2095 return (struct buf *) NULL;
2099 * The buffer is locked. B_CACHE is cleared if the buffer is
2100 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2101 * and for a VMIO buffer B_CACHE is adjusted according to the
2104 if (bp->b_flags & B_INVAL)
2105 bp->b_flags &= ~B_CACHE;
2106 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2107 bp->b_flags |= B_CACHE;
2111 * check for size inconsistancies for non-VMIO case.
2114 if (bp->b_bcount != size) {
2115 if ((bp->b_flags & B_VMIO) == 0 ||
2116 (size > bp->b_kvasize)) {
2117 if (bp->b_flags & B_DELWRI) {
2118 bp->b_flags |= B_NOCACHE;
2119 VOP_BWRITE(bp->b_vp, bp);
2121 if ((bp->b_flags & B_VMIO) &&
2122 (LIST_FIRST(&bp->b_dep) == NULL)) {
2123 bp->b_flags |= B_RELBUF;
2126 bp->b_flags |= B_NOCACHE;
2127 VOP_BWRITE(bp->b_vp, bp);
2135 * If the size is inconsistant in the VMIO case, we can resize
2136 * the buffer. This might lead to B_CACHE getting set or
2137 * cleared. If the size has not changed, B_CACHE remains
2138 * unchanged from its previous state.
2141 if (bp->b_bcount != size)
2144 KASSERT(bp->b_offset != NOOFFSET,
2145 ("getblk: no buffer offset"));
2148 * A buffer with B_DELWRI set and B_CACHE clear must
2149 * be committed before we can return the buffer in
2150 * order to prevent the caller from issuing a read
2151 * ( due to B_CACHE not being set ) and overwriting
2154 * Most callers, including NFS and FFS, need this to
2155 * operate properly either because they assume they
2156 * can issue a read if B_CACHE is not set, or because
2157 * ( for example ) an uncached B_DELWRI might loop due
2158 * to softupdates re-dirtying the buffer. In the latter
2159 * case, B_CACHE is set after the first write completes,
2160 * preventing further loops.
2162 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2163 * above while extending the buffer, we cannot allow the
2164 * buffer to remain with B_CACHE set after the write
2165 * completes or it will represent a corrupt state. To
2166 * deal with this we set B_NOCACHE to scrap the buffer
2169 * We might be able to do something fancy, like setting
2170 * B_CACHE in bwrite() except if B_DELWRI is already set,
2171 * so the below call doesn't set B_CACHE, but that gets real
2172 * confusing. This is much easier.
2175 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2176 bp->b_flags |= B_NOCACHE;
2177 VOP_BWRITE(bp->b_vp, bp);
2182 bp->b_flags &= ~B_DONE;
2185 * Buffer is not in-core, create new buffer. The buffer
2186 * returned by getnewbuf() is locked. Note that the returned
2187 * buffer is also considered valid (not marked B_INVAL).
2189 int bsize, maxsize, vmio;
2192 if (vn_isdisk(vp, NULL))
2194 else if (vp->v_mountedhere)
2195 bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2196 else if (vp->v_mount)
2197 bsize = vp->v_mount->mnt_stat.f_iosize;
2201 offset = (off_t)blkno * bsize;
2202 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2203 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2204 maxsize = imax(maxsize, bsize);
2206 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2207 if (slpflag || slptimeo) {
2215 * This code is used to make sure that a buffer is not
2216 * created while the getnewbuf routine is blocked.
2217 * This can be a problem whether the vnode is locked or not.
2218 * If the buffer is created out from under us, we have to
2219 * throw away the one we just created. There is now window
2220 * race because we are safely running at splbio() from the
2221 * point of the duplicate buffer creation through to here,
2222 * and we've locked the buffer.
2224 if (gbincore(vp, blkno)) {
2225 bp->b_flags |= B_INVAL;
2231 * Insert the buffer into the hash, so that it can
2232 * be found by incore.
2234 bp->b_blkno = bp->b_lblkno = blkno;
2235 bp->b_offset = offset;
2238 LIST_REMOVE(bp, b_hash);
2239 bh = bufhash(vp, blkno);
2240 LIST_INSERT_HEAD(bh, bp, b_hash);
2243 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2244 * buffer size starts out as 0, B_CACHE will be set by
2245 * allocbuf() for the VMIO case prior to it testing the
2246 * backing store for validity.
2250 bp->b_flags |= B_VMIO;
2251 #if defined(VFS_BIO_DEBUG)
2252 if (vp->v_type != VREG && vp->v_type != VBLK)
2253 printf("getblk: vmioing file type %d???\n", vp->v_type);
2256 bp->b_flags &= ~B_VMIO;
2262 bp->b_flags &= ~B_DONE;
2268 * Get an empty, disassociated buffer of given size. The buffer is initially
2278 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2281 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2284 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2290 * This code constitutes the buffer memory from either anonymous system
2291 * memory (in the case of non-VMIO operations) or from an associated
2292 * VM object (in the case of VMIO operations). This code is able to
2293 * resize a buffer up or down.
2295 * Note that this code is tricky, and has many complications to resolve
2296 * deadlock or inconsistant data situations. Tread lightly!!!
2297 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2298 * the caller. Calling this code willy nilly can result in the loss of data.
2300 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2301 * B_CACHE for the non-VMIO case.
2305 allocbuf(struct buf *bp, int size)
2307 int newbsize, mbsize;
2310 if (BUF_REFCNT(bp) == 0)
2311 panic("allocbuf: buffer not busy");
2313 if (bp->b_kvasize < size)
2314 panic("allocbuf: buffer too small");
2316 if ((bp->b_flags & B_VMIO) == 0) {
2320 * Just get anonymous memory from the kernel. Don't
2321 * mess with B_CACHE.
2323 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2324 #if !defined(NO_B_MALLOC)
2325 if (bp->b_flags & B_MALLOC)
2329 newbsize = round_page(size);
2331 if (newbsize < bp->b_bufsize) {
2332 #if !defined(NO_B_MALLOC)
2334 * malloced buffers are not shrunk
2336 if (bp->b_flags & B_MALLOC) {
2338 bp->b_bcount = size;
2340 free(bp->b_data, M_BIOBUF);
2341 if (bp->b_bufsize) {
2342 bufmallocspace -= bp->b_bufsize;
2346 bp->b_data = bp->b_kvabase;
2348 bp->b_flags &= ~B_MALLOC;
2355 (vm_offset_t) bp->b_data + newbsize,
2356 (vm_offset_t) bp->b_data + bp->b_bufsize);
2357 } else if (newbsize > bp->b_bufsize) {
2358 #if !defined(NO_B_MALLOC)
2360 * We only use malloced memory on the first allocation.
2361 * and revert to page-allocated memory when the buffer
2364 if ( (bufmallocspace < maxbufmallocspace) &&
2365 (bp->b_bufsize == 0) &&
2366 (mbsize <= PAGE_SIZE/2)) {
2368 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2369 bp->b_bufsize = mbsize;
2370 bp->b_bcount = size;
2371 bp->b_flags |= B_MALLOC;
2372 bufmallocspace += mbsize;
2378 #if !defined(NO_B_MALLOC)
2380 * If the buffer is growing on its other-than-first allocation,
2381 * then we revert to the page-allocation scheme.
2383 if (bp->b_flags & B_MALLOC) {
2384 origbuf = bp->b_data;
2385 origbufsize = bp->b_bufsize;
2386 bp->b_data = bp->b_kvabase;
2387 if (bp->b_bufsize) {
2388 bufmallocspace -= bp->b_bufsize;
2392 bp->b_flags &= ~B_MALLOC;
2393 newbsize = round_page(newbsize);
2398 (vm_offset_t) bp->b_data + bp->b_bufsize,
2399 (vm_offset_t) bp->b_data + newbsize);
2400 #if !defined(NO_B_MALLOC)
2402 bcopy(origbuf, bp->b_data, origbufsize);
2403 free(origbuf, M_BIOBUF);
2411 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2412 desiredpages = (size == 0) ? 0 :
2413 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2415 #if !defined(NO_B_MALLOC)
2416 if (bp->b_flags & B_MALLOC)
2417 panic("allocbuf: VMIO buffer can't be malloced");
2420 * Set B_CACHE initially if buffer is 0 length or will become
2423 if (size == 0 || bp->b_bufsize == 0)
2424 bp->b_flags |= B_CACHE;
2426 if (newbsize < bp->b_bufsize) {
2428 * DEV_BSIZE aligned new buffer size is less then the
2429 * DEV_BSIZE aligned existing buffer size. Figure out
2430 * if we have to remove any pages.
2432 if (desiredpages < bp->b_npages) {
2433 for (i = desiredpages; i < bp->b_npages; i++) {
2435 * the page is not freed here -- it
2436 * is the responsibility of
2437 * vnode_pager_setsize
2440 KASSERT(m != bogus_page,
2441 ("allocbuf: bogus page found"));
2442 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2445 bp->b_pages[i] = NULL;
2446 vm_page_unwire(m, 0);
2448 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2449 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2450 bp->b_npages = desiredpages;
2452 } else if (size > bp->b_bcount) {
2454 * We are growing the buffer, possibly in a
2455 * byte-granular fashion.
2463 * Step 1, bring in the VM pages from the object,
2464 * allocating them if necessary. We must clear
2465 * B_CACHE if these pages are not valid for the
2466 * range covered by the buffer.
2470 VOP_GETVOBJECT(vp, &obj);
2472 while (bp->b_npages < desiredpages) {
2476 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2477 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2479 * note: must allocate system pages
2480 * since blocking here could intefere
2481 * with paging I/O, no matter which
2484 m = vm_page_alloc(obj, pi, VM_ALLOC_SYSTEM);
2487 vm_pageout_deficit += desiredpages - bp->b_npages;
2491 bp->b_flags &= ~B_CACHE;
2492 bp->b_pages[bp->b_npages] = m;
2499 * We found a page. If we have to sleep on it,
2500 * retry because it might have gotten freed out
2503 * We can only test PG_BUSY here. Blocking on
2504 * m->busy might lead to a deadlock:
2506 * vm_fault->getpages->cluster_read->allocbuf
2510 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2514 * We have a good page. Should we wakeup the
2517 if ((curthread != pagethread) &&
2518 ((m->queue - m->pc) == PQ_CACHE) &&
2519 ((vmstats.v_free_count + vmstats.v_cache_count) <
2520 (vmstats.v_free_min + vmstats.v_cache_min))) {
2521 pagedaemon_wakeup();
2523 vm_page_flag_clear(m, PG_ZERO);
2525 bp->b_pages[bp->b_npages] = m;
2530 * Step 2. We've loaded the pages into the buffer,
2531 * we have to figure out if we can still have B_CACHE
2532 * set. Note that B_CACHE is set according to the
2533 * byte-granular range ( bcount and size ), new the
2534 * aligned range ( newbsize ).
2536 * The VM test is against m->valid, which is DEV_BSIZE
2537 * aligned. Needless to say, the validity of the data
2538 * needs to also be DEV_BSIZE aligned. Note that this
2539 * fails with NFS if the server or some other client
2540 * extends the file's EOF. If our buffer is resized,
2541 * B_CACHE may remain set! XXX
2544 toff = bp->b_bcount;
2545 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2547 while ((bp->b_flags & B_CACHE) && toff < size) {
2550 if (tinc > (size - toff))
2553 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2568 * Step 3, fixup the KVM pmap. Remember that
2569 * bp->b_data is relative to bp->b_offset, but
2570 * bp->b_offset may be offset into the first page.
2573 bp->b_data = (caddr_t)
2574 trunc_page((vm_offset_t)bp->b_data);
2576 (vm_offset_t)bp->b_data,
2580 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2581 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2584 if (newbsize < bp->b_bufsize)
2586 bp->b_bufsize = newbsize; /* actual buffer allocation */
2587 bp->b_bcount = size; /* requested buffer size */
2594 * Wait for buffer I/O completion, returning error status. The buffer
2595 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2596 * error and cleared.
2599 biowait(struct buf * bp)
2604 while ((bp->b_flags & B_DONE) == 0) {
2605 #if defined(NO_SCHEDULE_MODS)
2606 tsleep(bp, 0, "biowait", 0);
2608 if (bp->b_flags & B_READ)
2609 tsleep(bp, 0, "biord", 0);
2611 tsleep(bp, 0, "biowr", 0);
2615 if (bp->b_flags & B_EINTR) {
2616 bp->b_flags &= ~B_EINTR;
2619 if (bp->b_flags & B_ERROR) {
2620 return (bp->b_error ? bp->b_error : EIO);
2629 * Finish I/O on a buffer, optionally calling a completion function.
2630 * This is usually called from an interrupt so process blocking is
2633 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2634 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2635 * assuming B_INVAL is clear.
2637 * For the VMIO case, we set B_CACHE if the op was a read and no
2638 * read error occured, or if the op was a write. B_CACHE is never
2639 * set if the buffer is invalid or otherwise uncacheable.
2641 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2642 * initiator to leave B_INVAL set to brelse the buffer out of existance
2643 * in the biodone routine.
2646 biodone(struct buf * bp)
2652 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2653 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2655 bp->b_flags |= B_DONE;
2656 runningbufwakeup(bp);
2658 if (bp->b_flags & B_FREEBUF) {
2664 if ((bp->b_flags & B_READ) == 0) {
2668 /* call optional completion function if requested */
2669 if (bp->b_flags & B_CALL) {
2670 bp->b_flags &= ~B_CALL;
2671 (*bp->b_iodone) (bp);
2675 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2676 (*bioops.io_complete)(bp);
2678 if (bp->b_flags & B_VMIO) {
2684 struct vnode *vp = bp->b_vp;
2686 error = VOP_GETVOBJECT(vp, &obj);
2688 #if defined(VFS_BIO_DEBUG)
2689 if (vp->v_usecount == 0) {
2690 panic("biodone: zero vnode ref count");
2694 panic("biodone: missing VM object");
2697 if ((vp->v_flag & VOBJBUF) == 0) {
2698 panic("biodone: vnode is not setup for merged cache");
2702 foff = bp->b_offset;
2703 KASSERT(bp->b_offset != NOOFFSET,
2704 ("biodone: no buffer offset"));
2707 panic("biodone: no object");
2709 #if defined(VFS_BIO_DEBUG)
2710 if (obj->paging_in_progress < bp->b_npages) {
2711 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2712 obj->paging_in_progress, bp->b_npages);
2717 * Set B_CACHE if the op was a normal read and no error
2718 * occured. B_CACHE is set for writes in the b*write()
2721 iosize = bp->b_bcount - bp->b_resid;
2722 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2723 bp->b_flags |= B_CACHE;
2726 for (i = 0; i < bp->b_npages; i++) {
2730 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2735 * cleanup bogus pages, restoring the originals
2738 if (m == bogus_page) {
2740 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2742 panic("biodone: page disappeared");
2744 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2746 #if defined(VFS_BIO_DEBUG)
2747 if (OFF_TO_IDX(foff) != m->pindex) {
2749 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2750 (unsigned long)foff, m->pindex);
2755 * In the write case, the valid and clean bits are
2756 * already changed correctly ( see bdwrite() ), so we
2757 * only need to do this here in the read case.
2759 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2760 vfs_page_set_valid(bp, foff, i, m);
2762 vm_page_flag_clear(m, PG_ZERO);
2765 * when debugging new filesystems or buffer I/O methods, this
2766 * is the most common error that pops up. if you see this, you
2767 * have not set the page busy flag correctly!!!
2770 printf("biodone: page busy < 0, "
2771 "pindex: %d, foff: 0x(%x,%x), "
2772 "resid: %d, index: %d\n",
2773 (int) m->pindex, (int)(foff >> 32),
2774 (int) foff & 0xffffffff, resid, i);
2775 if (!vn_isdisk(vp, NULL))
2776 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2777 bp->b_vp->v_mount->mnt_stat.f_iosize,
2779 bp->b_flags, bp->b_npages);
2781 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2783 bp->b_flags, bp->b_npages);
2784 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2785 m->valid, m->dirty, m->wire_count);
2786 panic("biodone: page busy < 0\n");
2788 vm_page_io_finish(m);
2789 vm_object_pip_subtract(obj, 1);
2790 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2794 vm_object_pip_wakeupn(obj, 0);
2798 * For asynchronous completions, release the buffer now. The brelse
2799 * will do a wakeup there if necessary - so no need to do a wakeup
2800 * here in the async case. The sync case always needs to do a wakeup.
2803 if (bp->b_flags & B_ASYNC) {
2804 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2815 * This routine is called in lieu of iodone in the case of
2816 * incomplete I/O. This keeps the busy status for pages
2820 vfs_unbusy_pages(struct buf * bp)
2824 runningbufwakeup(bp);
2825 if (bp->b_flags & B_VMIO) {
2826 struct vnode *vp = bp->b_vp;
2829 VOP_GETVOBJECT(vp, &obj);
2831 for (i = 0; i < bp->b_npages; i++) {
2832 vm_page_t m = bp->b_pages[i];
2834 if (m == bogus_page) {
2835 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2837 panic("vfs_unbusy_pages: page missing\n");
2840 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2842 vm_object_pip_subtract(obj, 1);
2843 vm_page_flag_clear(m, PG_ZERO);
2844 vm_page_io_finish(m);
2846 vm_object_pip_wakeupn(obj, 0);
2851 * vfs_page_set_valid:
2853 * Set the valid bits in a page based on the supplied offset. The
2854 * range is restricted to the buffer's size.
2856 * This routine is typically called after a read completes.
2859 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2861 vm_ooffset_t soff, eoff;
2864 * Start and end offsets in buffer. eoff - soff may not cross a
2865 * page boundry or cross the end of the buffer. The end of the
2866 * buffer, in this case, is our file EOF, not the allocation size
2870 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2871 if (eoff > bp->b_offset + bp->b_bcount)
2872 eoff = bp->b_offset + bp->b_bcount;
2875 * Set valid range. This is typically the entire buffer and thus the
2879 vm_page_set_validclean(
2881 (vm_offset_t) (soff & PAGE_MASK),
2882 (vm_offset_t) (eoff - soff)
2888 * This routine is called before a device strategy routine.
2889 * It is used to tell the VM system that paging I/O is in
2890 * progress, and treat the pages associated with the buffer
2891 * almost as being PG_BUSY. Also the object paging_in_progress
2892 * flag is handled to make sure that the object doesn't become
2895 * Since I/O has not been initiated yet, certain buffer flags
2896 * such as B_ERROR or B_INVAL may be in an inconsistant state
2897 * and should be ignored.
2900 vfs_busy_pages(struct buf * bp, int clear_modify)
2904 if (bp->b_flags & B_VMIO) {
2905 struct vnode *vp = bp->b_vp;
2909 VOP_GETVOBJECT(vp, &obj);
2910 foff = bp->b_offset;
2911 KASSERT(bp->b_offset != NOOFFSET,
2912 ("vfs_busy_pages: no buffer offset"));
2916 for (i = 0; i < bp->b_npages; i++) {
2917 vm_page_t m = bp->b_pages[i];
2918 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
2923 for (i = 0; i < bp->b_npages; i++) {
2924 vm_page_t m = bp->b_pages[i];
2926 vm_page_flag_clear(m, PG_ZERO);
2927 if ((bp->b_flags & B_CLUSTER) == 0) {
2928 vm_object_pip_add(obj, 1);
2929 vm_page_io_start(m);
2933 * When readying a buffer for a read ( i.e
2934 * clear_modify == 0 ), it is important to do
2935 * bogus_page replacement for valid pages in
2936 * partially instantiated buffers. Partially
2937 * instantiated buffers can, in turn, occur when
2938 * reconstituting a buffer from its VM backing store
2939 * base. We only have to do this if B_CACHE is
2940 * clear ( which causes the I/O to occur in the
2941 * first place ). The replacement prevents the read
2942 * I/O from overwriting potentially dirty VM-backed
2943 * pages. XXX bogus page replacement is, uh, bogus.
2944 * It may not work properly with small-block devices.
2945 * We need to find a better way.
2948 vm_page_protect(m, VM_PROT_NONE);
2950 vfs_page_set_valid(bp, foff, i, m);
2951 else if (m->valid == VM_PAGE_BITS_ALL &&
2952 (bp->b_flags & B_CACHE) == 0) {
2953 bp->b_pages[i] = bogus_page;
2956 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2959 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2963 * This is the easiest place to put the process accounting for the I/O
2969 if ((p = curthread->td_proc) != NULL) {
2970 if (bp->b_flags & B_READ)
2971 p->p_stats->p_ru.ru_inblock++;
2973 p->p_stats->p_ru.ru_oublock++;
2979 * Tell the VM system that the pages associated with this buffer
2980 * are clean. This is used for delayed writes where the data is
2981 * going to go to disk eventually without additional VM intevention.
2983 * Note that while we only really need to clean through to b_bcount, we
2984 * just go ahead and clean through to b_bufsize.
2987 vfs_clean_pages(struct buf * bp)
2991 if (bp->b_flags & B_VMIO) {
2994 foff = bp->b_offset;
2995 KASSERT(bp->b_offset != NOOFFSET,
2996 ("vfs_clean_pages: no buffer offset"));
2997 for (i = 0; i < bp->b_npages; i++) {
2998 vm_page_t m = bp->b_pages[i];
2999 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3000 vm_ooffset_t eoff = noff;
3002 if (eoff > bp->b_offset + bp->b_bufsize)
3003 eoff = bp->b_offset + bp->b_bufsize;
3004 vfs_page_set_valid(bp, foff, i, m);
3005 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3012 * vfs_bio_set_validclean:
3014 * Set the range within the buffer to valid and clean. The range is
3015 * relative to the beginning of the buffer, b_offset. Note that b_offset
3016 * itself may be offset from the beginning of the first page.
3020 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3022 if (bp->b_flags & B_VMIO) {
3027 * Fixup base to be relative to beginning of first page.
3028 * Set initial n to be the maximum number of bytes in the
3029 * first page that can be validated.
3032 base += (bp->b_offset & PAGE_MASK);
3033 n = PAGE_SIZE - (base & PAGE_MASK);
3035 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3036 vm_page_t m = bp->b_pages[i];
3041 vm_page_set_validclean(m, base & PAGE_MASK, n);
3052 * clear a buffer. This routine essentially fakes an I/O, so we need
3053 * to clear B_ERROR and B_INVAL.
3055 * Note that while we only theoretically need to clear through b_bcount,
3056 * we go ahead and clear through b_bufsize.
3060 vfs_bio_clrbuf(struct buf *bp)
3064 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3065 bp->b_flags &= ~(B_INVAL|B_ERROR);
3066 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3067 (bp->b_offset & PAGE_MASK) == 0) {
3068 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3069 if ((bp->b_pages[0]->valid & mask) == mask) {
3073 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3074 ((bp->b_pages[0]->valid & mask) == 0)) {
3075 bzero(bp->b_data, bp->b_bufsize);
3076 bp->b_pages[0]->valid |= mask;
3081 ea = sa = bp->b_data;
3082 for(i=0;i<bp->b_npages;i++,sa=ea) {
3083 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3084 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3085 ea = (caddr_t)(vm_offset_t)ulmin(
3086 (u_long)(vm_offset_t)ea,
3087 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3088 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3089 if ((bp->b_pages[i]->valid & mask) == mask)
3091 if ((bp->b_pages[i]->valid & mask) == 0) {
3092 if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3096 for (; sa < ea; sa += DEV_BSIZE, j++) {
3097 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3098 (bp->b_pages[i]->valid & (1<<j)) == 0)
3099 bzero(sa, DEV_BSIZE);
3102 bp->b_pages[i]->valid |= mask;
3103 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3112 * vm_hold_load_pages and vm_hold_unload pages get pages into
3113 * a buffers address space. The pages are anonymous and are
3114 * not associated with a file object.
3117 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3123 to = round_page(to);
3124 from = round_page(from);
3125 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3127 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3132 * note: must allocate system pages since blocking here
3133 * could intefere with paging I/O, no matter which
3136 p = vm_page_alloc(kernel_object,
3137 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3140 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3145 p->valid = VM_PAGE_BITS_ALL;
3146 vm_page_flag_clear(p, PG_ZERO);
3147 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3148 bp->b_pages[index] = p;
3151 bp->b_npages = index;
3155 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3159 int index, newnpages;
3161 from = round_page(from);
3162 to = round_page(to);
3163 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3165 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3166 p = bp->b_pages[index];
3167 if (p && (index < bp->b_npages)) {
3169 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3170 bp->b_blkno, bp->b_lblkno);
3172 bp->b_pages[index] = NULL;
3175 vm_page_unwire(p, 0);
3179 bp->b_npages = newnpages;
3183 * Map an IO request into kernel virtual address space.
3185 * All requests are (re)mapped into kernel VA space.
3186 * Notice that we use b_bufsize for the size of the buffer
3187 * to be mapped. b_bcount might be modified by the driver.
3190 vmapbuf(struct buf *bp)
3192 caddr_t addr, v, kva;
3198 if ((bp->b_flags & B_PHYS) == 0)
3200 if (bp->b_bufsize < 0)
3202 for (v = bp->b_saveaddr,
3203 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3205 addr < bp->b_data + bp->b_bufsize;
3206 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3208 * Do the vm_fault if needed; do the copy-on-write thing
3209 * when reading stuff off device into memory.
3212 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3213 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3215 for (i = 0; i < pidx; ++i) {
3216 vm_page_unhold(bp->b_pages[i]);
3217 bp->b_pages[i] = NULL;
3223 * WARNING! If sparc support is MFCd in the future this will
3224 * have to be changed from pmap_kextract() to pmap_extract()
3228 #error "If MFCing sparc support use pmap_extract"
3230 pa = pmap_kextract((vm_offset_t)addr);
3232 printf("vmapbuf: warning, race against user address during I/O");
3235 m = PHYS_TO_VM_PAGE(pa);
3237 bp->b_pages[pidx] = m;
3239 if (pidx > btoc(MAXPHYS))
3240 panic("vmapbuf: mapped more than MAXPHYS");
3241 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3243 kva = bp->b_saveaddr;
3244 bp->b_npages = pidx;
3245 bp->b_saveaddr = bp->b_data;
3246 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3251 * Free the io map PTEs associated with this IO operation.
3252 * We also invalidate the TLB entries and restore the original b_addr.
3262 if ((bp->b_flags & B_PHYS) == 0)
3265 npages = bp->b_npages;
3266 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3269 for (pidx = 0; pidx < npages; pidx++)
3270 vm_page_unhold(*m++);
3272 bp->b_data = bp->b_saveaddr;
3275 #include "opt_ddb.h"
3277 #include <ddb/ddb.h>
3279 DB_SHOW_COMMAND(buffer, db_show_buffer)
3282 struct buf *bp = (struct buf *)addr;
3285 db_printf("usage: show buffer <addr>\n");
3289 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3290 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3291 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3292 "b_blkno = %d, b_pblkno = %d\n",
3293 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3294 major(bp->b_dev), minor(bp->b_dev),
3295 bp->b_data, bp->b_blkno, bp->b_pblkno);
3298 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3299 for (i = 0; i < bp->b_npages; i++) {
3302 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3303 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3304 if ((i + 1) < bp->b_npages)