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.8 2003/07/03 17:24:02 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 __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, PVM, "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 simple_lock_init(&buftimelock);
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, PRIBIO, "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, (PRIBIO + 4), "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, (PRIBIO + 4) | slpflag,
1702 * We finally have a valid bp. We aren't quite out of the
1703 * woods, we still have to reserve kva space. In order
1704 * to keep fragmentation sane we only allocate kva in
1707 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1709 if (maxsize != bp->b_kvasize) {
1710 vm_offset_t addr = 0;
1714 vm_map_lock(buffer_map);
1716 if (vm_map_findspace(buffer_map,
1717 vm_map_min(buffer_map), maxsize, &addr)) {
1719 * Uh oh. Buffer map is to fragmented. We
1720 * must defragment the map.
1722 vm_map_unlock(buffer_map);
1725 bp->b_flags |= B_INVAL;
1730 vm_map_insert(buffer_map, NULL, 0,
1731 addr, addr + maxsize,
1732 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1734 bp->b_kvabase = (caddr_t) addr;
1735 bp->b_kvasize = maxsize;
1736 bufspace += bp->b_kvasize;
1739 vm_map_unlock(buffer_map);
1741 bp->b_data = bp->b_kvabase;
1749 * buffer flushing daemon. Buffers are normally flushed by the
1750 * update daemon but if it cannot keep up this process starts to
1751 * take the load in an attempt to prevent getnewbuf() from blocking.
1754 static struct thread *bufdaemonthread;
1756 static struct kproc_desc buf_kp = {
1761 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1769 * This process needs to be suspended prior to shutdown sync.
1771 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1772 bufdaemonthread, SHUTDOWN_PRI_LAST);
1775 * This process is allowed to take the buffer cache to the limit
1780 kproc_suspend_loop();
1783 * Do the flush. Limit the amount of in-transit I/O we
1784 * allow to build up, otherwise we would completely saturate
1785 * the I/O system. Wakeup any waiting processes before we
1786 * normally would so they can run in parallel with our drain.
1788 while (numdirtybuffers > lodirtybuffers) {
1789 if (flushbufqueues() == 0)
1791 waitrunningbufspace();
1792 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1796 * Only clear bd_request if we have reached our low water
1797 * mark. The buf_daemon normally waits 5 seconds and
1798 * then incrementally flushes any dirty buffers that have
1799 * built up, within reason.
1801 * If we were unable to hit our low water mark and couldn't
1802 * find any flushable buffers, we sleep half a second.
1803 * Otherwise we loop immediately.
1805 if (numdirtybuffers <= lodirtybuffers) {
1807 * We reached our low water mark, reset the
1808 * request and sleep until we are needed again.
1809 * The sleep is just so the suspend code works.
1812 tsleep(&bd_request, PVM, "psleep", hz);
1815 * We couldn't find any flushable dirty buffers but
1816 * still have too many dirty buffers, we
1817 * have to sleep and try again. (rare)
1819 tsleep(&bd_request, PVM, "qsleep", hz / 2);
1827 * Try to flush a buffer in the dirty queue. We must be careful to
1828 * free up B_INVAL buffers instead of write them, which NFS is
1829 * particularly sensitive to.
1833 flushbufqueues(void)
1838 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1841 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1842 if ((bp->b_flags & B_DELWRI) != 0 &&
1843 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1844 if (bp->b_flags & B_INVAL) {
1845 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1846 panic("flushbufqueues: locked buf");
1852 if (LIST_FIRST(&bp->b_dep) != NULL &&
1853 bioops.io_countdeps &&
1854 (bp->b_flags & B_DEFERRED) == 0 &&
1855 (*bioops.io_countdeps)(bp, 0)) {
1856 TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
1858 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
1860 bp->b_flags |= B_DEFERRED;
1861 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1868 bp = TAILQ_NEXT(bp, b_freelist);
1874 * Check to see if a block is currently memory resident.
1877 incore(struct vnode * vp, daddr_t blkno)
1882 bp = gbincore(vp, blkno);
1888 * Returns true if no I/O is needed to access the
1889 * associated VM object. This is like incore except
1890 * it also hunts around in the VM system for the data.
1894 inmem(struct vnode * vp, daddr_t blkno)
1897 vm_offset_t toff, tinc, size;
1901 if (incore(vp, blkno))
1903 if (vp->v_mount == NULL)
1905 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
1909 if (size > vp->v_mount->mnt_stat.f_iosize)
1910 size = vp->v_mount->mnt_stat.f_iosize;
1911 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
1913 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1914 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1918 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
1919 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
1920 if (vm_page_is_valid(m,
1921 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
1930 * Sets the dirty range for a buffer based on the status of the dirty
1931 * bits in the pages comprising the buffer.
1933 * The range is limited to the size of the buffer.
1935 * This routine is primarily used by NFS, but is generalized for the
1939 vfs_setdirty(struct buf *bp)
1945 * Degenerate case - empty buffer
1948 if (bp->b_bufsize == 0)
1952 * We qualify the scan for modified pages on whether the
1953 * object has been flushed yet. The OBJ_WRITEABLE flag
1954 * is not cleared simply by protecting pages off.
1957 if ((bp->b_flags & B_VMIO) == 0)
1960 object = bp->b_pages[0]->object;
1962 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
1963 printf("Warning: object %p writeable but not mightbedirty\n", object);
1964 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
1965 printf("Warning: object %p mightbedirty but not writeable\n", object);
1967 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
1968 vm_offset_t boffset;
1969 vm_offset_t eoffset;
1972 * test the pages to see if they have been modified directly
1973 * by users through the VM system.
1975 for (i = 0; i < bp->b_npages; i++) {
1976 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
1977 vm_page_test_dirty(bp->b_pages[i]);
1981 * Calculate the encompassing dirty range, boffset and eoffset,
1982 * (eoffset - boffset) bytes.
1985 for (i = 0; i < bp->b_npages; i++) {
1986 if (bp->b_pages[i]->dirty)
1989 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
1991 for (i = bp->b_npages - 1; i >= 0; --i) {
1992 if (bp->b_pages[i]->dirty) {
1996 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
1999 * Fit it to the buffer.
2002 if (eoffset > bp->b_bcount)
2003 eoffset = bp->b_bcount;
2006 * If we have a good dirty range, merge with the existing
2010 if (boffset < eoffset) {
2011 if (bp->b_dirtyoff > boffset)
2012 bp->b_dirtyoff = boffset;
2013 if (bp->b_dirtyend < eoffset)
2014 bp->b_dirtyend = eoffset;
2022 * Get a block given a specified block and offset into a file/device.
2023 * The buffers B_DONE bit will be cleared on return, making it almost
2024 * ready for an I/O initiation. B_INVAL may or may not be set on
2025 * return. The caller should clear B_INVAL prior to initiating a
2028 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2029 * an existing buffer.
2031 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2032 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2033 * and then cleared based on the backing VM. If the previous buffer is
2034 * non-0-sized but invalid, B_CACHE will be cleared.
2036 * If getblk() must create a new buffer, the new buffer is returned with
2037 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2038 * case it is returned with B_INVAL clear and B_CACHE set based on the
2041 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2042 * B_CACHE bit is clear.
2044 * What this means, basically, is that the caller should use B_CACHE to
2045 * determine whether the buffer is fully valid or not and should clear
2046 * B_INVAL prior to issuing a read. If the caller intends to validate
2047 * the buffer by loading its data area with something, the caller needs
2048 * to clear B_INVAL. If the caller does this without issuing an I/O,
2049 * the caller should set B_CACHE ( as an optimization ), else the caller
2050 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2051 * a write attempt or if it was a successfull read. If the caller
2052 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2053 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2056 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2060 struct bufhashhdr *bh;
2062 if (size > MAXBSIZE)
2063 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2068 * Block if we are low on buffers. Certain processes are allowed
2069 * to completely exhaust the buffer cache.
2071 * If this check ever becomes a bottleneck it may be better to
2072 * move it into the else, when gbincore() fails. At the moment
2073 * it isn't a problem.
2075 * XXX remove, we cannot afford to block anywhere if holding a vnode
2076 * lock in low-memory situation, so take it to the max.
2078 if (numfreebuffers == 0) {
2081 needsbuffer |= VFS_BIO_NEED_ANY;
2082 tsleep(&needsbuffer, (PRIBIO + 4) | slpflag, "newbuf",
2086 if ((bp = gbincore(vp, blkno))) {
2088 * Buffer is in-core. If the buffer is not busy, it must
2092 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2093 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2094 "getblk", slpflag, slptimeo) == ENOLCK)
2097 return (struct buf *) NULL;
2101 * The buffer is locked. B_CACHE is cleared if the buffer is
2102 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2103 * and for a VMIO buffer B_CACHE is adjusted according to the
2106 if (bp->b_flags & B_INVAL)
2107 bp->b_flags &= ~B_CACHE;
2108 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2109 bp->b_flags |= B_CACHE;
2113 * check for size inconsistancies for non-VMIO case.
2116 if (bp->b_bcount != size) {
2117 if ((bp->b_flags & B_VMIO) == 0 ||
2118 (size > bp->b_kvasize)) {
2119 if (bp->b_flags & B_DELWRI) {
2120 bp->b_flags |= B_NOCACHE;
2121 VOP_BWRITE(bp->b_vp, bp);
2123 if ((bp->b_flags & B_VMIO) &&
2124 (LIST_FIRST(&bp->b_dep) == NULL)) {
2125 bp->b_flags |= B_RELBUF;
2128 bp->b_flags |= B_NOCACHE;
2129 VOP_BWRITE(bp->b_vp, bp);
2137 * If the size is inconsistant in the VMIO case, we can resize
2138 * the buffer. This might lead to B_CACHE getting set or
2139 * cleared. If the size has not changed, B_CACHE remains
2140 * unchanged from its previous state.
2143 if (bp->b_bcount != size)
2146 KASSERT(bp->b_offset != NOOFFSET,
2147 ("getblk: no buffer offset"));
2150 * A buffer with B_DELWRI set and B_CACHE clear must
2151 * be committed before we can return the buffer in
2152 * order to prevent the caller from issuing a read
2153 * ( due to B_CACHE not being set ) and overwriting
2156 * Most callers, including NFS and FFS, need this to
2157 * operate properly either because they assume they
2158 * can issue a read if B_CACHE is not set, or because
2159 * ( for example ) an uncached B_DELWRI might loop due
2160 * to softupdates re-dirtying the buffer. In the latter
2161 * case, B_CACHE is set after the first write completes,
2162 * preventing further loops.
2164 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2165 * above while extending the buffer, we cannot allow the
2166 * buffer to remain with B_CACHE set after the write
2167 * completes or it will represent a corrupt state. To
2168 * deal with this we set B_NOCACHE to scrap the buffer
2171 * We might be able to do something fancy, like setting
2172 * B_CACHE in bwrite() except if B_DELWRI is already set,
2173 * so the below call doesn't set B_CACHE, but that gets real
2174 * confusing. This is much easier.
2177 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2178 bp->b_flags |= B_NOCACHE;
2179 VOP_BWRITE(bp->b_vp, bp);
2184 bp->b_flags &= ~B_DONE;
2187 * Buffer is not in-core, create new buffer. The buffer
2188 * returned by getnewbuf() is locked. Note that the returned
2189 * buffer is also considered valid (not marked B_INVAL).
2191 int bsize, maxsize, vmio;
2194 if (vn_isdisk(vp, NULL))
2196 else if (vp->v_mountedhere)
2197 bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2198 else if (vp->v_mount)
2199 bsize = vp->v_mount->mnt_stat.f_iosize;
2203 offset = (off_t)blkno * bsize;
2204 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2205 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2206 maxsize = imax(maxsize, bsize);
2208 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2209 if (slpflag || slptimeo) {
2217 * This code is used to make sure that a buffer is not
2218 * created while the getnewbuf routine is blocked.
2219 * This can be a problem whether the vnode is locked or not.
2220 * If the buffer is created out from under us, we have to
2221 * throw away the one we just created. There is now window
2222 * race because we are safely running at splbio() from the
2223 * point of the duplicate buffer creation through to here,
2224 * and we've locked the buffer.
2226 if (gbincore(vp, blkno)) {
2227 bp->b_flags |= B_INVAL;
2233 * Insert the buffer into the hash, so that it can
2234 * be found by incore.
2236 bp->b_blkno = bp->b_lblkno = blkno;
2237 bp->b_offset = offset;
2240 LIST_REMOVE(bp, b_hash);
2241 bh = bufhash(vp, blkno);
2242 LIST_INSERT_HEAD(bh, bp, b_hash);
2245 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2246 * buffer size starts out as 0, B_CACHE will be set by
2247 * allocbuf() for the VMIO case prior to it testing the
2248 * backing store for validity.
2252 bp->b_flags |= B_VMIO;
2253 #if defined(VFS_BIO_DEBUG)
2254 if (vp->v_type != VREG && vp->v_type != VBLK)
2255 printf("getblk: vmioing file type %d???\n", vp->v_type);
2258 bp->b_flags &= ~B_VMIO;
2264 bp->b_flags &= ~B_DONE;
2270 * Get an empty, disassociated buffer of given size. The buffer is initially
2280 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2283 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2286 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2292 * This code constitutes the buffer memory from either anonymous system
2293 * memory (in the case of non-VMIO operations) or from an associated
2294 * VM object (in the case of VMIO operations). This code is able to
2295 * resize a buffer up or down.
2297 * Note that this code is tricky, and has many complications to resolve
2298 * deadlock or inconsistant data situations. Tread lightly!!!
2299 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2300 * the caller. Calling this code willy nilly can result in the loss of data.
2302 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2303 * B_CACHE for the non-VMIO case.
2307 allocbuf(struct buf *bp, int size)
2309 int newbsize, mbsize;
2312 if (BUF_REFCNT(bp) == 0)
2313 panic("allocbuf: buffer not busy");
2315 if (bp->b_kvasize < size)
2316 panic("allocbuf: buffer too small");
2318 if ((bp->b_flags & B_VMIO) == 0) {
2322 * Just get anonymous memory from the kernel. Don't
2323 * mess with B_CACHE.
2325 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2326 #if !defined(NO_B_MALLOC)
2327 if (bp->b_flags & B_MALLOC)
2331 newbsize = round_page(size);
2333 if (newbsize < bp->b_bufsize) {
2334 #if !defined(NO_B_MALLOC)
2336 * malloced buffers are not shrunk
2338 if (bp->b_flags & B_MALLOC) {
2340 bp->b_bcount = size;
2342 free(bp->b_data, M_BIOBUF);
2343 if (bp->b_bufsize) {
2344 bufmallocspace -= bp->b_bufsize;
2348 bp->b_data = bp->b_kvabase;
2350 bp->b_flags &= ~B_MALLOC;
2357 (vm_offset_t) bp->b_data + newbsize,
2358 (vm_offset_t) bp->b_data + bp->b_bufsize);
2359 } else if (newbsize > bp->b_bufsize) {
2360 #if !defined(NO_B_MALLOC)
2362 * We only use malloced memory on the first allocation.
2363 * and revert to page-allocated memory when the buffer
2366 if ( (bufmallocspace < maxbufmallocspace) &&
2367 (bp->b_bufsize == 0) &&
2368 (mbsize <= PAGE_SIZE/2)) {
2370 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2371 bp->b_bufsize = mbsize;
2372 bp->b_bcount = size;
2373 bp->b_flags |= B_MALLOC;
2374 bufmallocspace += mbsize;
2380 #if !defined(NO_B_MALLOC)
2382 * If the buffer is growing on its other-than-first allocation,
2383 * then we revert to the page-allocation scheme.
2385 if (bp->b_flags & B_MALLOC) {
2386 origbuf = bp->b_data;
2387 origbufsize = bp->b_bufsize;
2388 bp->b_data = bp->b_kvabase;
2389 if (bp->b_bufsize) {
2390 bufmallocspace -= bp->b_bufsize;
2394 bp->b_flags &= ~B_MALLOC;
2395 newbsize = round_page(newbsize);
2400 (vm_offset_t) bp->b_data + bp->b_bufsize,
2401 (vm_offset_t) bp->b_data + newbsize);
2402 #if !defined(NO_B_MALLOC)
2404 bcopy(origbuf, bp->b_data, origbufsize);
2405 free(origbuf, M_BIOBUF);
2413 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2414 desiredpages = (size == 0) ? 0 :
2415 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2417 #if !defined(NO_B_MALLOC)
2418 if (bp->b_flags & B_MALLOC)
2419 panic("allocbuf: VMIO buffer can't be malloced");
2422 * Set B_CACHE initially if buffer is 0 length or will become
2425 if (size == 0 || bp->b_bufsize == 0)
2426 bp->b_flags |= B_CACHE;
2428 if (newbsize < bp->b_bufsize) {
2430 * DEV_BSIZE aligned new buffer size is less then the
2431 * DEV_BSIZE aligned existing buffer size. Figure out
2432 * if we have to remove any pages.
2434 if (desiredpages < bp->b_npages) {
2435 for (i = desiredpages; i < bp->b_npages; i++) {
2437 * the page is not freed here -- it
2438 * is the responsibility of
2439 * vnode_pager_setsize
2442 KASSERT(m != bogus_page,
2443 ("allocbuf: bogus page found"));
2444 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2447 bp->b_pages[i] = NULL;
2448 vm_page_unwire(m, 0);
2450 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2451 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2452 bp->b_npages = desiredpages;
2454 } else if (size > bp->b_bcount) {
2456 * We are growing the buffer, possibly in a
2457 * byte-granular fashion.
2465 * Step 1, bring in the VM pages from the object,
2466 * allocating them if necessary. We must clear
2467 * B_CACHE if these pages are not valid for the
2468 * range covered by the buffer.
2472 VOP_GETVOBJECT(vp, &obj);
2474 while (bp->b_npages < desiredpages) {
2478 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2479 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2481 * note: must allocate system pages
2482 * since blocking here could intefere
2483 * with paging I/O, no matter which
2486 m = vm_page_alloc(obj, pi, VM_ALLOC_SYSTEM);
2489 vm_pageout_deficit += desiredpages - bp->b_npages;
2493 bp->b_flags &= ~B_CACHE;
2494 bp->b_pages[bp->b_npages] = m;
2501 * We found a page. If we have to sleep on it,
2502 * retry because it might have gotten freed out
2505 * We can only test PG_BUSY here. Blocking on
2506 * m->busy might lead to a deadlock:
2508 * vm_fault->getpages->cluster_read->allocbuf
2512 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2516 * We have a good page. Should we wakeup the
2519 if ((curthread != pagethread) &&
2520 ((m->queue - m->pc) == PQ_CACHE) &&
2521 ((vmstats.v_free_count + vmstats.v_cache_count) <
2522 (vmstats.v_free_min + vmstats.v_cache_min))) {
2523 pagedaemon_wakeup();
2525 vm_page_flag_clear(m, PG_ZERO);
2527 bp->b_pages[bp->b_npages] = m;
2532 * Step 2. We've loaded the pages into the buffer,
2533 * we have to figure out if we can still have B_CACHE
2534 * set. Note that B_CACHE is set according to the
2535 * byte-granular range ( bcount and size ), new the
2536 * aligned range ( newbsize ).
2538 * The VM test is against m->valid, which is DEV_BSIZE
2539 * aligned. Needless to say, the validity of the data
2540 * needs to also be DEV_BSIZE aligned. Note that this
2541 * fails with NFS if the server or some other client
2542 * extends the file's EOF. If our buffer is resized,
2543 * B_CACHE may remain set! XXX
2546 toff = bp->b_bcount;
2547 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2549 while ((bp->b_flags & B_CACHE) && toff < size) {
2552 if (tinc > (size - toff))
2555 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2570 * Step 3, fixup the KVM pmap. Remember that
2571 * bp->b_data is relative to bp->b_offset, but
2572 * bp->b_offset may be offset into the first page.
2575 bp->b_data = (caddr_t)
2576 trunc_page((vm_offset_t)bp->b_data);
2578 (vm_offset_t)bp->b_data,
2582 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2583 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2586 if (newbsize < bp->b_bufsize)
2588 bp->b_bufsize = newbsize; /* actual buffer allocation */
2589 bp->b_bcount = size; /* requested buffer size */
2596 * Wait for buffer I/O completion, returning error status. The buffer
2597 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2598 * error and cleared.
2601 biowait(register struct buf * bp)
2606 while ((bp->b_flags & B_DONE) == 0) {
2607 #if defined(NO_SCHEDULE_MODS)
2608 tsleep(bp, PRIBIO, "biowait", 0);
2610 if (bp->b_flags & B_READ)
2611 tsleep(bp, PRIBIO, "biord", 0);
2613 tsleep(bp, PRIBIO, "biowr", 0);
2617 if (bp->b_flags & B_EINTR) {
2618 bp->b_flags &= ~B_EINTR;
2621 if (bp->b_flags & B_ERROR) {
2622 return (bp->b_error ? bp->b_error : EIO);
2631 * Finish I/O on a buffer, optionally calling a completion function.
2632 * This is usually called from an interrupt so process blocking is
2635 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2636 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2637 * assuming B_INVAL is clear.
2639 * For the VMIO case, we set B_CACHE if the op was a read and no
2640 * read error occured, or if the op was a write. B_CACHE is never
2641 * set if the buffer is invalid or otherwise uncacheable.
2643 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2644 * initiator to leave B_INVAL set to brelse the buffer out of existance
2645 * in the biodone routine.
2648 biodone(register struct buf * bp)
2654 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2655 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2657 bp->b_flags |= B_DONE;
2658 runningbufwakeup(bp);
2660 if (bp->b_flags & B_FREEBUF) {
2666 if ((bp->b_flags & B_READ) == 0) {
2670 /* call optional completion function if requested */
2671 if (bp->b_flags & B_CALL) {
2672 bp->b_flags &= ~B_CALL;
2673 (*bp->b_iodone) (bp);
2677 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2678 (*bioops.io_complete)(bp);
2680 if (bp->b_flags & B_VMIO) {
2686 struct vnode *vp = bp->b_vp;
2688 error = VOP_GETVOBJECT(vp, &obj);
2690 #if defined(VFS_BIO_DEBUG)
2691 if (vp->v_usecount == 0) {
2692 panic("biodone: zero vnode ref count");
2696 panic("biodone: missing VM object");
2699 if ((vp->v_flag & VOBJBUF) == 0) {
2700 panic("biodone: vnode is not setup for merged cache");
2704 foff = bp->b_offset;
2705 KASSERT(bp->b_offset != NOOFFSET,
2706 ("biodone: no buffer offset"));
2709 panic("biodone: no object");
2711 #if defined(VFS_BIO_DEBUG)
2712 if (obj->paging_in_progress < bp->b_npages) {
2713 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2714 obj->paging_in_progress, bp->b_npages);
2719 * Set B_CACHE if the op was a normal read and no error
2720 * occured. B_CACHE is set for writes in the b*write()
2723 iosize = bp->b_bcount - bp->b_resid;
2724 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2725 bp->b_flags |= B_CACHE;
2728 for (i = 0; i < bp->b_npages; i++) {
2732 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2737 * cleanup bogus pages, restoring the originals
2740 if (m == bogus_page) {
2742 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2744 panic("biodone: page disappeared");
2746 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2748 #if defined(VFS_BIO_DEBUG)
2749 if (OFF_TO_IDX(foff) != m->pindex) {
2751 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2752 (unsigned long)foff, m->pindex);
2757 * In the write case, the valid and clean bits are
2758 * already changed correctly ( see bdwrite() ), so we
2759 * only need to do this here in the read case.
2761 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2762 vfs_page_set_valid(bp, foff, i, m);
2764 vm_page_flag_clear(m, PG_ZERO);
2767 * when debugging new filesystems or buffer I/O methods, this
2768 * is the most common error that pops up. if you see this, you
2769 * have not set the page busy flag correctly!!!
2772 printf("biodone: page busy < 0, "
2773 "pindex: %d, foff: 0x(%x,%x), "
2774 "resid: %d, index: %d\n",
2775 (int) m->pindex, (int)(foff >> 32),
2776 (int) foff & 0xffffffff, resid, i);
2777 if (!vn_isdisk(vp, NULL))
2778 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2779 bp->b_vp->v_mount->mnt_stat.f_iosize,
2781 bp->b_flags, bp->b_npages);
2783 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2785 bp->b_flags, bp->b_npages);
2786 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2787 m->valid, m->dirty, m->wire_count);
2788 panic("biodone: page busy < 0\n");
2790 vm_page_io_finish(m);
2791 vm_object_pip_subtract(obj, 1);
2792 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2796 vm_object_pip_wakeupn(obj, 0);
2800 * For asynchronous completions, release the buffer now. The brelse
2801 * will do a wakeup there if necessary - so no need to do a wakeup
2802 * here in the async case. The sync case always needs to do a wakeup.
2805 if (bp->b_flags & B_ASYNC) {
2806 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2817 * This routine is called in lieu of iodone in the case of
2818 * incomplete I/O. This keeps the busy status for pages
2822 vfs_unbusy_pages(struct buf * bp)
2826 runningbufwakeup(bp);
2827 if (bp->b_flags & B_VMIO) {
2828 struct vnode *vp = bp->b_vp;
2831 VOP_GETVOBJECT(vp, &obj);
2833 for (i = 0; i < bp->b_npages; i++) {
2834 vm_page_t m = bp->b_pages[i];
2836 if (m == bogus_page) {
2837 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2839 panic("vfs_unbusy_pages: page missing\n");
2842 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2844 vm_object_pip_subtract(obj, 1);
2845 vm_page_flag_clear(m, PG_ZERO);
2846 vm_page_io_finish(m);
2848 vm_object_pip_wakeupn(obj, 0);
2853 * vfs_page_set_valid:
2855 * Set the valid bits in a page based on the supplied offset. The
2856 * range is restricted to the buffer's size.
2858 * This routine is typically called after a read completes.
2861 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2863 vm_ooffset_t soff, eoff;
2866 * Start and end offsets in buffer. eoff - soff may not cross a
2867 * page boundry or cross the end of the buffer. The end of the
2868 * buffer, in this case, is our file EOF, not the allocation size
2872 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2873 if (eoff > bp->b_offset + bp->b_bcount)
2874 eoff = bp->b_offset + bp->b_bcount;
2877 * Set valid range. This is typically the entire buffer and thus the
2881 vm_page_set_validclean(
2883 (vm_offset_t) (soff & PAGE_MASK),
2884 (vm_offset_t) (eoff - soff)
2890 * This routine is called before a device strategy routine.
2891 * It is used to tell the VM system that paging I/O is in
2892 * progress, and treat the pages associated with the buffer
2893 * almost as being PG_BUSY. Also the object paging_in_progress
2894 * flag is handled to make sure that the object doesn't become
2897 * Since I/O has not been initiated yet, certain buffer flags
2898 * such as B_ERROR or B_INVAL may be in an inconsistant state
2899 * and should be ignored.
2902 vfs_busy_pages(struct buf * bp, int clear_modify)
2906 if (bp->b_flags & B_VMIO) {
2907 struct vnode *vp = bp->b_vp;
2911 VOP_GETVOBJECT(vp, &obj);
2912 foff = bp->b_offset;
2913 KASSERT(bp->b_offset != NOOFFSET,
2914 ("vfs_busy_pages: no buffer offset"));
2918 for (i = 0; i < bp->b_npages; i++) {
2919 vm_page_t m = bp->b_pages[i];
2920 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
2925 for (i = 0; i < bp->b_npages; i++) {
2926 vm_page_t m = bp->b_pages[i];
2928 vm_page_flag_clear(m, PG_ZERO);
2929 if ((bp->b_flags & B_CLUSTER) == 0) {
2930 vm_object_pip_add(obj, 1);
2931 vm_page_io_start(m);
2935 * When readying a buffer for a read ( i.e
2936 * clear_modify == 0 ), it is important to do
2937 * bogus_page replacement for valid pages in
2938 * partially instantiated buffers. Partially
2939 * instantiated buffers can, in turn, occur when
2940 * reconstituting a buffer from its VM backing store
2941 * base. We only have to do this if B_CACHE is
2942 * clear ( which causes the I/O to occur in the
2943 * first place ). The replacement prevents the read
2944 * I/O from overwriting potentially dirty VM-backed
2945 * pages. XXX bogus page replacement is, uh, bogus.
2946 * It may not work properly with small-block devices.
2947 * We need to find a better way.
2950 vm_page_protect(m, VM_PROT_NONE);
2952 vfs_page_set_valid(bp, foff, i, m);
2953 else if (m->valid == VM_PAGE_BITS_ALL &&
2954 (bp->b_flags & B_CACHE) == 0) {
2955 bp->b_pages[i] = bogus_page;
2958 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2961 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2965 * This is the easiest place to put the process accounting for the I/O
2971 if ((p = curthread->td_proc) != NULL) {
2972 if (bp->b_flags & B_READ)
2973 p->p_stats->p_ru.ru_inblock++;
2975 p->p_stats->p_ru.ru_oublock++;
2981 * Tell the VM system that the pages associated with this buffer
2982 * are clean. This is used for delayed writes where the data is
2983 * going to go to disk eventually without additional VM intevention.
2985 * Note that while we only really need to clean through to b_bcount, we
2986 * just go ahead and clean through to b_bufsize.
2989 vfs_clean_pages(struct buf * bp)
2993 if (bp->b_flags & B_VMIO) {
2996 foff = bp->b_offset;
2997 KASSERT(bp->b_offset != NOOFFSET,
2998 ("vfs_clean_pages: no buffer offset"));
2999 for (i = 0; i < bp->b_npages; i++) {
3000 vm_page_t m = bp->b_pages[i];
3001 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3002 vm_ooffset_t eoff = noff;
3004 if (eoff > bp->b_offset + bp->b_bufsize)
3005 eoff = bp->b_offset + bp->b_bufsize;
3006 vfs_page_set_valid(bp, foff, i, m);
3007 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3014 * vfs_bio_set_validclean:
3016 * Set the range within the buffer to valid and clean. The range is
3017 * relative to the beginning of the buffer, b_offset. Note that b_offset
3018 * itself may be offset from the beginning of the first page.
3022 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3024 if (bp->b_flags & B_VMIO) {
3029 * Fixup base to be relative to beginning of first page.
3030 * Set initial n to be the maximum number of bytes in the
3031 * first page that can be validated.
3034 base += (bp->b_offset & PAGE_MASK);
3035 n = PAGE_SIZE - (base & PAGE_MASK);
3037 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3038 vm_page_t m = bp->b_pages[i];
3043 vm_page_set_validclean(m, base & PAGE_MASK, n);
3054 * clear a buffer. This routine essentially fakes an I/O, so we need
3055 * to clear B_ERROR and B_INVAL.
3057 * Note that while we only theoretically need to clear through b_bcount,
3058 * we go ahead and clear through b_bufsize.
3062 vfs_bio_clrbuf(struct buf *bp)
3066 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3067 bp->b_flags &= ~(B_INVAL|B_ERROR);
3068 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3069 (bp->b_offset & PAGE_MASK) == 0) {
3070 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3071 if ((bp->b_pages[0]->valid & mask) == mask) {
3075 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3076 ((bp->b_pages[0]->valid & mask) == 0)) {
3077 bzero(bp->b_data, bp->b_bufsize);
3078 bp->b_pages[0]->valid |= mask;
3083 ea = sa = bp->b_data;
3084 for(i=0;i<bp->b_npages;i++,sa=ea) {
3085 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3086 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3087 ea = (caddr_t)(vm_offset_t)ulmin(
3088 (u_long)(vm_offset_t)ea,
3089 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3090 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3091 if ((bp->b_pages[i]->valid & mask) == mask)
3093 if ((bp->b_pages[i]->valid & mask) == 0) {
3094 if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3098 for (; sa < ea; sa += DEV_BSIZE, j++) {
3099 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3100 (bp->b_pages[i]->valid & (1<<j)) == 0)
3101 bzero(sa, DEV_BSIZE);
3104 bp->b_pages[i]->valid |= mask;
3105 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3114 * vm_hold_load_pages and vm_hold_unload pages get pages into
3115 * a buffers address space. The pages are anonymous and are
3116 * not associated with a file object.
3119 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3125 to = round_page(to);
3126 from = round_page(from);
3127 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3129 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3134 * note: must allocate system pages since blocking here
3135 * could intefere with paging I/O, no matter which
3138 p = vm_page_alloc(kernel_object,
3139 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3142 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3147 p->valid = VM_PAGE_BITS_ALL;
3148 vm_page_flag_clear(p, PG_ZERO);
3149 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3150 bp->b_pages[index] = p;
3153 bp->b_npages = index;
3157 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3161 int index, newnpages;
3163 from = round_page(from);
3164 to = round_page(to);
3165 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3167 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3168 p = bp->b_pages[index];
3169 if (p && (index < bp->b_npages)) {
3171 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3172 bp->b_blkno, bp->b_lblkno);
3174 bp->b_pages[index] = NULL;
3177 vm_page_unwire(p, 0);
3181 bp->b_npages = newnpages;
3185 * Map an IO request into kernel virtual address space.
3187 * All requests are (re)mapped into kernel VA space.
3188 * Notice that we use b_bufsize for the size of the buffer
3189 * to be mapped. b_bcount might be modified by the driver.
3192 vmapbuf(struct buf *bp)
3194 caddr_t addr, v, kva;
3200 if ((bp->b_flags & B_PHYS) == 0)
3202 if (bp->b_bufsize < 0)
3204 for (v = bp->b_saveaddr,
3205 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3207 addr < bp->b_data + bp->b_bufsize;
3208 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3210 * Do the vm_fault if needed; do the copy-on-write thing
3211 * when reading stuff off device into memory.
3214 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3215 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3217 for (i = 0; i < pidx; ++i) {
3218 vm_page_unhold(bp->b_pages[i]);
3219 bp->b_pages[i] = NULL;
3225 * WARNING! If sparc support is MFCd in the future this will
3226 * have to be changed from pmap_kextract() to pmap_extract()
3230 #error "If MFCing sparc support use pmap_extract"
3232 pa = pmap_kextract((vm_offset_t)addr);
3234 printf("vmapbuf: warning, race against user address during I/O");
3237 m = PHYS_TO_VM_PAGE(pa);
3239 bp->b_pages[pidx] = m;
3241 if (pidx > btoc(MAXPHYS))
3242 panic("vmapbuf: mapped more than MAXPHYS");
3243 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3245 kva = bp->b_saveaddr;
3246 bp->b_npages = pidx;
3247 bp->b_saveaddr = bp->b_data;
3248 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3253 * Free the io map PTEs associated with this IO operation.
3254 * We also invalidate the TLB entries and restore the original b_addr.
3258 register struct buf *bp;
3264 if ((bp->b_flags & B_PHYS) == 0)
3267 npages = bp->b_npages;
3268 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3271 for (pidx = 0; pidx < npages; pidx++)
3272 vm_page_unhold(*m++);
3274 bp->b_data = bp->b_saveaddr;
3277 #include "opt_ddb.h"
3279 #include <ddb/ddb.h>
3281 DB_SHOW_COMMAND(buffer, db_show_buffer)
3284 struct buf *bp = (struct buf *)addr;
3287 db_printf("usage: show buffer <addr>\n");
3291 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3292 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3293 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3294 "b_blkno = %d, b_pblkno = %d\n",
3295 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3296 major(bp->b_dev), minor(bp->b_dev),
3297 bp->b_data, bp->b_blkno, bp->b_pblkno);
3300 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3301 for (i = 0; i < bp->b_npages; i++) {
3304 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3305 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3306 if ((i + 1) < bp->b_npages)