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.17 2004/01/20 05:04:06 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>
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 (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, "");
147 * Disable background writes for now. There appear to be races in the
148 * flags tests and locking operations as well as races in the completion
149 * code modifying the original bp (origbp) without holding a lock, assuming
150 * splbio protection when there might not be splbio protection.
152 static int dobkgrdwrite = 0;
153 SYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
154 "Do background writes (honoring the BV_BKGRDWRITE flag)?");
156 static int bufhashmask;
157 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
158 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
159 char *buf_wmesg = BUF_WMESG;
161 extern int vm_swap_size;
163 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
164 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
165 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
166 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
169 * Buffer hash table code. Note that the logical block scans linearly, which
170 * gives us some L1 cache locality.
175 bufhash(struct vnode *vnp, daddr_t bn)
177 return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
183 * If someone is blocked due to there being too many dirty buffers,
184 * and numdirtybuffers is now reasonable, wake them up.
188 numdirtywakeup(int level)
190 if (numdirtybuffers <= level) {
191 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
192 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
193 wakeup(&needsbuffer);
201 * Called when buffer space is potentially available for recovery.
202 * getnewbuf() will block on this flag when it is unable to free
203 * sufficient buffer space. Buffer space becomes recoverable when
204 * bp's get placed back in the queues.
211 * If someone is waiting for BUF space, wake them up. Even
212 * though we haven't freed the kva space yet, the waiting
213 * process will be able to now.
215 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
216 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
217 wakeup(&needsbuffer);
222 * runningbufwakeup() - in-progress I/O accounting.
226 runningbufwakeup(struct buf *bp)
228 if (bp->b_runningbufspace) {
229 runningbufspace -= bp->b_runningbufspace;
230 bp->b_runningbufspace = 0;
231 if (runningbufreq && runningbufspace <= lorunningspace) {
233 wakeup(&runningbufreq);
241 * Called when a buffer has been added to one of the free queues to
242 * account for the buffer and to wakeup anyone waiting for free buffers.
243 * This typically occurs when large amounts of metadata are being handled
244 * by the buffer cache ( else buffer space runs out first, usually ).
252 needsbuffer &= ~VFS_BIO_NEED_ANY;
253 if (numfreebuffers >= hifreebuffers)
254 needsbuffer &= ~VFS_BIO_NEED_FREE;
255 wakeup(&needsbuffer);
260 * waitrunningbufspace()
262 * runningbufspace is a measure of the amount of I/O currently
263 * running. This routine is used in async-write situations to
264 * prevent creating huge backups of pending writes to a device.
265 * Only asynchronous writes are governed by this function.
267 * Reads will adjust runningbufspace, but will not block based on it.
268 * The read load has a side effect of reducing the allowed write load.
270 * This does NOT turn an async write into a sync write. It waits
271 * for earlier writes to complete and generally returns before the
272 * caller's write has reached the device.
275 waitrunningbufspace(void)
277 while (runningbufspace > hirunningspace) {
280 s = splbio(); /* fix race against interrupt/biodone() */
282 tsleep(&runningbufreq, 0, "wdrain", 0);
288 * vfs_buf_test_cache:
290 * Called when a buffer is extended. This function clears the B_CACHE
291 * bit if the newly extended portion of the buffer does not contain
296 vfs_buf_test_cache(struct buf *bp,
297 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
300 if (bp->b_flags & B_CACHE) {
301 int base = (foff + off) & PAGE_MASK;
302 if (vm_page_is_valid(m, base, size) == 0)
303 bp->b_flags &= ~B_CACHE;
309 bd_wakeup(int dirtybuflevel)
311 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
318 * bd_speedup - speedup the buffer cache flushing code
329 * Initialize buffer headers and related structures.
333 bufhashinit(caddr_t vaddr)
335 /* first, make a null hash table */
336 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
338 bufhashtbl = (void *)vaddr;
339 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
350 TAILQ_INIT(&bswlist);
351 LIST_INIT(&invalhash);
352 lwkt_inittoken(&buftimetoken);
354 for (i = 0; i <= bufhashmask; i++)
355 LIST_INIT(&bufhashtbl[i]);
357 /* next, make a null set of free lists */
358 for (i = 0; i < BUFFER_QUEUES; i++)
359 TAILQ_INIT(&bufqueues[i]);
361 /* finally, initialize each buffer header and stick on empty q */
362 for (i = 0; i < nbuf; i++) {
364 bzero(bp, sizeof *bp);
365 bp->b_flags = B_INVAL; /* we're just an empty header */
367 bp->b_qindex = QUEUE_EMPTY;
369 LIST_INIT(&bp->b_dep);
371 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
372 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
376 * maxbufspace is the absolute maximum amount of buffer space we are
377 * allowed to reserve in KVM and in real terms. The absolute maximum
378 * is nominally used by buf_daemon. hibufspace is the nominal maximum
379 * used by most other processes. The differential is required to
380 * ensure that buf_daemon is able to run when other processes might
381 * be blocked waiting for buffer space.
383 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
384 * this may result in KVM fragmentation which is not handled optimally
387 maxbufspace = nbuf * BKVASIZE;
388 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
389 lobufspace = hibufspace - MAXBSIZE;
391 lorunningspace = 512 * 1024;
392 hirunningspace = 1024 * 1024;
395 * Limit the amount of malloc memory since it is wired permanently into
396 * the kernel space. Even though this is accounted for in the buffer
397 * allocation, we don't want the malloced region to grow uncontrolled.
398 * The malloc scheme improves memory utilization significantly on average
399 * (small) directories.
401 maxbufmallocspace = hibufspace / 20;
404 * Reduce the chance of a deadlock occuring by limiting the number
405 * of delayed-write dirty buffers we allow to stack up.
407 hidirtybuffers = nbuf / 4 + 20;
410 * To support extreme low-memory systems, make sure hidirtybuffers cannot
411 * eat up all available buffer space. This occurs when our minimum cannot
412 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
413 * BKVASIZE'd (8K) buffers.
415 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
416 hidirtybuffers >>= 1;
418 lodirtybuffers = hidirtybuffers / 2;
421 * Try to keep the number of free buffers in the specified range,
422 * and give special processes (e.g. like buf_daemon) access to an
425 lofreebuffers = nbuf / 18 + 5;
426 hifreebuffers = 2 * lofreebuffers;
427 numfreebuffers = nbuf;
430 * Maximum number of async ops initiated per buf_daemon loop. This is
431 * somewhat of a hack at the moment, we really need to limit ourselves
432 * based on the number of bytes of I/O in-transit that were initiated
436 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
437 bogus_page = vm_page_alloc(kernel_object,
438 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
440 vmstats.v_wire_count++;
445 * bfreekva() - free the kva allocation for a buffer.
447 * Must be called at splbio() or higher as this is the only locking for
450 * Since this call frees up buffer space, we call bufspacewakeup().
453 bfreekva(struct buf * bp)
459 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
460 vm_map_lock(buffer_map);
461 bufspace -= bp->b_kvasize;
462 vm_map_delete(buffer_map,
463 (vm_offset_t) bp->b_kvabase,
464 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
467 vm_map_unlock(buffer_map);
468 vm_map_entry_release(count);
477 * Remove the buffer from the appropriate free list.
480 bremfree(struct buf * bp)
483 int old_qindex = bp->b_qindex;
485 if (bp->b_qindex != QUEUE_NONE) {
486 KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
487 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
488 bp->b_qindex = QUEUE_NONE;
490 if (BUF_REFCNT(bp) <= 1)
491 panic("bremfree: removing a buffer not on a queue");
495 * Fixup numfreebuffers count. If the buffer is invalid or not
496 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
497 * the buffer was free and we must decrement numfreebuffers.
499 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
516 * Get a buffer with the specified data. Look in the cache first. We
517 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
518 * is set, the buffer is valid and we do not have to do anything ( see
522 bread(struct vnode * vp, daddr_t blkno, int size, struct buf ** bpp)
526 bp = getblk(vp, blkno, size, 0, 0);
529 /* if not found in cache, do some I/O */
530 if ((bp->b_flags & B_CACHE) == 0) {
531 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
532 bp->b_flags |= B_READ;
533 bp->b_flags &= ~(B_ERROR | B_INVAL);
534 vfs_busy_pages(bp, 0);
535 VOP_STRATEGY(vp, bp);
536 return (biowait(bp));
542 * Operates like bread, but also starts asynchronous I/O on
543 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
544 * to initiating I/O . If B_CACHE is set, the buffer is valid
545 * and we do not have to do anything.
548 breadn(struct vnode * vp, daddr_t blkno, int size, daddr_t * rablkno,
549 int *rabsize, int cnt, struct buf ** bpp)
551 struct buf *bp, *rabp;
553 int rv = 0, readwait = 0;
555 *bpp = bp = getblk(vp, blkno, size, 0, 0);
557 /* if not found in cache, do some I/O */
558 if ((bp->b_flags & B_CACHE) == 0) {
559 bp->b_flags |= B_READ;
560 bp->b_flags &= ~(B_ERROR | B_INVAL);
561 vfs_busy_pages(bp, 0);
562 VOP_STRATEGY(vp, bp);
566 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
567 if (inmem(vp, *rablkno))
569 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
571 if ((rabp->b_flags & B_CACHE) == 0) {
572 rabp->b_flags |= B_READ | B_ASYNC;
573 rabp->b_flags &= ~(B_ERROR | B_INVAL);
574 vfs_busy_pages(rabp, 0);
576 VOP_STRATEGY(vp, rabp);
589 * Write, release buffer on completion. (Done by iodone
590 * if async). Do not bother writing anything if the buffer
593 * Note that we set B_CACHE here, indicating that buffer is
594 * fully valid and thus cacheable. This is true even of NFS
595 * now so we set it generally. This could be set either here
596 * or in biodone() since the I/O is synchronous. We put it
600 bwrite(struct buf * bp)
605 if (bp->b_flags & B_INVAL) {
610 oldflags = bp->b_flags;
612 if (BUF_REFCNT(bp) == 0)
613 panic("bwrite: buffer is not busy???");
616 * If a background write is already in progress, delay
617 * writing this block if it is asynchronous. Otherwise
618 * wait for the background write to complete.
620 if (bp->b_xflags & BX_BKGRDINPROG) {
621 if (bp->b_flags & B_ASYNC) {
626 bp->b_xflags |= BX_BKGRDWAIT;
627 tsleep(&bp->b_xflags, 0, "biord", 0);
628 if (bp->b_xflags & BX_BKGRDINPROG)
629 panic("bwrite: still writing");
632 /* Mark the buffer clean */
636 * If this buffer is marked for background writing and we
637 * do not have to wait for it, make a copy and write the
638 * copy so as to leave this buffer ready for further use.
640 * This optimization eats a lot of memory. If we have a page
641 * or buffer shortfull we can't do it.
644 (bp->b_xflags & BX_BKGRDWRITE) &&
645 (bp->b_flags & B_ASYNC) &&
646 !vm_page_count_severe() &&
647 !buf_dirty_count_severe()) {
648 if (bp->b_flags & B_CALL)
649 panic("bwrite: need chained iodone");
651 /* get a new block */
652 newbp = geteblk(bp->b_bufsize);
654 /* set it to be identical to the old block */
655 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
656 bgetvp(bp->b_vp, newbp);
657 newbp->b_lblkno = bp->b_lblkno;
658 newbp->b_blkno = bp->b_blkno;
659 newbp->b_offset = bp->b_offset;
660 newbp->b_iodone = vfs_backgroundwritedone;
661 newbp->b_flags |= B_ASYNC | B_CALL;
662 newbp->b_flags &= ~B_INVAL;
664 /* move over the dependencies */
665 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
666 (*bioops.io_movedeps)(bp, newbp);
669 * Initiate write on the copy, release the original to
670 * the B_LOCKED queue so that it cannot go away until
671 * the background write completes. If not locked it could go
672 * away and then be reconstituted while it was being written.
673 * If the reconstituted buffer were written, we could end up
674 * with two background copies being written at the same time.
676 bp->b_xflags |= BX_BKGRDINPROG;
677 bp->b_flags |= B_LOCKED;
682 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
683 bp->b_flags |= B_WRITEINPROG | B_CACHE;
685 bp->b_vp->v_numoutput++;
686 vfs_busy_pages(bp, 1);
689 * Normal bwrites pipeline writes
691 bp->b_runningbufspace = bp->b_bufsize;
692 runningbufspace += bp->b_runningbufspace;
695 if (oldflags & B_ASYNC)
697 VOP_STRATEGY(bp->b_vp, bp);
699 if ((oldflags & B_ASYNC) == 0) {
700 int rtval = biowait(bp);
703 } else if ((oldflags & B_NOWDRAIN) == 0) {
705 * don't allow the async write to saturate the I/O
706 * system. Deadlocks can occur only if a device strategy
707 * routine (like in VN) turns around and issues another
708 * high-level write, in which case B_NOWDRAIN is expected
709 * to be set. Otherwise we will not deadlock here because
710 * we are blocking waiting for I/O that is already in-progress
713 waitrunningbufspace();
720 * Complete a background write started from bwrite.
723 vfs_backgroundwritedone(bp)
729 * Find the original buffer that we are writing.
731 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
732 panic("backgroundwritedone: lost buffer");
734 * Process dependencies then return any unfinished ones.
736 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
737 (*bioops.io_complete)(bp);
738 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
739 (*bioops.io_movedeps)(bp, origbp);
741 * Clear the BX_BKGRDINPROG flag in the original buffer
742 * and awaken it if it is waiting for the write to complete.
743 * If BX_BKGRDINPROG is not set in the original buffer it must
744 * have been released and re-instantiated - which is not legal.
746 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
747 origbp->b_xflags &= ~BX_BKGRDINPROG;
748 if (origbp->b_xflags & BX_BKGRDWAIT) {
749 origbp->b_xflags &= ~BX_BKGRDWAIT;
750 wakeup(&origbp->b_xflags);
753 * Clear the B_LOCKED flag and remove it from the locked
754 * queue if it currently resides there.
756 origbp->b_flags &= ~B_LOCKED;
757 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
762 * This buffer is marked B_NOCACHE, so when it is released
763 * by biodone, it will be tossed. We mark it with B_READ
764 * to avoid biodone doing a second vwakeup.
766 bp->b_flags |= B_NOCACHE | B_READ;
767 bp->b_flags &= ~(B_CACHE | B_CALL | B_DONE);
773 * Delayed write. (Buffer is marked dirty). Do not bother writing
774 * anything if the buffer is marked invalid.
776 * Note that since the buffer must be completely valid, we can safely
777 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
778 * biodone() in order to prevent getblk from writing the buffer
782 bdwrite(struct buf * bp)
784 if (BUF_REFCNT(bp) == 0)
785 panic("bdwrite: buffer is not busy");
787 if (bp->b_flags & B_INVAL) {
794 * Set B_CACHE, indicating that the buffer is fully valid. This is
795 * true even of NFS now.
797 bp->b_flags |= B_CACHE;
800 * This bmap keeps the system from needing to do the bmap later,
801 * perhaps when the system is attempting to do a sync. Since it
802 * is likely that the indirect block -- or whatever other datastructure
803 * that the filesystem needs is still in memory now, it is a good
804 * thing to do this. Note also, that if the pageout daemon is
805 * requesting a sync -- there might not be enough memory to do
806 * the bmap then... So, this is important to do.
808 if (bp->b_lblkno == bp->b_blkno) {
809 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
813 * Set the *dirty* buffer range based upon the VM system dirty pages.
818 * We need to do this here to satisfy the vnode_pager and the
819 * pageout daemon, so that it thinks that the pages have been
820 * "cleaned". Note that since the pages are in a delayed write
821 * buffer -- the VFS layer "will" see that the pages get written
822 * out on the next sync, or perhaps the cluster will be completed.
828 * Wakeup the buffer flushing daemon if we have a lot of dirty
829 * buffers (midpoint between our recovery point and our stall
832 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
835 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
836 * due to the softdep code.
843 * Turn buffer into delayed write request. We must clear B_READ and
844 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
845 * itself to properly update it in the dirty/clean lists. We mark it
846 * B_DONE to ensure that any asynchronization of the buffer properly
847 * clears B_DONE ( else a panic will occur later ).
849 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
850 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
851 * should only be called if the buffer is known-good.
853 * Since the buffer is not on a queue, we do not update the numfreebuffers
856 * Must be called at splbio().
857 * The buffer must be on QUEUE_NONE.
863 KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
864 bp->b_flags &= ~(B_READ|B_RELBUF);
866 if ((bp->b_flags & B_DELWRI) == 0) {
867 bp->b_flags |= B_DONE | B_DELWRI;
868 reassignbuf(bp, bp->b_vp);
870 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
877 * Clear B_DELWRI for buffer.
879 * Since the buffer is not on a queue, we do not update the numfreebuffers
882 * Must be called at splbio().
883 * The buffer must be on QUEUE_NONE.
890 KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
892 if (bp->b_flags & B_DELWRI) {
893 bp->b_flags &= ~B_DELWRI;
894 reassignbuf(bp, bp->b_vp);
896 numdirtywakeup(lodirtybuffers);
899 * Since it is now being written, we can clear its deferred write flag.
901 bp->b_flags &= ~B_DEFERRED;
907 * Asynchronous write. Start output on a buffer, but do not wait for
908 * it to complete. The buffer is released when the output completes.
910 * bwrite() ( or the VOP routine anyway ) is responsible for handling
911 * B_INVAL buffers. Not us.
914 bawrite(struct buf * bp)
916 bp->b_flags |= B_ASYNC;
917 (void) VOP_BWRITE(bp->b_vp, bp);
923 * Ordered write. Start output on a buffer, and flag it so that the
924 * device will write it in the order it was queued. The buffer is
925 * released when the output completes. bwrite() ( or the VOP routine
926 * anyway ) is responsible for handling B_INVAL buffers.
929 bowrite(struct buf * bp)
931 bp->b_flags |= B_ORDERED | B_ASYNC;
932 return (VOP_BWRITE(bp->b_vp, bp));
938 * Called prior to the locking of any vnodes when we are expecting to
939 * write. We do not want to starve the buffer cache with too many
940 * dirty buffers so we block here. By blocking prior to the locking
941 * of any vnodes we attempt to avoid the situation where a locked vnode
942 * prevents the various system daemons from flushing related buffers.
948 if (numdirtybuffers >= hidirtybuffers) {
952 while (numdirtybuffers >= hidirtybuffers) {
954 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
955 tsleep(&needsbuffer, 0, "flswai", 0);
962 * Return true if we have too many dirty buffers.
965 buf_dirty_count_severe(void)
967 return(numdirtybuffers >= hidirtybuffers);
973 * Release a busy buffer and, if requested, free its resources. The
974 * buffer will be stashed in the appropriate bufqueue[] allowing it
975 * to be accessed later as a cache entity or reused for other purposes.
978 brelse(struct buf * bp)
982 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
986 if (bp->b_flags & B_LOCKED)
987 bp->b_flags &= ~B_ERROR;
989 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
991 * Failed write, redirty. Must clear B_ERROR to prevent
992 * pages from being scrapped. If B_INVAL is set then
993 * this case is not run and the next case is run to
994 * destroy the buffer. B_INVAL can occur if the buffer
995 * is outside the range supported by the underlying device.
997 bp->b_flags &= ~B_ERROR;
999 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
1000 (bp->b_bufsize <= 0)) {
1002 * Either a failed I/O or we were asked to free or not
1005 bp->b_flags |= B_INVAL;
1006 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1007 (*bioops.io_deallocate)(bp);
1008 if (bp->b_flags & B_DELWRI) {
1010 numdirtywakeup(lodirtybuffers);
1012 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
1013 if ((bp->b_flags & B_VMIO) == 0) {
1022 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1023 * is called with B_DELWRI set, the underlying pages may wind up
1024 * getting freed causing a previous write (bdwrite()) to get 'lost'
1025 * because pages associated with a B_DELWRI bp are marked clean.
1027 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1028 * if B_DELWRI is set.
1030 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1031 * on pages to return pages to the VM page queues.
1033 if (bp->b_flags & B_DELWRI)
1034 bp->b_flags &= ~B_RELBUF;
1035 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1036 bp->b_flags |= B_RELBUF;
1039 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1040 * constituted, not even NFS buffers now. Two flags effect this. If
1041 * B_INVAL, the struct buf is invalidated but the VM object is kept
1042 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1044 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1045 * invalidated. B_ERROR cannot be set for a failed write unless the
1046 * buffer is also B_INVAL because it hits the re-dirtying code above.
1048 * Normally we can do this whether a buffer is B_DELWRI or not. If
1049 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1050 * the commit state and we cannot afford to lose the buffer. If the
1051 * buffer has a background write in progress, we need to keep it
1052 * around to prevent it from being reconstituted and starting a second
1055 if ((bp->b_flags & B_VMIO)
1056 && !(bp->b_vp->v_tag == VT_NFS &&
1057 !vn_isdisk(bp->b_vp, NULL) &&
1058 (bp->b_flags & B_DELWRI))
1071 * Get the base offset and length of the buffer. Note that
1072 * in the VMIO case if the buffer block size is not
1073 * page-aligned then b_data pointer may not be page-aligned.
1074 * But our b_pages[] array *IS* page aligned.
1076 * block sizes less then DEV_BSIZE (usually 512) are not
1077 * supported due to the page granularity bits (m->valid,
1078 * m->dirty, etc...).
1080 * See man buf(9) for more information
1083 resid = bp->b_bufsize;
1084 foff = bp->b_offset;
1086 for (i = 0; i < bp->b_npages; i++) {
1088 vm_page_flag_clear(m, PG_ZERO);
1090 * If we hit a bogus page, fixup *all* of them
1093 if (m == bogus_page) {
1094 VOP_GETVOBJECT(vp, &obj);
1095 poff = OFF_TO_IDX(bp->b_offset);
1097 for (j = i; j < bp->b_npages; j++) {
1100 mtmp = bp->b_pages[j];
1101 if (mtmp == bogus_page) {
1102 mtmp = vm_page_lookup(obj, poff + j);
1104 panic("brelse: page missing\n");
1106 bp->b_pages[j] = mtmp;
1110 if ((bp->b_flags & B_INVAL) == 0) {
1111 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1115 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1116 int poffset = foff & PAGE_MASK;
1117 int presid = resid > (PAGE_SIZE - poffset) ?
1118 (PAGE_SIZE - poffset) : resid;
1120 KASSERT(presid >= 0, ("brelse: extra page"));
1121 vm_page_set_invalid(m, poffset, presid);
1123 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1124 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1127 if (bp->b_flags & (B_INVAL | B_RELBUF))
1128 vfs_vmio_release(bp);
1130 } else if (bp->b_flags & B_VMIO) {
1132 if (bp->b_flags & (B_INVAL | B_RELBUF))
1133 vfs_vmio_release(bp);
1137 if (bp->b_qindex != QUEUE_NONE)
1138 panic("brelse: free buffer onto another queue???");
1139 if (BUF_REFCNT(bp) > 1) {
1140 /* Temporary panic to verify exclusive locking */
1141 /* This panic goes away when we allow shared refs */
1142 panic("brelse: multiple refs");
1143 /* do not release to free list */
1151 /* buffers with no memory */
1152 if (bp->b_bufsize == 0) {
1153 bp->b_flags |= B_INVAL;
1154 bp->b_xflags &= ~BX_BKGRDWRITE;
1155 if (bp->b_xflags & BX_BKGRDINPROG)
1156 panic("losing buffer 1");
1157 if (bp->b_kvasize) {
1158 bp->b_qindex = QUEUE_EMPTYKVA;
1160 bp->b_qindex = QUEUE_EMPTY;
1162 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1163 LIST_REMOVE(bp, b_hash);
1164 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1166 /* buffers with junk contents */
1167 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1168 bp->b_flags |= B_INVAL;
1169 bp->b_xflags &= ~BX_BKGRDWRITE;
1170 if (bp->b_xflags & BX_BKGRDINPROG)
1171 panic("losing buffer 2");
1172 bp->b_qindex = QUEUE_CLEAN;
1173 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1174 LIST_REMOVE(bp, b_hash);
1175 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1178 /* buffers that are locked */
1179 } else if (bp->b_flags & B_LOCKED) {
1180 bp->b_qindex = QUEUE_LOCKED;
1181 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1183 /* remaining buffers */
1185 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1186 case B_DELWRI | B_AGE:
1187 bp->b_qindex = QUEUE_DIRTY;
1188 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1191 bp->b_qindex = QUEUE_DIRTY;
1192 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1195 bp->b_qindex = QUEUE_CLEAN;
1196 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1199 bp->b_qindex = QUEUE_CLEAN;
1200 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1206 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1207 * on the correct queue.
1209 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1213 * Fixup numfreebuffers count. The bp is on an appropriate queue
1214 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1215 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1216 * if B_INVAL is set ).
1219 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1223 * Something we can maybe free or reuse
1225 if (bp->b_bufsize || bp->b_kvasize)
1230 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1231 B_DIRECT | B_NOWDRAIN);
1236 * Release a buffer back to the appropriate queue but do not try to free
1237 * it. The buffer is expected to be used again soon.
1239 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1240 * biodone() to requeue an async I/O on completion. It is also used when
1241 * known good buffers need to be requeued but we think we may need the data
1244 * XXX we should be able to leave the B_RELBUF hint set on completion.
1247 bqrelse(struct buf * bp)
1253 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1255 if (bp->b_qindex != QUEUE_NONE)
1256 panic("bqrelse: free buffer onto another queue???");
1257 if (BUF_REFCNT(bp) > 1) {
1258 /* do not release to free list */
1259 panic("bqrelse: multiple refs");
1264 if (bp->b_flags & B_LOCKED) {
1265 bp->b_flags &= ~B_ERROR;
1266 bp->b_qindex = QUEUE_LOCKED;
1267 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1268 /* buffers with stale but valid contents */
1269 } else if (bp->b_flags & B_DELWRI) {
1270 bp->b_qindex = QUEUE_DIRTY;
1271 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1272 } else if (vm_page_count_severe()) {
1274 * We are too low on memory, we have to try to free the
1275 * buffer (most importantly: the wired pages making up its
1276 * backing store) *now*.
1282 bp->b_qindex = QUEUE_CLEAN;
1283 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1286 if ((bp->b_flags & B_LOCKED) == 0 &&
1287 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1292 * Something we can maybe free or reuse.
1294 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1299 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1304 vfs_vmio_release(bp)
1311 for (i = 0; i < bp->b_npages; i++) {
1313 bp->b_pages[i] = NULL;
1315 * In order to keep page LRU ordering consistent, put
1316 * everything on the inactive queue.
1318 vm_page_unwire(m, 0);
1320 * We don't mess with busy pages, it is
1321 * the responsibility of the process that
1322 * busied the pages to deal with them.
1324 if ((m->flags & PG_BUSY) || (m->busy != 0))
1327 if (m->wire_count == 0) {
1328 vm_page_flag_clear(m, PG_ZERO);
1330 * Might as well free the page if we can and it has
1331 * no valid data. We also free the page if the
1332 * buffer was used for direct I/O.
1334 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1336 vm_page_protect(m, VM_PROT_NONE);
1338 } else if (bp->b_flags & B_DIRECT) {
1339 vm_page_try_to_free(m);
1340 } else if (vm_page_count_severe()) {
1341 vm_page_try_to_cache(m);
1346 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1347 if (bp->b_bufsize) {
1352 bp->b_flags &= ~B_VMIO;
1358 * Check to see if a block is currently memory resident.
1361 gbincore(struct vnode * vp, daddr_t blkno)
1364 struct bufhashhdr *bh;
1366 bh = bufhash(vp, blkno);
1368 /* Search hash chain */
1369 LIST_FOREACH(bp, bh, b_hash) {
1371 if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1372 (bp->b_flags & B_INVAL) == 0) {
1382 * Implement clustered async writes for clearing out B_DELWRI buffers.
1383 * This is much better then the old way of writing only one buffer at
1384 * a time. Note that we may not be presented with the buffers in the
1385 * correct order, so we search for the cluster in both directions.
1388 vfs_bio_awrite(struct buf * bp)
1392 daddr_t lblkno = bp->b_lblkno;
1393 struct vnode *vp = bp->b_vp;
1403 * right now we support clustered writing only to regular files. If
1404 * we find a clusterable block we could be in the middle of a cluster
1405 * rather then at the beginning.
1407 if ((vp->v_type == VREG) &&
1408 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1409 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1411 size = vp->v_mount->mnt_stat.f_iosize;
1412 maxcl = MAXPHYS / size;
1414 for (i = 1; i < maxcl; i++) {
1415 if ((bpa = gbincore(vp, lblkno + i)) &&
1416 BUF_REFCNT(bpa) == 0 &&
1417 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1418 (B_DELWRI | B_CLUSTEROK)) &&
1419 (bpa->b_bufsize == size)) {
1420 if ((bpa->b_blkno == bpa->b_lblkno) ||
1422 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1428 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1429 if ((bpa = gbincore(vp, lblkno - j)) &&
1430 BUF_REFCNT(bpa) == 0 &&
1431 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1432 (B_DELWRI | B_CLUSTEROK)) &&
1433 (bpa->b_bufsize == size)) {
1434 if ((bpa->b_blkno == bpa->b_lblkno) ||
1436 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1445 * this is a possible cluster write
1448 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1454 BUF_LOCK(bp, LK_EXCLUSIVE);
1456 bp->b_flags |= B_ASYNC;
1460 * default (old) behavior, writing out only one block
1462 * XXX returns b_bufsize instead of b_bcount for nwritten?
1464 nwritten = bp->b_bufsize;
1465 (void) VOP_BWRITE(bp->b_vp, bp);
1473 * Find and initialize a new buffer header, freeing up existing buffers
1474 * in the bufqueues as necessary. The new buffer is returned locked.
1476 * Important: B_INVAL is not set. If the caller wishes to throw the
1477 * buffer away, the caller must set B_INVAL prior to calling brelse().
1480 * We have insufficient buffer headers
1481 * We have insufficient buffer space
1482 * buffer_map is too fragmented ( space reservation fails )
1483 * If we have to flush dirty buffers ( but we try to avoid this )
1485 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1486 * Instead we ask the buf daemon to do it for us. We attempt to
1487 * avoid piecemeal wakeups of the pageout daemon.
1491 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1497 static int flushingbufs;
1500 * We can't afford to block since we might be holding a vnode lock,
1501 * which may prevent system daemons from running. We deal with
1502 * low-memory situations by proactively returning memory and running
1503 * async I/O rather then sync I/O.
1507 --getnewbufrestarts;
1509 ++getnewbufrestarts;
1512 * Setup for scan. If we do not have enough free buffers,
1513 * we setup a degenerate case that immediately fails. Note
1514 * that if we are specially marked process, we are allowed to
1515 * dip into our reserves.
1517 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1519 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1520 * However, there are a number of cases (defragging, reusing, ...)
1521 * where we cannot backup.
1523 nqindex = QUEUE_EMPTYKVA;
1524 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1528 * If no EMPTYKVA buffers and we are either
1529 * defragging or reusing, locate a CLEAN buffer
1530 * to free or reuse. If bufspace useage is low
1531 * skip this step so we can allocate a new buffer.
1533 if (defrag || bufspace >= lobufspace) {
1534 nqindex = QUEUE_CLEAN;
1535 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1539 * If we could not find or were not allowed to reuse a
1540 * CLEAN buffer, check to see if it is ok to use an EMPTY
1541 * buffer. We can only use an EMPTY buffer if allocating
1542 * its KVA would not otherwise run us out of buffer space.
1544 if (nbp == NULL && defrag == 0 &&
1545 bufspace + maxsize < hibufspace) {
1546 nqindex = QUEUE_EMPTY;
1547 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1552 * Run scan, possibly freeing data and/or kva mappings on the fly
1556 while ((bp = nbp) != NULL) {
1557 int qindex = nqindex;
1560 * Calculate next bp ( we can only use it if we do not block
1561 * or do other fancy things ).
1563 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1566 nqindex = QUEUE_EMPTYKVA;
1567 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1570 case QUEUE_EMPTYKVA:
1571 nqindex = QUEUE_CLEAN;
1572 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1586 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1589 * Note: we no longer distinguish between VMIO and non-VMIO
1593 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1596 * If we are defragging then we need a buffer with
1597 * b_kvasize != 0. XXX this situation should no longer
1598 * occur, if defrag is non-zero the buffer's b_kvasize
1599 * should also be non-zero at this point. XXX
1601 if (defrag && bp->b_kvasize == 0) {
1602 printf("Warning: defrag empty buffer %p\n", bp);
1607 * Start freeing the bp. This is somewhat involved. nbp
1608 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1611 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1612 panic("getnewbuf: locked buf");
1615 if (qindex == QUEUE_CLEAN) {
1616 if (bp->b_flags & B_VMIO) {
1617 bp->b_flags &= ~B_ASYNC;
1618 vfs_vmio_release(bp);
1625 * NOTE: nbp is now entirely invalid. We can only restart
1626 * the scan from this point on.
1628 * Get the rest of the buffer freed up. b_kva* is still
1629 * valid after this operation.
1632 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1633 (*bioops.io_deallocate)(bp);
1634 if (bp->b_xflags & BX_BKGRDINPROG)
1635 panic("losing buffer 3");
1636 LIST_REMOVE(bp, b_hash);
1637 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1646 bp->b_blkno = bp->b_lblkno = 0;
1647 bp->b_offset = NOOFFSET;
1653 bp->b_dirtyoff = bp->b_dirtyend = 0;
1655 LIST_INIT(&bp->b_dep);
1658 * If we are defragging then free the buffer.
1661 bp->b_flags |= B_INVAL;
1669 * If we are overcomitted then recover the buffer and its
1670 * KVM space. This occurs in rare situations when multiple
1671 * processes are blocked in getnewbuf() or allocbuf().
1673 if (bufspace >= hibufspace)
1675 if (flushingbufs && bp->b_kvasize != 0) {
1676 bp->b_flags |= B_INVAL;
1681 if (bufspace < lobufspace)
1687 * If we exhausted our list, sleep as appropriate. We may have to
1688 * wakeup various daemons and write out some dirty buffers.
1690 * Generally we are sleeping due to insufficient buffer space.
1698 flags = VFS_BIO_NEED_BUFSPACE;
1700 } else if (bufspace >= hibufspace) {
1702 flags = VFS_BIO_NEED_BUFSPACE;
1705 flags = VFS_BIO_NEED_ANY;
1708 bd_speedup(); /* heeeelp */
1710 needsbuffer |= flags;
1711 while (needsbuffer & flags) {
1712 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
1717 * We finally have a valid bp. We aren't quite out of the
1718 * woods, we still have to reserve kva space. In order
1719 * to keep fragmentation sane we only allocate kva in
1722 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1724 if (maxsize != bp->b_kvasize) {
1725 vm_offset_t addr = 0;
1730 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1731 vm_map_lock(buffer_map);
1733 if (vm_map_findspace(buffer_map,
1734 vm_map_min(buffer_map), maxsize,
1737 * Uh oh. Buffer map is to fragmented. We
1738 * must defragment the map.
1740 vm_map_unlock(buffer_map);
1741 vm_map_entry_release(count);
1744 bp->b_flags |= B_INVAL;
1749 vm_map_insert(buffer_map, &count,
1751 addr, addr + maxsize,
1752 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1754 bp->b_kvabase = (caddr_t) addr;
1755 bp->b_kvasize = maxsize;
1756 bufspace += bp->b_kvasize;
1759 vm_map_unlock(buffer_map);
1760 vm_map_entry_release(count);
1762 bp->b_data = bp->b_kvabase;
1770 * buffer flushing daemon. Buffers are normally flushed by the
1771 * update daemon but if it cannot keep up this process starts to
1772 * take the load in an attempt to prevent getnewbuf() from blocking.
1775 static struct thread *bufdaemonthread;
1777 static struct kproc_desc buf_kp = {
1782 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1790 * This process needs to be suspended prior to shutdown sync.
1792 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1793 bufdaemonthread, SHUTDOWN_PRI_LAST);
1796 * This process is allowed to take the buffer cache to the limit
1801 kproc_suspend_loop();
1804 * Do the flush. Limit the amount of in-transit I/O we
1805 * allow to build up, otherwise we would completely saturate
1806 * the I/O system. Wakeup any waiting processes before we
1807 * normally would so they can run in parallel with our drain.
1809 while (numdirtybuffers > lodirtybuffers) {
1810 if (flushbufqueues() == 0)
1812 waitrunningbufspace();
1813 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1817 * Only clear bd_request if we have reached our low water
1818 * mark. The buf_daemon normally waits 5 seconds and
1819 * then incrementally flushes any dirty buffers that have
1820 * built up, within reason.
1822 * If we were unable to hit our low water mark and couldn't
1823 * find any flushable buffers, we sleep half a second.
1824 * Otherwise we loop immediately.
1826 if (numdirtybuffers <= lodirtybuffers) {
1828 * We reached our low water mark, reset the
1829 * request and sleep until we are needed again.
1830 * The sleep is just so the suspend code works.
1833 tsleep(&bd_request, 0, "psleep", hz);
1836 * We couldn't find any flushable dirty buffers but
1837 * still have too many dirty buffers, we
1838 * have to sleep and try again. (rare)
1840 tsleep(&bd_request, 0, "qsleep", hz / 2);
1848 * Try to flush a buffer in the dirty queue. We must be careful to
1849 * free up B_INVAL buffers instead of write them, which NFS is
1850 * particularly sensitive to.
1854 flushbufqueues(void)
1859 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1862 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1863 if ((bp->b_flags & B_DELWRI) != 0 &&
1864 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1865 if (bp->b_flags & B_INVAL) {
1866 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1867 panic("flushbufqueues: locked buf");
1873 if (LIST_FIRST(&bp->b_dep) != NULL &&
1874 bioops.io_countdeps &&
1875 (bp->b_flags & B_DEFERRED) == 0 &&
1876 (*bioops.io_countdeps)(bp, 0)) {
1877 TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
1879 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
1881 bp->b_flags |= B_DEFERRED;
1882 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1889 bp = TAILQ_NEXT(bp, b_freelist);
1895 * Check to see if a block is currently memory resident.
1898 incore(struct vnode * vp, daddr_t blkno)
1903 bp = gbincore(vp, blkno);
1909 * Returns true if no I/O is needed to access the
1910 * associated VM object. This is like incore except
1911 * it also hunts around in the VM system for the data.
1915 inmem(struct vnode * vp, daddr_t blkno)
1918 vm_offset_t toff, tinc, size;
1922 if (incore(vp, blkno))
1924 if (vp->v_mount == NULL)
1926 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
1930 if (size > vp->v_mount->mnt_stat.f_iosize)
1931 size = vp->v_mount->mnt_stat.f_iosize;
1932 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
1934 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1935 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1939 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
1940 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
1941 if (vm_page_is_valid(m,
1942 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
1951 * Sets the dirty range for a buffer based on the status of the dirty
1952 * bits in the pages comprising the buffer.
1954 * The range is limited to the size of the buffer.
1956 * This routine is primarily used by NFS, but is generalized for the
1960 vfs_setdirty(struct buf *bp)
1966 * Degenerate case - empty buffer
1969 if (bp->b_bufsize == 0)
1973 * We qualify the scan for modified pages on whether the
1974 * object has been flushed yet. The OBJ_WRITEABLE flag
1975 * is not cleared simply by protecting pages off.
1978 if ((bp->b_flags & B_VMIO) == 0)
1981 object = bp->b_pages[0]->object;
1983 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
1984 printf("Warning: object %p writeable but not mightbedirty\n", object);
1985 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
1986 printf("Warning: object %p mightbedirty but not writeable\n", object);
1988 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
1989 vm_offset_t boffset;
1990 vm_offset_t eoffset;
1993 * test the pages to see if they have been modified directly
1994 * by users through the VM system.
1996 for (i = 0; i < bp->b_npages; i++) {
1997 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
1998 vm_page_test_dirty(bp->b_pages[i]);
2002 * Calculate the encompassing dirty range, boffset and eoffset,
2003 * (eoffset - boffset) bytes.
2006 for (i = 0; i < bp->b_npages; i++) {
2007 if (bp->b_pages[i]->dirty)
2010 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2012 for (i = bp->b_npages - 1; i >= 0; --i) {
2013 if (bp->b_pages[i]->dirty) {
2017 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2020 * Fit it to the buffer.
2023 if (eoffset > bp->b_bcount)
2024 eoffset = bp->b_bcount;
2027 * If we have a good dirty range, merge with the existing
2031 if (boffset < eoffset) {
2032 if (bp->b_dirtyoff > boffset)
2033 bp->b_dirtyoff = boffset;
2034 if (bp->b_dirtyend < eoffset)
2035 bp->b_dirtyend = eoffset;
2043 * Get a block given a specified block and offset into a file/device.
2044 * The buffers B_DONE bit will be cleared on return, making it almost
2045 * ready for an I/O initiation. B_INVAL may or may not be set on
2046 * return. The caller should clear B_INVAL prior to initiating a
2049 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2050 * an existing buffer.
2052 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2053 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2054 * and then cleared based on the backing VM. If the previous buffer is
2055 * non-0-sized but invalid, B_CACHE will be cleared.
2057 * If getblk() must create a new buffer, the new buffer is returned with
2058 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2059 * case it is returned with B_INVAL clear and B_CACHE set based on the
2062 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2063 * B_CACHE bit is clear.
2065 * What this means, basically, is that the caller should use B_CACHE to
2066 * determine whether the buffer is fully valid or not and should clear
2067 * B_INVAL prior to issuing a read. If the caller intends to validate
2068 * the buffer by loading its data area with something, the caller needs
2069 * to clear B_INVAL. If the caller does this without issuing an I/O,
2070 * the caller should set B_CACHE ( as an optimization ), else the caller
2071 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2072 * a write attempt or if it was a successfull read. If the caller
2073 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2074 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2077 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2081 struct bufhashhdr *bh;
2083 if (size > MAXBSIZE)
2084 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2089 * Block if we are low on buffers. Certain processes are allowed
2090 * to completely exhaust the buffer cache.
2092 * If this check ever becomes a bottleneck it may be better to
2093 * move it into the else, when gbincore() fails. At the moment
2094 * it isn't a problem.
2096 * XXX remove, we cannot afford to block anywhere if holding a vnode
2097 * lock in low-memory situation, so take it to the max.
2099 if (numfreebuffers == 0) {
2102 needsbuffer |= VFS_BIO_NEED_ANY;
2103 tsleep(&needsbuffer, slpflag, "newbuf", slptimeo);
2106 if ((bp = gbincore(vp, blkno))) {
2108 * Buffer is in-core. If the buffer is not busy, it must
2112 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2113 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2114 "getblk", slpflag, slptimeo) == ENOLCK)
2117 return (struct buf *) NULL;
2121 * The buffer is locked. B_CACHE is cleared if the buffer is
2122 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2123 * and for a VMIO buffer B_CACHE is adjusted according to the
2126 if (bp->b_flags & B_INVAL)
2127 bp->b_flags &= ~B_CACHE;
2128 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2129 bp->b_flags |= B_CACHE;
2133 * check for size inconsistancies for non-VMIO case.
2136 if (bp->b_bcount != size) {
2137 if ((bp->b_flags & B_VMIO) == 0 ||
2138 (size > bp->b_kvasize)) {
2139 if (bp->b_flags & B_DELWRI) {
2140 bp->b_flags |= B_NOCACHE;
2141 VOP_BWRITE(bp->b_vp, bp);
2143 if ((bp->b_flags & B_VMIO) &&
2144 (LIST_FIRST(&bp->b_dep) == NULL)) {
2145 bp->b_flags |= B_RELBUF;
2148 bp->b_flags |= B_NOCACHE;
2149 VOP_BWRITE(bp->b_vp, bp);
2157 * If the size is inconsistant in the VMIO case, we can resize
2158 * the buffer. This might lead to B_CACHE getting set or
2159 * cleared. If the size has not changed, B_CACHE remains
2160 * unchanged from its previous state.
2163 if (bp->b_bcount != size)
2166 KASSERT(bp->b_offset != NOOFFSET,
2167 ("getblk: no buffer offset"));
2170 * A buffer with B_DELWRI set and B_CACHE clear must
2171 * be committed before we can return the buffer in
2172 * order to prevent the caller from issuing a read
2173 * ( due to B_CACHE not being set ) and overwriting
2176 * Most callers, including NFS and FFS, need this to
2177 * operate properly either because they assume they
2178 * can issue a read if B_CACHE is not set, or because
2179 * ( for example ) an uncached B_DELWRI might loop due
2180 * to softupdates re-dirtying the buffer. In the latter
2181 * case, B_CACHE is set after the first write completes,
2182 * preventing further loops.
2184 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2185 * above while extending the buffer, we cannot allow the
2186 * buffer to remain with B_CACHE set after the write
2187 * completes or it will represent a corrupt state. To
2188 * deal with this we set B_NOCACHE to scrap the buffer
2191 * We might be able to do something fancy, like setting
2192 * B_CACHE in bwrite() except if B_DELWRI is already set,
2193 * so the below call doesn't set B_CACHE, but that gets real
2194 * confusing. This is much easier.
2197 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2198 bp->b_flags |= B_NOCACHE;
2199 VOP_BWRITE(bp->b_vp, bp);
2204 bp->b_flags &= ~B_DONE;
2207 * Buffer is not in-core, create new buffer. The buffer
2208 * returned by getnewbuf() is locked. Note that the returned
2209 * buffer is also considered valid (not marked B_INVAL).
2211 int bsize, maxsize, vmio;
2214 if (vn_isdisk(vp, NULL))
2216 else if (vp->v_mountedhere)
2217 bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2218 else if (vp->v_mount)
2219 bsize = vp->v_mount->mnt_stat.f_iosize;
2223 offset = (off_t)blkno * bsize;
2224 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2225 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2226 maxsize = imax(maxsize, bsize);
2228 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2229 if (slpflag || slptimeo) {
2237 * This code is used to make sure that a buffer is not
2238 * created while the getnewbuf routine is blocked.
2239 * This can be a problem whether the vnode is locked or not.
2240 * If the buffer is created out from under us, we have to
2241 * throw away the one we just created. There is now window
2242 * race because we are safely running at splbio() from the
2243 * point of the duplicate buffer creation through to here,
2244 * and we've locked the buffer.
2246 if (gbincore(vp, blkno)) {
2247 bp->b_flags |= B_INVAL;
2253 * Insert the buffer into the hash, so that it can
2254 * be found by incore.
2256 bp->b_blkno = bp->b_lblkno = blkno;
2257 bp->b_offset = offset;
2260 LIST_REMOVE(bp, b_hash);
2261 bh = bufhash(vp, blkno);
2262 LIST_INSERT_HEAD(bh, bp, b_hash);
2265 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2266 * buffer size starts out as 0, B_CACHE will be set by
2267 * allocbuf() for the VMIO case prior to it testing the
2268 * backing store for validity.
2272 bp->b_flags |= B_VMIO;
2273 #if defined(VFS_BIO_DEBUG)
2274 if (vp->v_type != VREG && vp->v_type != VBLK)
2275 printf("getblk: vmioing file type %d???\n", vp->v_type);
2278 bp->b_flags &= ~B_VMIO;
2284 bp->b_flags &= ~B_DONE;
2290 * Get an empty, disassociated buffer of given size. The buffer is initially
2300 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2303 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2306 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2312 * This code constitutes the buffer memory from either anonymous system
2313 * memory (in the case of non-VMIO operations) or from an associated
2314 * VM object (in the case of VMIO operations). This code is able to
2315 * resize a buffer up or down.
2317 * Note that this code is tricky, and has many complications to resolve
2318 * deadlock or inconsistant data situations. Tread lightly!!!
2319 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2320 * the caller. Calling this code willy nilly can result in the loss of data.
2322 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2323 * B_CACHE for the non-VMIO case.
2327 allocbuf(struct buf *bp, int size)
2329 int newbsize, mbsize;
2332 if (BUF_REFCNT(bp) == 0)
2333 panic("allocbuf: buffer not busy");
2335 if (bp->b_kvasize < size)
2336 panic("allocbuf: buffer too small");
2338 if ((bp->b_flags & B_VMIO) == 0) {
2342 * Just get anonymous memory from the kernel. Don't
2343 * mess with B_CACHE.
2345 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2346 #if !defined(NO_B_MALLOC)
2347 if (bp->b_flags & B_MALLOC)
2351 newbsize = round_page(size);
2353 if (newbsize < bp->b_bufsize) {
2354 #if !defined(NO_B_MALLOC)
2356 * malloced buffers are not shrunk
2358 if (bp->b_flags & B_MALLOC) {
2360 bp->b_bcount = size;
2362 free(bp->b_data, M_BIOBUF);
2363 if (bp->b_bufsize) {
2364 bufmallocspace -= bp->b_bufsize;
2368 bp->b_data = bp->b_kvabase;
2370 bp->b_flags &= ~B_MALLOC;
2377 (vm_offset_t) bp->b_data + newbsize,
2378 (vm_offset_t) bp->b_data + bp->b_bufsize);
2379 } else if (newbsize > bp->b_bufsize) {
2380 #if !defined(NO_B_MALLOC)
2382 * We only use malloced memory on the first allocation.
2383 * and revert to page-allocated memory when the buffer
2386 if ( (bufmallocspace < maxbufmallocspace) &&
2387 (bp->b_bufsize == 0) &&
2388 (mbsize <= PAGE_SIZE/2)) {
2390 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2391 bp->b_bufsize = mbsize;
2392 bp->b_bcount = size;
2393 bp->b_flags |= B_MALLOC;
2394 bufmallocspace += mbsize;
2400 #if !defined(NO_B_MALLOC)
2402 * If the buffer is growing on its other-than-first allocation,
2403 * then we revert to the page-allocation scheme.
2405 if (bp->b_flags & B_MALLOC) {
2406 origbuf = bp->b_data;
2407 origbufsize = bp->b_bufsize;
2408 bp->b_data = bp->b_kvabase;
2409 if (bp->b_bufsize) {
2410 bufmallocspace -= bp->b_bufsize;
2414 bp->b_flags &= ~B_MALLOC;
2415 newbsize = round_page(newbsize);
2420 (vm_offset_t) bp->b_data + bp->b_bufsize,
2421 (vm_offset_t) bp->b_data + newbsize);
2422 #if !defined(NO_B_MALLOC)
2424 bcopy(origbuf, bp->b_data, origbufsize);
2425 free(origbuf, M_BIOBUF);
2433 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2434 desiredpages = (size == 0) ? 0 :
2435 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2437 #if !defined(NO_B_MALLOC)
2438 if (bp->b_flags & B_MALLOC)
2439 panic("allocbuf: VMIO buffer can't be malloced");
2442 * Set B_CACHE initially if buffer is 0 length or will become
2445 if (size == 0 || bp->b_bufsize == 0)
2446 bp->b_flags |= B_CACHE;
2448 if (newbsize < bp->b_bufsize) {
2450 * DEV_BSIZE aligned new buffer size is less then the
2451 * DEV_BSIZE aligned existing buffer size. Figure out
2452 * if we have to remove any pages.
2454 if (desiredpages < bp->b_npages) {
2455 for (i = desiredpages; i < bp->b_npages; i++) {
2457 * the page is not freed here -- it
2458 * is the responsibility of
2459 * vnode_pager_setsize
2462 KASSERT(m != bogus_page,
2463 ("allocbuf: bogus page found"));
2464 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2467 bp->b_pages[i] = NULL;
2468 vm_page_unwire(m, 0);
2470 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2471 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2472 bp->b_npages = desiredpages;
2474 } else if (size > bp->b_bcount) {
2476 * We are growing the buffer, possibly in a
2477 * byte-granular fashion.
2485 * Step 1, bring in the VM pages from the object,
2486 * allocating them if necessary. We must clear
2487 * B_CACHE if these pages are not valid for the
2488 * range covered by the buffer.
2492 VOP_GETVOBJECT(vp, &obj);
2494 while (bp->b_npages < desiredpages) {
2498 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2499 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2501 * note: must allocate system pages
2502 * since blocking here could intefere
2503 * with paging I/O, no matter which
2506 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2509 vm_pageout_deficit += desiredpages - bp->b_npages;
2513 bp->b_flags &= ~B_CACHE;
2514 bp->b_pages[bp->b_npages] = m;
2521 * We found a page. If we have to sleep on it,
2522 * retry because it might have gotten freed out
2525 * We can only test PG_BUSY here. Blocking on
2526 * m->busy might lead to a deadlock:
2528 * vm_fault->getpages->cluster_read->allocbuf
2532 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2536 * We have a good page. Should we wakeup the
2539 if ((curthread != pagethread) &&
2540 ((m->queue - m->pc) == PQ_CACHE) &&
2541 ((vmstats.v_free_count + vmstats.v_cache_count) <
2542 (vmstats.v_free_min + vmstats.v_cache_min))) {
2543 pagedaemon_wakeup();
2545 vm_page_flag_clear(m, PG_ZERO);
2547 bp->b_pages[bp->b_npages] = m;
2552 * Step 2. We've loaded the pages into the buffer,
2553 * we have to figure out if we can still have B_CACHE
2554 * set. Note that B_CACHE is set according to the
2555 * byte-granular range ( bcount and size ), new the
2556 * aligned range ( newbsize ).
2558 * The VM test is against m->valid, which is DEV_BSIZE
2559 * aligned. Needless to say, the validity of the data
2560 * needs to also be DEV_BSIZE aligned. Note that this
2561 * fails with NFS if the server or some other client
2562 * extends the file's EOF. If our buffer is resized,
2563 * B_CACHE may remain set! XXX
2566 toff = bp->b_bcount;
2567 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2569 while ((bp->b_flags & B_CACHE) && toff < size) {
2572 if (tinc > (size - toff))
2575 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2590 * Step 3, fixup the KVM pmap. Remember that
2591 * bp->b_data is relative to bp->b_offset, but
2592 * bp->b_offset may be offset into the first page.
2595 bp->b_data = (caddr_t)
2596 trunc_page((vm_offset_t)bp->b_data);
2598 (vm_offset_t)bp->b_data,
2602 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2603 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2606 if (newbsize < bp->b_bufsize)
2608 bp->b_bufsize = newbsize; /* actual buffer allocation */
2609 bp->b_bcount = size; /* requested buffer size */
2616 * Wait for buffer I/O completion, returning error status. The buffer
2617 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2618 * error and cleared.
2621 biowait(struct buf * bp)
2626 while ((bp->b_flags & B_DONE) == 0) {
2627 #if defined(NO_SCHEDULE_MODS)
2628 tsleep(bp, 0, "biowait", 0);
2630 if (bp->b_flags & B_READ)
2631 tsleep(bp, 0, "biord", 0);
2633 tsleep(bp, 0, "biowr", 0);
2637 if (bp->b_flags & B_EINTR) {
2638 bp->b_flags &= ~B_EINTR;
2641 if (bp->b_flags & B_ERROR) {
2642 return (bp->b_error ? bp->b_error : EIO);
2651 * Finish I/O on a buffer, optionally calling a completion function.
2652 * This is usually called from an interrupt so process blocking is
2655 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2656 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2657 * assuming B_INVAL is clear.
2659 * For the VMIO case, we set B_CACHE if the op was a read and no
2660 * read error occured, or if the op was a write. B_CACHE is never
2661 * set if the buffer is invalid or otherwise uncacheable.
2663 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2664 * initiator to leave B_INVAL set to brelse the buffer out of existance
2665 * in the biodone routine.
2668 biodone(struct buf * bp)
2674 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2675 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2677 bp->b_flags |= B_DONE;
2678 runningbufwakeup(bp);
2680 if (bp->b_flags & B_FREEBUF) {
2686 if ((bp->b_flags & B_READ) == 0) {
2690 /* call optional completion function if requested */
2691 if (bp->b_flags & B_CALL) {
2692 bp->b_flags &= ~B_CALL;
2693 (*bp->b_iodone) (bp);
2697 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2698 (*bioops.io_complete)(bp);
2700 if (bp->b_flags & B_VMIO) {
2706 struct vnode *vp = bp->b_vp;
2708 error = VOP_GETVOBJECT(vp, &obj);
2710 #if defined(VFS_BIO_DEBUG)
2711 if (vp->v_usecount == 0) {
2712 panic("biodone: zero vnode ref count");
2716 panic("biodone: missing VM object");
2719 if ((vp->v_flag & VOBJBUF) == 0) {
2720 panic("biodone: vnode is not setup for merged cache");
2724 foff = bp->b_offset;
2725 KASSERT(bp->b_offset != NOOFFSET,
2726 ("biodone: no buffer offset"));
2729 panic("biodone: no object");
2731 #if defined(VFS_BIO_DEBUG)
2732 if (obj->paging_in_progress < bp->b_npages) {
2733 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2734 obj->paging_in_progress, bp->b_npages);
2739 * Set B_CACHE if the op was a normal read and no error
2740 * occured. B_CACHE is set for writes in the b*write()
2743 iosize = bp->b_bcount - bp->b_resid;
2744 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2745 bp->b_flags |= B_CACHE;
2748 for (i = 0; i < bp->b_npages; i++) {
2752 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2757 * cleanup bogus pages, restoring the originals
2760 if (m == bogus_page) {
2762 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2764 panic("biodone: page disappeared");
2766 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2768 #if defined(VFS_BIO_DEBUG)
2769 if (OFF_TO_IDX(foff) != m->pindex) {
2771 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2772 (unsigned long)foff, m->pindex);
2777 * In the write case, the valid and clean bits are
2778 * already changed correctly ( see bdwrite() ), so we
2779 * only need to do this here in the read case.
2781 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2782 vfs_page_set_valid(bp, foff, i, m);
2784 vm_page_flag_clear(m, PG_ZERO);
2787 * when debugging new filesystems or buffer I/O methods, this
2788 * is the most common error that pops up. if you see this, you
2789 * have not set the page busy flag correctly!!!
2792 printf("biodone: page busy < 0, "
2793 "pindex: %d, foff: 0x(%x,%x), "
2794 "resid: %d, index: %d\n",
2795 (int) m->pindex, (int)(foff >> 32),
2796 (int) foff & 0xffffffff, resid, i);
2797 if (!vn_isdisk(vp, NULL))
2798 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2799 bp->b_vp->v_mount->mnt_stat.f_iosize,
2801 bp->b_flags, bp->b_npages);
2803 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2805 bp->b_flags, bp->b_npages);
2806 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2807 m->valid, m->dirty, m->wire_count);
2808 panic("biodone: page busy < 0\n");
2810 vm_page_io_finish(m);
2811 vm_object_pip_subtract(obj, 1);
2812 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2816 vm_object_pip_wakeupn(obj, 0);
2820 * For asynchronous completions, release the buffer now. The brelse
2821 * will do a wakeup there if necessary - so no need to do a wakeup
2822 * here in the async case. The sync case always needs to do a wakeup.
2825 if (bp->b_flags & B_ASYNC) {
2826 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2837 * This routine is called in lieu of iodone in the case of
2838 * incomplete I/O. This keeps the busy status for pages
2842 vfs_unbusy_pages(struct buf * bp)
2846 runningbufwakeup(bp);
2847 if (bp->b_flags & B_VMIO) {
2848 struct vnode *vp = bp->b_vp;
2851 VOP_GETVOBJECT(vp, &obj);
2853 for (i = 0; i < bp->b_npages; i++) {
2854 vm_page_t m = bp->b_pages[i];
2856 if (m == bogus_page) {
2857 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2859 panic("vfs_unbusy_pages: page missing\n");
2862 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2864 vm_object_pip_subtract(obj, 1);
2865 vm_page_flag_clear(m, PG_ZERO);
2866 vm_page_io_finish(m);
2868 vm_object_pip_wakeupn(obj, 0);
2873 * vfs_page_set_valid:
2875 * Set the valid bits in a page based on the supplied offset. The
2876 * range is restricted to the buffer's size.
2878 * This routine is typically called after a read completes.
2881 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2883 vm_ooffset_t soff, eoff;
2886 * Start and end offsets in buffer. eoff - soff may not cross a
2887 * page boundry or cross the end of the buffer. The end of the
2888 * buffer, in this case, is our file EOF, not the allocation size
2892 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2893 if (eoff > bp->b_offset + bp->b_bcount)
2894 eoff = bp->b_offset + bp->b_bcount;
2897 * Set valid range. This is typically the entire buffer and thus the
2901 vm_page_set_validclean(
2903 (vm_offset_t) (soff & PAGE_MASK),
2904 (vm_offset_t) (eoff - soff)
2910 * This routine is called before a device strategy routine.
2911 * It is used to tell the VM system that paging I/O is in
2912 * progress, and treat the pages associated with the buffer
2913 * almost as being PG_BUSY. Also the object paging_in_progress
2914 * flag is handled to make sure that the object doesn't become
2917 * Since I/O has not been initiated yet, certain buffer flags
2918 * such as B_ERROR or B_INVAL may be in an inconsistant state
2919 * and should be ignored.
2922 vfs_busy_pages(struct buf * bp, int clear_modify)
2926 if (bp->b_flags & B_VMIO) {
2927 struct vnode *vp = bp->b_vp;
2931 VOP_GETVOBJECT(vp, &obj);
2932 foff = bp->b_offset;
2933 KASSERT(bp->b_offset != NOOFFSET,
2934 ("vfs_busy_pages: no buffer offset"));
2938 for (i = 0; i < bp->b_npages; i++) {
2939 vm_page_t m = bp->b_pages[i];
2940 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
2945 for (i = 0; i < bp->b_npages; i++) {
2946 vm_page_t m = bp->b_pages[i];
2948 vm_page_flag_clear(m, PG_ZERO);
2949 if ((bp->b_flags & B_CLUSTER) == 0) {
2950 vm_object_pip_add(obj, 1);
2951 vm_page_io_start(m);
2955 * When readying a buffer for a read ( i.e
2956 * clear_modify == 0 ), it is important to do
2957 * bogus_page replacement for valid pages in
2958 * partially instantiated buffers. Partially
2959 * instantiated buffers can, in turn, occur when
2960 * reconstituting a buffer from its VM backing store
2961 * base. We only have to do this if B_CACHE is
2962 * clear ( which causes the I/O to occur in the
2963 * first place ). The replacement prevents the read
2964 * I/O from overwriting potentially dirty VM-backed
2965 * pages. XXX bogus page replacement is, uh, bogus.
2966 * It may not work properly with small-block devices.
2967 * We need to find a better way.
2970 vm_page_protect(m, VM_PROT_NONE);
2972 vfs_page_set_valid(bp, foff, i, m);
2973 else if (m->valid == VM_PAGE_BITS_ALL &&
2974 (bp->b_flags & B_CACHE) == 0) {
2975 bp->b_pages[i] = bogus_page;
2978 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2981 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2985 * This is the easiest place to put the process accounting for the I/O
2991 if ((p = curthread->td_proc) != NULL) {
2992 if (bp->b_flags & B_READ)
2993 p->p_stats->p_ru.ru_inblock++;
2995 p->p_stats->p_ru.ru_oublock++;
3001 * Tell the VM system that the pages associated with this buffer
3002 * are clean. This is used for delayed writes where the data is
3003 * going to go to disk eventually without additional VM intevention.
3005 * Note that while we only really need to clean through to b_bcount, we
3006 * just go ahead and clean through to b_bufsize.
3009 vfs_clean_pages(struct buf * bp)
3013 if (bp->b_flags & B_VMIO) {
3016 foff = bp->b_offset;
3017 KASSERT(bp->b_offset != NOOFFSET,
3018 ("vfs_clean_pages: no buffer offset"));
3019 for (i = 0; i < bp->b_npages; i++) {
3020 vm_page_t m = bp->b_pages[i];
3021 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3022 vm_ooffset_t eoff = noff;
3024 if (eoff > bp->b_offset + bp->b_bufsize)
3025 eoff = bp->b_offset + bp->b_bufsize;
3026 vfs_page_set_valid(bp, foff, i, m);
3027 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3034 * vfs_bio_set_validclean:
3036 * Set the range within the buffer to valid and clean. The range is
3037 * relative to the beginning of the buffer, b_offset. Note that b_offset
3038 * itself may be offset from the beginning of the first page.
3042 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3044 if (bp->b_flags & B_VMIO) {
3049 * Fixup base to be relative to beginning of first page.
3050 * Set initial n to be the maximum number of bytes in the
3051 * first page that can be validated.
3054 base += (bp->b_offset & PAGE_MASK);
3055 n = PAGE_SIZE - (base & PAGE_MASK);
3057 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3058 vm_page_t m = bp->b_pages[i];
3063 vm_page_set_validclean(m, base & PAGE_MASK, n);
3074 * clear a buffer. This routine essentially fakes an I/O, so we need
3075 * to clear B_ERROR and B_INVAL.
3077 * Note that while we only theoretically need to clear through b_bcount,
3078 * we go ahead and clear through b_bufsize.
3082 vfs_bio_clrbuf(struct buf *bp)
3086 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3087 bp->b_flags &= ~(B_INVAL|B_ERROR);
3088 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3089 (bp->b_offset & PAGE_MASK) == 0) {
3090 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3091 if ((bp->b_pages[0]->valid & mask) == mask) {
3095 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3096 ((bp->b_pages[0]->valid & mask) == 0)) {
3097 bzero(bp->b_data, bp->b_bufsize);
3098 bp->b_pages[0]->valid |= mask;
3103 ea = sa = bp->b_data;
3104 for(i=0;i<bp->b_npages;i++,sa=ea) {
3105 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3106 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3107 ea = (caddr_t)(vm_offset_t)ulmin(
3108 (u_long)(vm_offset_t)ea,
3109 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3110 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3111 if ((bp->b_pages[i]->valid & mask) == mask)
3113 if ((bp->b_pages[i]->valid & mask) == 0) {
3114 if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3118 for (; sa < ea; sa += DEV_BSIZE, j++) {
3119 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3120 (bp->b_pages[i]->valid & (1<<j)) == 0)
3121 bzero(sa, DEV_BSIZE);
3124 bp->b_pages[i]->valid |= mask;
3125 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3134 * vm_hold_load_pages and vm_hold_unload pages get pages into
3135 * a buffers address space. The pages are anonymous and are
3136 * not associated with a file object.
3139 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3145 to = round_page(to);
3146 from = round_page(from);
3147 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3149 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3154 * note: must allocate system pages since blocking here
3155 * could intefere with paging I/O, no matter which
3158 p = vm_page_alloc(kernel_object,
3159 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3160 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3162 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3167 p->valid = VM_PAGE_BITS_ALL;
3168 vm_page_flag_clear(p, PG_ZERO);
3169 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3170 bp->b_pages[index] = p;
3173 bp->b_npages = index;
3177 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3181 int index, newnpages;
3183 from = round_page(from);
3184 to = round_page(to);
3185 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3187 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3188 p = bp->b_pages[index];
3189 if (p && (index < bp->b_npages)) {
3191 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3192 bp->b_blkno, bp->b_lblkno);
3194 bp->b_pages[index] = NULL;
3197 vm_page_unwire(p, 0);
3201 bp->b_npages = newnpages;
3205 * Map an IO request into kernel virtual address space.
3207 * All requests are (re)mapped into kernel VA space.
3208 * Notice that we use b_bufsize for the size of the buffer
3209 * to be mapped. b_bcount might be modified by the driver.
3212 vmapbuf(struct buf *bp)
3214 caddr_t addr, v, kva;
3220 if ((bp->b_flags & B_PHYS) == 0)
3222 if (bp->b_bufsize < 0)
3224 for (v = bp->b_saveaddr,
3225 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3227 addr < bp->b_data + bp->b_bufsize;
3228 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3230 * Do the vm_fault if needed; do the copy-on-write thing
3231 * when reading stuff off device into memory.
3234 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3235 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3237 for (i = 0; i < pidx; ++i) {
3238 vm_page_unhold(bp->b_pages[i]);
3239 bp->b_pages[i] = NULL;
3245 * WARNING! If sparc support is MFCd in the future this will
3246 * have to be changed from pmap_kextract() to pmap_extract()
3250 #error "If MFCing sparc support use pmap_extract"
3252 pa = pmap_kextract((vm_offset_t)addr);
3254 printf("vmapbuf: warning, race against user address during I/O");
3257 m = PHYS_TO_VM_PAGE(pa);
3259 bp->b_pages[pidx] = m;
3261 if (pidx > btoc(MAXPHYS))
3262 panic("vmapbuf: mapped more than MAXPHYS");
3263 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3265 kva = bp->b_saveaddr;
3266 bp->b_npages = pidx;
3267 bp->b_saveaddr = bp->b_data;
3268 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3273 * Free the io map PTEs associated with this IO operation.
3274 * We also invalidate the TLB entries and restore the original b_addr.
3284 if ((bp->b_flags & B_PHYS) == 0)
3287 npages = bp->b_npages;
3288 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3291 for (pidx = 0; pidx < npages; pidx++)
3292 vm_page_unhold(*m++);
3294 bp->b_data = bp->b_saveaddr;
3297 #include "opt_ddb.h"
3299 #include <ddb/ddb.h>
3301 DB_SHOW_COMMAND(buffer, db_show_buffer)
3304 struct buf *bp = (struct buf *)addr;
3307 db_printf("usage: show buffer <addr>\n");
3311 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3312 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3313 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3314 "b_blkno = %d, b_pblkno = %d\n",
3315 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3316 major(bp->b_dev), minor(bp->b_dev),
3317 bp->b_data, bp->b_blkno, bp->b_pblkno);
3320 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3321 for (i = 0; i < bp->b_npages; i++) {
3324 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3325 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3326 if ((i + 1) < bp->b_npages)