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 $
18 * this file contains a new buffer I/O scheme implementing a coherent
19 * VM object and buffer cache scheme. Pains have been taken to make
20 * sure that the performance degradation associated with schemes such
21 * as this is not realized.
23 * Author: John S. Dyson
24 * Significant help during the development and debugging phases
25 * had been provided by David Greenman, also of the FreeBSD core team.
27 * see man buf(9) for more info.
30 #include <sys/param.h>
31 #include <sys/systm.h>
34 #include <sys/eventhandler.h>
36 #include <sys/malloc.h>
37 #include <sys/mount.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
41 #include <sys/reboot.h>
42 #include <sys/resourcevar.h>
43 #include <sys/sysctl.h>
44 #include <sys/vmmeter.h>
45 #include <sys/vnode.h>
47 #include <vm/vm_param.h>
48 #include <vm/vm_kern.h>
49 #include <vm/vm_pageout.h>
50 #include <vm/vm_page.h>
51 #include <vm/vm_object.h>
52 #include <vm/vm_extern.h>
53 #include <vm/vm_map.h>
55 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
57 struct bio_ops bioops; /* I/O operation notification */
59 struct buf *buf; /* buffer header pool */
60 struct swqueue bswlist;
62 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
64 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
66 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
67 int pageno, vm_page_t m);
68 static void vfs_clean_pages(struct buf * bp);
69 static void vfs_setdirty(struct buf *bp);
70 static void vfs_vmio_release(struct buf *bp);
71 static void vfs_backgroundwritedone(struct buf *bp);
72 static int flushbufqueues(void);
74 static int bd_request;
76 static void buf_daemon __P((void));
78 * bogus page -- for I/O to/from partially complete buffers
79 * this is a temporary solution to the problem, but it is not
80 * really that bad. it would be better to split the buffer
81 * for input in the case of buffers partially already in memory,
82 * but the code is intricate enough already.
85 int vmiodirenable = TRUE;
87 static vm_offset_t bogus_offset;
89 static int bufspace, maxbufspace,
90 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
91 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
92 static int needsbuffer;
93 static int lorunningspace, hirunningspace, runningbufreq;
94 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
95 static int numfreebuffers, lofreebuffers, hifreebuffers;
96 static int getnewbufcalls;
97 static int getnewbufrestarts;
99 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
100 &numdirtybuffers, 0, "");
101 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
102 &lodirtybuffers, 0, "");
103 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
104 &hidirtybuffers, 0, "");
105 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
106 &numfreebuffers, 0, "");
107 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
108 &lofreebuffers, 0, "");
109 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
110 &hifreebuffers, 0, "");
111 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
112 &runningbufspace, 0, "");
113 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW,
114 &lorunningspace, 0, "");
115 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW,
116 &hirunningspace, 0, "");
117 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD,
118 &maxbufspace, 0, "");
119 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
121 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD,
123 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
125 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
126 &maxbufmallocspace, 0, "");
127 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
128 &bufmallocspace, 0, "");
129 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW,
130 &getnewbufcalls, 0, "");
131 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW,
132 &getnewbufrestarts, 0, "");
133 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW,
134 &vmiodirenable, 0, "");
135 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW,
136 &bufdefragcnt, 0, "");
137 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW,
138 &buffreekvacnt, 0, "");
139 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW,
140 &bufreusecnt, 0, "");
142 static int bufhashmask;
143 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
144 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
145 char *buf_wmesg = BUF_WMESG;
147 extern int vm_swap_size;
149 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
150 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
151 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
152 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
155 * Buffer hash table code. Note that the logical block scans linearly, which
156 * gives us some L1 cache locality.
161 bufhash(struct vnode *vnp, daddr_t bn)
163 return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
169 * If someone is blocked due to there being too many dirty buffers,
170 * and numdirtybuffers is now reasonable, wake them up.
174 numdirtywakeup(int level)
176 if (numdirtybuffers <= level) {
177 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
178 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
179 wakeup(&needsbuffer);
187 * Called when buffer space is potentially available for recovery.
188 * getnewbuf() will block on this flag when it is unable to free
189 * sufficient buffer space. Buffer space becomes recoverable when
190 * bp's get placed back in the queues.
197 * If someone is waiting for BUF space, wake them up. Even
198 * though we haven't freed the kva space yet, the waiting
199 * process will be able to now.
201 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
202 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
203 wakeup(&needsbuffer);
208 * runningbufwakeup() - in-progress I/O accounting.
212 runningbufwakeup(struct buf *bp)
214 if (bp->b_runningbufspace) {
215 runningbufspace -= bp->b_runningbufspace;
216 bp->b_runningbufspace = 0;
217 if (runningbufreq && runningbufspace <= lorunningspace) {
219 wakeup(&runningbufreq);
227 * Called when a buffer has been added to one of the free queues to
228 * account for the buffer and to wakeup anyone waiting for free buffers.
229 * This typically occurs when large amounts of metadata are being handled
230 * by the buffer cache ( else buffer space runs out first, usually ).
238 needsbuffer &= ~VFS_BIO_NEED_ANY;
239 if (numfreebuffers >= hifreebuffers)
240 needsbuffer &= ~VFS_BIO_NEED_FREE;
241 wakeup(&needsbuffer);
246 * waitrunningbufspace()
248 * runningbufspace is a measure of the amount of I/O currently
249 * running. This routine is used in async-write situations to
250 * prevent creating huge backups of pending writes to a device.
251 * Only asynchronous writes are governed by this function.
253 * Reads will adjust runningbufspace, but will not block based on it.
254 * The read load has a side effect of reducing the allowed write load.
256 * This does NOT turn an async write into a sync write. It waits
257 * for earlier writes to complete and generally returns before the
258 * caller's write has reached the device.
261 waitrunningbufspace(void)
263 while (runningbufspace > hirunningspace) {
266 s = splbio(); /* fix race against interrupt/biodone() */
268 tsleep(&runningbufreq, PVM, "wdrain", 0);
274 * vfs_buf_test_cache:
276 * Called when a buffer is extended. This function clears the B_CACHE
277 * bit if the newly extended portion of the buffer does not contain
282 vfs_buf_test_cache(struct buf *bp,
283 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
286 if (bp->b_flags & B_CACHE) {
287 int base = (foff + off) & PAGE_MASK;
288 if (vm_page_is_valid(m, base, size) == 0)
289 bp->b_flags &= ~B_CACHE;
295 bd_wakeup(int dirtybuflevel)
297 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
304 * bd_speedup - speedup the buffer cache flushing code
315 * Initialize buffer headers and related structures.
319 bufhashinit(caddr_t vaddr)
321 /* first, make a null hash table */
322 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
324 bufhashtbl = (void *)vaddr;
325 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
336 TAILQ_INIT(&bswlist);
337 LIST_INIT(&invalhash);
338 simple_lock_init(&buftimelock);
340 for (i = 0; i <= bufhashmask; i++)
341 LIST_INIT(&bufhashtbl[i]);
343 /* next, make a null set of free lists */
344 for (i = 0; i < BUFFER_QUEUES; i++)
345 TAILQ_INIT(&bufqueues[i]);
347 /* finally, initialize each buffer header and stick on empty q */
348 for (i = 0; i < nbuf; i++) {
350 bzero(bp, sizeof *bp);
351 bp->b_flags = B_INVAL; /* we're just an empty header */
353 bp->b_rcred = NOCRED;
354 bp->b_wcred = NOCRED;
355 bp->b_qindex = QUEUE_EMPTY;
357 LIST_INIT(&bp->b_dep);
359 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
360 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
364 * maxbufspace is the absolute maximum amount of buffer space we are
365 * allowed to reserve in KVM and in real terms. The absolute maximum
366 * is nominally used by buf_daemon. hibufspace is the nominal maximum
367 * used by most other processes. The differential is required to
368 * ensure that buf_daemon is able to run when other processes might
369 * be blocked waiting for buffer space.
371 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
372 * this may result in KVM fragmentation which is not handled optimally
375 maxbufspace = nbuf * BKVASIZE;
376 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
377 lobufspace = hibufspace - MAXBSIZE;
379 lorunningspace = 512 * 1024;
380 hirunningspace = 1024 * 1024;
383 * Limit the amount of malloc memory since it is wired permanently into
384 * the kernel space. Even though this is accounted for in the buffer
385 * allocation, we don't want the malloced region to grow uncontrolled.
386 * The malloc scheme improves memory utilization significantly on average
387 * (small) directories.
389 maxbufmallocspace = hibufspace / 20;
392 * Reduce the chance of a deadlock occuring by limiting the number
393 * of delayed-write dirty buffers we allow to stack up.
395 hidirtybuffers = nbuf / 4 + 20;
398 * To support extreme low-memory systems, make sure hidirtybuffers cannot
399 * eat up all available buffer space. This occurs when our minimum cannot
400 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
401 * BKVASIZE'd (8K) buffers.
403 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
404 hidirtybuffers >>= 1;
406 lodirtybuffers = hidirtybuffers / 2;
409 * Try to keep the number of free buffers in the specified range,
410 * and give special processes (e.g. like buf_daemon) access to an
413 lofreebuffers = nbuf / 18 + 5;
414 hifreebuffers = 2 * lofreebuffers;
415 numfreebuffers = nbuf;
418 * Maximum number of async ops initiated per buf_daemon loop. This is
419 * somewhat of a hack at the moment, we really need to limit ourselves
420 * based on the number of bytes of I/O in-transit that were initiated
424 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
425 bogus_page = vm_page_alloc(kernel_object,
426 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
433 * bfreekva() - free the kva allocation for a buffer.
435 * Must be called at splbio() or higher as this is the only locking for
438 * Since this call frees up buffer space, we call bufspacewakeup().
441 bfreekva(struct buf * bp)
445 vm_map_lock(buffer_map);
446 bufspace -= bp->b_kvasize;
447 vm_map_delete(buffer_map,
448 (vm_offset_t) bp->b_kvabase,
449 (vm_offset_t) bp->b_kvabase + bp->b_kvasize
451 vm_map_unlock(buffer_map);
460 * Remove the buffer from the appropriate free list.
463 bremfree(struct buf * bp)
466 int old_qindex = bp->b_qindex;
468 if (bp->b_qindex != QUEUE_NONE) {
469 KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
470 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
471 bp->b_qindex = QUEUE_NONE;
473 if (BUF_REFCNT(bp) <= 1)
474 panic("bremfree: removing a buffer not on a queue");
478 * Fixup numfreebuffers count. If the buffer is invalid or not
479 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
480 * the buffer was free and we must decrement numfreebuffers.
482 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
499 * Get a buffer with the specified data. Look in the cache first. We
500 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
501 * is set, the buffer is valid and we do not have to do anything ( see
505 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
510 bp = getblk(vp, blkno, size, 0, 0);
513 /* if not found in cache, do some I/O */
514 if ((bp->b_flags & B_CACHE) == 0) {
516 curproc->p_stats->p_ru.ru_inblock++;
517 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
518 bp->b_flags |= B_READ;
519 bp->b_flags &= ~(B_ERROR | B_INVAL);
520 if (bp->b_rcred == NOCRED) {
525 vfs_busy_pages(bp, 0);
526 VOP_STRATEGY(vp, bp);
527 return (biowait(bp));
533 * Operates like bread, but also starts asynchronous I/O on
534 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
535 * to initiating I/O . If B_CACHE is set, the buffer is valid
536 * and we do not have to do anything.
539 breadn(struct vnode * vp, daddr_t blkno, int size,
540 daddr_t * rablkno, int *rabsize,
541 int cnt, struct ucred * cred, struct buf ** bpp)
543 struct buf *bp, *rabp;
545 int rv = 0, readwait = 0;
547 *bpp = bp = getblk(vp, blkno, size, 0, 0);
549 /* if not found in cache, do some I/O */
550 if ((bp->b_flags & B_CACHE) == 0) {
552 curproc->p_stats->p_ru.ru_inblock++;
553 bp->b_flags |= B_READ;
554 bp->b_flags &= ~(B_ERROR | B_INVAL);
555 if (bp->b_rcred == NOCRED) {
560 vfs_busy_pages(bp, 0);
561 VOP_STRATEGY(vp, bp);
565 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
566 if (inmem(vp, *rablkno))
568 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
570 if ((rabp->b_flags & B_CACHE) == 0) {
572 curproc->p_stats->p_ru.ru_inblock++;
573 rabp->b_flags |= B_READ | B_ASYNC;
574 rabp->b_flags &= ~(B_ERROR | B_INVAL);
575 if (rabp->b_rcred == NOCRED) {
578 rabp->b_rcred = cred;
580 vfs_busy_pages(rabp, 0);
582 VOP_STRATEGY(vp, rabp);
595 * Write, release buffer on completion. (Done by iodone
596 * if async). Do not bother writing anything if the buffer
599 * Note that we set B_CACHE here, indicating that buffer is
600 * fully valid and thus cacheable. This is true even of NFS
601 * now so we set it generally. This could be set either here
602 * or in biodone() since the I/O is synchronous. We put it
606 bwrite(struct buf * bp)
611 if (bp->b_flags & B_INVAL) {
616 oldflags = bp->b_flags;
618 if (BUF_REFCNT(bp) == 0)
619 panic("bwrite: buffer is not busy???");
622 * If a background write is already in progress, delay
623 * writing this block if it is asynchronous. Otherwise
624 * wait for the background write to complete.
626 if (bp->b_xflags & BX_BKGRDINPROG) {
627 if (bp->b_flags & B_ASYNC) {
632 bp->b_xflags |= BX_BKGRDWAIT;
633 tsleep(&bp->b_xflags, PRIBIO, "biord", 0);
634 if (bp->b_xflags & BX_BKGRDINPROG)
635 panic("bwrite: still writing");
638 /* Mark the buffer clean */
642 * If this buffer is marked for background writing and we
643 * do not have to wait for it, make a copy and write the
644 * copy so as to leave this buffer ready for further use.
646 * This optimization eats a lot of memory. If we have a page
647 * or buffer shortfull we can't do it.
649 if ((bp->b_xflags & BX_BKGRDWRITE) &&
650 (bp->b_flags & B_ASYNC) &&
651 !vm_page_count_severe() &&
652 !buf_dirty_count_severe()) {
653 if (bp->b_flags & B_CALL)
654 panic("bwrite: need chained iodone");
656 /* get a new block */
657 newbp = geteblk(bp->b_bufsize);
659 /* set it to be identical to the old block */
660 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
661 bgetvp(bp->b_vp, newbp);
662 newbp->b_lblkno = bp->b_lblkno;
663 newbp->b_blkno = bp->b_blkno;
664 newbp->b_offset = bp->b_offset;
665 newbp->b_iodone = vfs_backgroundwritedone;
666 newbp->b_flags |= B_ASYNC | B_CALL;
667 newbp->b_flags &= ~B_INVAL;
669 /* move over the dependencies */
670 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
671 (*bioops.io_movedeps)(bp, newbp);
674 * Initiate write on the copy, release the original to
675 * the B_LOCKED queue so that it cannot go away until
676 * the background write completes. If not locked it could go
677 * away and then be reconstituted while it was being written.
678 * If the reconstituted buffer were written, we could end up
679 * with two background copies being written at the same time.
681 bp->b_xflags |= BX_BKGRDINPROG;
682 bp->b_flags |= B_LOCKED;
687 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
688 bp->b_flags |= B_WRITEINPROG | B_CACHE;
690 bp->b_vp->v_numoutput++;
691 vfs_busy_pages(bp, 1);
694 * Normal bwrites pipeline writes
696 bp->b_runningbufspace = bp->b_bufsize;
697 runningbufspace += bp->b_runningbufspace;
700 curproc->p_stats->p_ru.ru_oublock++;
702 if (oldflags & B_ASYNC)
704 VOP_STRATEGY(bp->b_vp, bp);
706 if ((oldflags & B_ASYNC) == 0) {
707 int rtval = biowait(bp);
710 } else if ((oldflags & B_NOWDRAIN) == 0) {
712 * don't allow the async write to saturate the I/O
713 * system. Deadlocks can occur only if a device strategy
714 * routine (like in VN) turns around and issues another
715 * high-level write, in which case B_NOWDRAIN is expected
716 * to be set. Otherwise we will not deadlock here because
717 * we are blocking waiting for I/O that is already in-progress
720 waitrunningbufspace();
727 * Complete a background write started from bwrite.
730 vfs_backgroundwritedone(bp)
736 * Find the original buffer that we are writing.
738 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
739 panic("backgroundwritedone: lost buffer");
741 * Process dependencies then return any unfinished ones.
743 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
744 (*bioops.io_complete)(bp);
745 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
746 (*bioops.io_movedeps)(bp, origbp);
748 * Clear the BX_BKGRDINPROG flag in the original buffer
749 * and awaken it if it is waiting for the write to complete.
750 * If BX_BKGRDINPROG is not set in the original buffer it must
751 * have been released and re-instantiated - which is not legal.
753 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
754 origbp->b_xflags &= ~BX_BKGRDINPROG;
755 if (origbp->b_xflags & BX_BKGRDWAIT) {
756 origbp->b_xflags &= ~BX_BKGRDWAIT;
757 wakeup(&origbp->b_xflags);
760 * Clear the B_LOCKED flag and remove it from the locked
761 * queue if it currently resides there.
763 origbp->b_flags &= ~B_LOCKED;
764 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
769 * This buffer is marked B_NOCACHE, so when it is released
770 * by biodone, it will be tossed. We mark it with B_READ
771 * to avoid biodone doing a second vwakeup.
773 bp->b_flags |= B_NOCACHE | B_READ;
774 bp->b_flags &= ~(B_CACHE | B_CALL | B_DONE);
780 * Delayed write. (Buffer is marked dirty). Do not bother writing
781 * anything if the buffer is marked invalid.
783 * Note that since the buffer must be completely valid, we can safely
784 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
785 * biodone() in order to prevent getblk from writing the buffer
789 bdwrite(struct buf * bp)
791 if (BUF_REFCNT(bp) == 0)
792 panic("bdwrite: buffer is not busy");
794 if (bp->b_flags & B_INVAL) {
801 * Set B_CACHE, indicating that the buffer is fully valid. This is
802 * true even of NFS now.
804 bp->b_flags |= B_CACHE;
807 * This bmap keeps the system from needing to do the bmap later,
808 * perhaps when the system is attempting to do a sync. Since it
809 * is likely that the indirect block -- or whatever other datastructure
810 * that the filesystem needs is still in memory now, it is a good
811 * thing to do this. Note also, that if the pageout daemon is
812 * requesting a sync -- there might not be enough memory to do
813 * the bmap then... So, this is important to do.
815 if (bp->b_lblkno == bp->b_blkno) {
816 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
820 * Set the *dirty* buffer range based upon the VM system dirty pages.
825 * We need to do this here to satisfy the vnode_pager and the
826 * pageout daemon, so that it thinks that the pages have been
827 * "cleaned". Note that since the pages are in a delayed write
828 * buffer -- the VFS layer "will" see that the pages get written
829 * out on the next sync, or perhaps the cluster will be completed.
835 * Wakeup the buffer flushing daemon if we have a lot of dirty
836 * buffers (midpoint between our recovery point and our stall
839 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
842 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
843 * due to the softdep code.
850 * Turn buffer into delayed write request. We must clear B_READ and
851 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
852 * itself to properly update it in the dirty/clean lists. We mark it
853 * B_DONE to ensure that any asynchronization of the buffer properly
854 * clears B_DONE ( else a panic will occur later ).
856 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
857 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
858 * should only be called if the buffer is known-good.
860 * Since the buffer is not on a queue, we do not update the numfreebuffers
863 * Must be called at splbio().
864 * The buffer must be on QUEUE_NONE.
870 KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
871 bp->b_flags &= ~(B_READ|B_RELBUF);
873 if ((bp->b_flags & B_DELWRI) == 0) {
874 bp->b_flags |= B_DONE | B_DELWRI;
875 reassignbuf(bp, bp->b_vp);
877 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
884 * Clear B_DELWRI for buffer.
886 * Since the buffer is not on a queue, we do not update the numfreebuffers
889 * Must be called at splbio().
890 * The buffer must be on QUEUE_NONE.
897 KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
899 if (bp->b_flags & B_DELWRI) {
900 bp->b_flags &= ~B_DELWRI;
901 reassignbuf(bp, bp->b_vp);
903 numdirtywakeup(lodirtybuffers);
906 * Since it is now being written, we can clear its deferred write flag.
908 bp->b_flags &= ~B_DEFERRED;
914 * Asynchronous write. Start output on a buffer, but do not wait for
915 * it to complete. The buffer is released when the output completes.
917 * bwrite() ( or the VOP routine anyway ) is responsible for handling
918 * B_INVAL buffers. Not us.
921 bawrite(struct buf * bp)
923 bp->b_flags |= B_ASYNC;
924 (void) VOP_BWRITE(bp->b_vp, bp);
930 * Ordered write. Start output on a buffer, and flag it so that the
931 * device will write it in the order it was queued. The buffer is
932 * released when the output completes. bwrite() ( or the VOP routine
933 * anyway ) is responsible for handling B_INVAL buffers.
936 bowrite(struct buf * bp)
938 bp->b_flags |= B_ORDERED | B_ASYNC;
939 return (VOP_BWRITE(bp->b_vp, bp));
945 * Called prior to the locking of any vnodes when we are expecting to
946 * write. We do not want to starve the buffer cache with too many
947 * dirty buffers so we block here. By blocking prior to the locking
948 * of any vnodes we attempt to avoid the situation where a locked vnode
949 * prevents the various system daemons from flushing related buffers.
955 if (numdirtybuffers >= hidirtybuffers) {
959 while (numdirtybuffers >= hidirtybuffers) {
961 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
962 tsleep(&needsbuffer, (PRIBIO + 4), "flswai", 0);
969 * Return true if we have too many dirty buffers.
972 buf_dirty_count_severe(void)
974 return(numdirtybuffers >= hidirtybuffers);
980 * Release a busy buffer and, if requested, free its resources. The
981 * buffer will be stashed in the appropriate bufqueue[] allowing it
982 * to be accessed later as a cache entity or reused for other purposes.
985 brelse(struct buf * bp)
989 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
993 if (bp->b_flags & B_LOCKED)
994 bp->b_flags &= ~B_ERROR;
996 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
998 * Failed write, redirty. Must clear B_ERROR to prevent
999 * pages from being scrapped. If B_INVAL is set then
1000 * this case is not run and the next case is run to
1001 * destroy the buffer. B_INVAL can occur if the buffer
1002 * is outside the range supported by the underlying device.
1004 bp->b_flags &= ~B_ERROR;
1006 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
1007 (bp->b_bufsize <= 0)) {
1009 * Either a failed I/O or we were asked to free or not
1012 bp->b_flags |= B_INVAL;
1013 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1014 (*bioops.io_deallocate)(bp);
1015 if (bp->b_flags & B_DELWRI) {
1017 numdirtywakeup(lodirtybuffers);
1019 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
1020 if ((bp->b_flags & B_VMIO) == 0) {
1029 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1030 * is called with B_DELWRI set, the underlying pages may wind up
1031 * getting freed causing a previous write (bdwrite()) to get 'lost'
1032 * because pages associated with a B_DELWRI bp are marked clean.
1034 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1035 * if B_DELWRI is set.
1037 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1038 * on pages to return pages to the VM page queues.
1040 if (bp->b_flags & B_DELWRI)
1041 bp->b_flags &= ~B_RELBUF;
1042 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1043 bp->b_flags |= B_RELBUF;
1046 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1047 * constituted, not even NFS buffers now. Two flags effect this. If
1048 * B_INVAL, the struct buf is invalidated but the VM object is kept
1049 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1051 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1052 * invalidated. B_ERROR cannot be set for a failed write unless the
1053 * buffer is also B_INVAL because it hits the re-dirtying code above.
1055 * Normally we can do this whether a buffer is B_DELWRI or not. If
1056 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1057 * the commit state and we cannot afford to lose the buffer. If the
1058 * buffer has a background write in progress, we need to keep it
1059 * around to prevent it from being reconstituted and starting a second
1062 if ((bp->b_flags & B_VMIO)
1063 && !(bp->b_vp->v_tag == VT_NFS &&
1064 !vn_isdisk(bp->b_vp, NULL) &&
1065 (bp->b_flags & B_DELWRI))
1078 * Get the base offset and length of the buffer. Note that
1079 * in the VMIO case if the buffer block size is not
1080 * page-aligned then b_data pointer may not be page-aligned.
1081 * But our b_pages[] array *IS* page aligned.
1083 * block sizes less then DEV_BSIZE (usually 512) are not
1084 * supported due to the page granularity bits (m->valid,
1085 * m->dirty, etc...).
1087 * See man buf(9) for more information
1090 resid = bp->b_bufsize;
1091 foff = bp->b_offset;
1093 for (i = 0; i < bp->b_npages; i++) {
1095 vm_page_flag_clear(m, PG_ZERO);
1097 * If we hit a bogus page, fixup *all* of them
1100 if (m == bogus_page) {
1101 VOP_GETVOBJECT(vp, &obj);
1102 poff = OFF_TO_IDX(bp->b_offset);
1104 for (j = i; j < bp->b_npages; j++) {
1107 mtmp = bp->b_pages[j];
1108 if (mtmp == bogus_page) {
1109 mtmp = vm_page_lookup(obj, poff + j);
1111 panic("brelse: page missing\n");
1113 bp->b_pages[j] = mtmp;
1117 if ((bp->b_flags & B_INVAL) == 0) {
1118 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
1122 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1123 int poffset = foff & PAGE_MASK;
1124 int presid = resid > (PAGE_SIZE - poffset) ?
1125 (PAGE_SIZE - poffset) : resid;
1127 KASSERT(presid >= 0, ("brelse: extra page"));
1128 vm_page_set_invalid(m, poffset, presid);
1130 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1131 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1134 if (bp->b_flags & (B_INVAL | B_RELBUF))
1135 vfs_vmio_release(bp);
1137 } else if (bp->b_flags & B_VMIO) {
1139 if (bp->b_flags & (B_INVAL | B_RELBUF))
1140 vfs_vmio_release(bp);
1144 if (bp->b_qindex != QUEUE_NONE)
1145 panic("brelse: free buffer onto another queue???");
1146 if (BUF_REFCNT(bp) > 1) {
1147 /* Temporary panic to verify exclusive locking */
1148 /* This panic goes away when we allow shared refs */
1149 panic("brelse: multiple refs");
1150 /* do not release to free list */
1158 /* buffers with no memory */
1159 if (bp->b_bufsize == 0) {
1160 bp->b_flags |= B_INVAL;
1161 bp->b_xflags &= ~BX_BKGRDWRITE;
1162 if (bp->b_xflags & BX_BKGRDINPROG)
1163 panic("losing buffer 1");
1164 if (bp->b_kvasize) {
1165 bp->b_qindex = QUEUE_EMPTYKVA;
1167 bp->b_qindex = QUEUE_EMPTY;
1169 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1170 LIST_REMOVE(bp, b_hash);
1171 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1173 /* buffers with junk contents */
1174 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1175 bp->b_flags |= B_INVAL;
1176 bp->b_xflags &= ~BX_BKGRDWRITE;
1177 if (bp->b_xflags & BX_BKGRDINPROG)
1178 panic("losing buffer 2");
1179 bp->b_qindex = QUEUE_CLEAN;
1180 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1181 LIST_REMOVE(bp, b_hash);
1182 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1185 /* buffers that are locked */
1186 } else if (bp->b_flags & B_LOCKED) {
1187 bp->b_qindex = QUEUE_LOCKED;
1188 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1190 /* remaining buffers */
1192 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1193 case B_DELWRI | B_AGE:
1194 bp->b_qindex = QUEUE_DIRTY;
1195 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1198 bp->b_qindex = QUEUE_DIRTY;
1199 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1202 bp->b_qindex = QUEUE_CLEAN;
1203 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1206 bp->b_qindex = QUEUE_CLEAN;
1207 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1213 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1214 * on the correct queue.
1216 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1220 * Fixup numfreebuffers count. The bp is on an appropriate queue
1221 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1222 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1223 * if B_INVAL is set ).
1226 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1230 * Something we can maybe free or reuse
1232 if (bp->b_bufsize || bp->b_kvasize)
1237 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1238 B_DIRECT | B_NOWDRAIN);
1243 * Release a buffer back to the appropriate queue but do not try to free
1244 * it. The buffer is expected to be used again soon.
1246 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1247 * biodone() to requeue an async I/O on completion. It is also used when
1248 * known good buffers need to be requeued but we think we may need the data
1251 * XXX we should be able to leave the B_RELBUF hint set on completion.
1254 bqrelse(struct buf * bp)
1260 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1262 if (bp->b_qindex != QUEUE_NONE)
1263 panic("bqrelse: free buffer onto another queue???");
1264 if (BUF_REFCNT(bp) > 1) {
1265 /* do not release to free list */
1266 panic("bqrelse: multiple refs");
1271 if (bp->b_flags & B_LOCKED) {
1272 bp->b_flags &= ~B_ERROR;
1273 bp->b_qindex = QUEUE_LOCKED;
1274 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1275 /* buffers with stale but valid contents */
1276 } else if (bp->b_flags & B_DELWRI) {
1277 bp->b_qindex = QUEUE_DIRTY;
1278 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1279 } else if (vm_page_count_severe()) {
1281 * We are too low on memory, we have to try to free the
1282 * buffer (most importantly: the wired pages making up its
1283 * backing store) *now*.
1289 bp->b_qindex = QUEUE_CLEAN;
1290 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1293 if ((bp->b_flags & B_LOCKED) == 0 &&
1294 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1299 * Something we can maybe free or reuse.
1301 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1306 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1311 vfs_vmio_release(bp)
1318 for (i = 0; i < bp->b_npages; i++) {
1320 bp->b_pages[i] = NULL;
1322 * In order to keep page LRU ordering consistent, put
1323 * everything on the inactive queue.
1325 vm_page_unwire(m, 0);
1327 * We don't mess with busy pages, it is
1328 * the responsibility of the process that
1329 * busied the pages to deal with them.
1331 if ((m->flags & PG_BUSY) || (m->busy != 0))
1334 if (m->wire_count == 0) {
1335 vm_page_flag_clear(m, PG_ZERO);
1337 * Might as well free the page if we can and it has
1338 * no valid data. We also free the page if the
1339 * buffer was used for direct I/O.
1341 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1343 vm_page_protect(m, VM_PROT_NONE);
1345 } else if (bp->b_flags & B_DIRECT) {
1346 vm_page_try_to_free(m);
1347 } else if (vm_page_count_severe()) {
1348 vm_page_try_to_cache(m);
1353 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1354 if (bp->b_bufsize) {
1359 bp->b_flags &= ~B_VMIO;
1365 * Check to see if a block is currently memory resident.
1368 gbincore(struct vnode * vp, daddr_t blkno)
1371 struct bufhashhdr *bh;
1373 bh = bufhash(vp, blkno);
1375 /* Search hash chain */
1376 LIST_FOREACH(bp, bh, b_hash) {
1378 if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1379 (bp->b_flags & B_INVAL) == 0) {
1389 * Implement clustered async writes for clearing out B_DELWRI buffers.
1390 * This is much better then the old way of writing only one buffer at
1391 * a time. Note that we may not be presented with the buffers in the
1392 * correct order, so we search for the cluster in both directions.
1395 vfs_bio_awrite(struct buf * bp)
1399 daddr_t lblkno = bp->b_lblkno;
1400 struct vnode *vp = bp->b_vp;
1410 * right now we support clustered writing only to regular files. If
1411 * we find a clusterable block we could be in the middle of a cluster
1412 * rather then at the beginning.
1414 if ((vp->v_type == VREG) &&
1415 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1416 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1418 size = vp->v_mount->mnt_stat.f_iosize;
1419 maxcl = MAXPHYS / size;
1421 for (i = 1; i < maxcl; i++) {
1422 if ((bpa = gbincore(vp, lblkno + i)) &&
1423 BUF_REFCNT(bpa) == 0 &&
1424 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1425 (B_DELWRI | B_CLUSTEROK)) &&
1426 (bpa->b_bufsize == size)) {
1427 if ((bpa->b_blkno == bpa->b_lblkno) ||
1429 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1435 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1436 if ((bpa = gbincore(vp, lblkno - j)) &&
1437 BUF_REFCNT(bpa) == 0 &&
1438 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1439 (B_DELWRI | B_CLUSTEROK)) &&
1440 (bpa->b_bufsize == size)) {
1441 if ((bpa->b_blkno == bpa->b_lblkno) ||
1443 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1452 * this is a possible cluster write
1455 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1461 BUF_LOCK(bp, LK_EXCLUSIVE);
1463 bp->b_flags |= B_ASYNC;
1467 * default (old) behavior, writing out only one block
1469 * XXX returns b_bufsize instead of b_bcount for nwritten?
1471 nwritten = bp->b_bufsize;
1472 (void) VOP_BWRITE(bp->b_vp, bp);
1480 * Find and initialize a new buffer header, freeing up existing buffers
1481 * in the bufqueues as necessary. The new buffer is returned locked.
1483 * Important: B_INVAL is not set. If the caller wishes to throw the
1484 * buffer away, the caller must set B_INVAL prior to calling brelse().
1487 * We have insufficient buffer headers
1488 * We have insufficient buffer space
1489 * buffer_map is too fragmented ( space reservation fails )
1490 * If we have to flush dirty buffers ( but we try to avoid this )
1492 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1493 * Instead we ask the buf daemon to do it for us. We attempt to
1494 * avoid piecemeal wakeups of the pageout daemon.
1498 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1504 static int flushingbufs;
1507 * We can't afford to block since we might be holding a vnode lock,
1508 * which may prevent system daemons from running. We deal with
1509 * low-memory situations by proactively returning memory and running
1510 * async I/O rather then sync I/O.
1514 --getnewbufrestarts;
1516 ++getnewbufrestarts;
1519 * Setup for scan. If we do not have enough free buffers,
1520 * we setup a degenerate case that immediately fails. Note
1521 * that if we are specially marked process, we are allowed to
1522 * dip into our reserves.
1524 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1526 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1527 * However, there are a number of cases (defragging, reusing, ...)
1528 * where we cannot backup.
1530 nqindex = QUEUE_EMPTYKVA;
1531 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1535 * If no EMPTYKVA buffers and we are either
1536 * defragging or reusing, locate a CLEAN buffer
1537 * to free or reuse. If bufspace useage is low
1538 * skip this step so we can allocate a new buffer.
1540 if (defrag || bufspace >= lobufspace) {
1541 nqindex = QUEUE_CLEAN;
1542 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1546 * If we could not find or were not allowed to reuse a
1547 * CLEAN buffer, check to see if it is ok to use an EMPTY
1548 * buffer. We can only use an EMPTY buffer if allocating
1549 * its KVA would not otherwise run us out of buffer space.
1551 if (nbp == NULL && defrag == 0 &&
1552 bufspace + maxsize < hibufspace) {
1553 nqindex = QUEUE_EMPTY;
1554 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1559 * Run scan, possibly freeing data and/or kva mappings on the fly
1563 while ((bp = nbp) != NULL) {
1564 int qindex = nqindex;
1567 * Calculate next bp ( we can only use it if we do not block
1568 * or do other fancy things ).
1570 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1573 nqindex = QUEUE_EMPTYKVA;
1574 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1577 case QUEUE_EMPTYKVA:
1578 nqindex = QUEUE_CLEAN;
1579 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1593 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1596 * Note: we no longer distinguish between VMIO and non-VMIO
1600 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1603 * If we are defragging then we need a buffer with
1604 * b_kvasize != 0. XXX this situation should no longer
1605 * occur, if defrag is non-zero the buffer's b_kvasize
1606 * should also be non-zero at this point. XXX
1608 if (defrag && bp->b_kvasize == 0) {
1609 printf("Warning: defrag empty buffer %p\n", bp);
1614 * Start freeing the bp. This is somewhat involved. nbp
1615 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1618 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1619 panic("getnewbuf: locked buf");
1622 if (qindex == QUEUE_CLEAN) {
1623 if (bp->b_flags & B_VMIO) {
1624 bp->b_flags &= ~B_ASYNC;
1625 vfs_vmio_release(bp);
1632 * NOTE: nbp is now entirely invalid. We can only restart
1633 * the scan from this point on.
1635 * Get the rest of the buffer freed up. b_kva* is still
1636 * valid after this operation.
1639 if (bp->b_rcred != NOCRED) {
1640 crfree(bp->b_rcred);
1641 bp->b_rcred = NOCRED;
1643 if (bp->b_wcred != NOCRED) {
1644 crfree(bp->b_wcred);
1645 bp->b_wcred = NOCRED;
1647 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1648 (*bioops.io_deallocate)(bp);
1649 if (bp->b_xflags & BX_BKGRDINPROG)
1650 panic("losing buffer 3");
1651 LIST_REMOVE(bp, b_hash);
1652 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1661 bp->b_blkno = bp->b_lblkno = 0;
1662 bp->b_offset = NOOFFSET;
1668 bp->b_dirtyoff = bp->b_dirtyend = 0;
1670 LIST_INIT(&bp->b_dep);
1673 * If we are defragging then free the buffer.
1676 bp->b_flags |= B_INVAL;
1684 * If we are overcomitted then recover the buffer and its
1685 * KVM space. This occurs in rare situations when multiple
1686 * processes are blocked in getnewbuf() or allocbuf().
1688 if (bufspace >= hibufspace)
1690 if (flushingbufs && bp->b_kvasize != 0) {
1691 bp->b_flags |= B_INVAL;
1696 if (bufspace < lobufspace)
1702 * If we exhausted our list, sleep as appropriate. We may have to
1703 * wakeup various daemons and write out some dirty buffers.
1705 * Generally we are sleeping due to insufficient buffer space.
1713 flags = VFS_BIO_NEED_BUFSPACE;
1715 } else if (bufspace >= hibufspace) {
1717 flags = VFS_BIO_NEED_BUFSPACE;
1720 flags = VFS_BIO_NEED_ANY;
1723 bd_speedup(); /* heeeelp */
1725 needsbuffer |= flags;
1726 while (needsbuffer & flags) {
1727 if (tsleep(&needsbuffer, (PRIBIO + 4) | slpflag,
1733 * We finally have a valid bp. We aren't quite out of the
1734 * woods, we still have to reserve kva space. In order
1735 * to keep fragmentation sane we only allocate kva in
1738 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1740 if (maxsize != bp->b_kvasize) {
1741 vm_offset_t addr = 0;
1745 vm_map_lock(buffer_map);
1747 if (vm_map_findspace(buffer_map,
1748 vm_map_min(buffer_map), maxsize, &addr)) {
1750 * Uh oh. Buffer map is to fragmented. We
1751 * must defragment the map.
1753 vm_map_unlock(buffer_map);
1756 bp->b_flags |= B_INVAL;
1761 vm_map_insert(buffer_map, NULL, 0,
1762 addr, addr + maxsize,
1763 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1765 bp->b_kvabase = (caddr_t) addr;
1766 bp->b_kvasize = maxsize;
1767 bufspace += bp->b_kvasize;
1770 vm_map_unlock(buffer_map);
1772 bp->b_data = bp->b_kvabase;
1780 * buffer flushing daemon. Buffers are normally flushed by the
1781 * update daemon but if it cannot keep up this process starts to
1782 * take the load in an attempt to prevent getnewbuf() from blocking.
1785 static struct proc *bufdaemonproc;
1787 static struct kproc_desc buf_kp = {
1792 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1800 * This process needs to be suspended prior to shutdown sync.
1802 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, bufdaemonproc,
1806 * This process is allowed to take the buffer cache to the limit
1811 kproc_suspend_loop(bufdaemonproc);
1814 * Do the flush. Limit the amount of in-transit I/O we
1815 * allow to build up, otherwise we would completely saturate
1816 * the I/O system. Wakeup any waiting processes before we
1817 * normally would so they can run in parallel with our drain.
1819 while (numdirtybuffers > lodirtybuffers) {
1820 if (flushbufqueues() == 0)
1822 waitrunningbufspace();
1823 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1827 * Only clear bd_request if we have reached our low water
1828 * mark. The buf_daemon normally waits 5 seconds and
1829 * then incrementally flushes any dirty buffers that have
1830 * built up, within reason.
1832 * If we were unable to hit our low water mark and couldn't
1833 * find any flushable buffers, we sleep half a second.
1834 * Otherwise we loop immediately.
1836 if (numdirtybuffers <= lodirtybuffers) {
1838 * We reached our low water mark, reset the
1839 * request and sleep until we are needed again.
1840 * The sleep is just so the suspend code works.
1843 tsleep(&bd_request, PVM, "psleep", hz);
1846 * We couldn't find any flushable dirty buffers but
1847 * still have too many dirty buffers, we
1848 * have to sleep and try again. (rare)
1850 tsleep(&bd_request, PVM, "qsleep", hz / 2);
1858 * Try to flush a buffer in the dirty queue. We must be careful to
1859 * free up B_INVAL buffers instead of write them, which NFS is
1860 * particularly sensitive to.
1864 flushbufqueues(void)
1869 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1872 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1873 if ((bp->b_flags & B_DELWRI) != 0 &&
1874 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1875 if (bp->b_flags & B_INVAL) {
1876 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1877 panic("flushbufqueues: locked buf");
1883 if (LIST_FIRST(&bp->b_dep) != NULL &&
1884 bioops.io_countdeps &&
1885 (bp->b_flags & B_DEFERRED) == 0 &&
1886 (*bioops.io_countdeps)(bp, 0)) {
1887 TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
1889 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
1891 bp->b_flags |= B_DEFERRED;
1892 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1899 bp = TAILQ_NEXT(bp, b_freelist);
1905 * Check to see if a block is currently memory resident.
1908 incore(struct vnode * vp, daddr_t blkno)
1913 bp = gbincore(vp, blkno);
1919 * Returns true if no I/O is needed to access the
1920 * associated VM object. This is like incore except
1921 * it also hunts around in the VM system for the data.
1925 inmem(struct vnode * vp, daddr_t blkno)
1928 vm_offset_t toff, tinc, size;
1932 if (incore(vp, blkno))
1934 if (vp->v_mount == NULL)
1936 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
1940 if (size > vp->v_mount->mnt_stat.f_iosize)
1941 size = vp->v_mount->mnt_stat.f_iosize;
1942 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
1944 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1945 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1949 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
1950 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
1951 if (vm_page_is_valid(m,
1952 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
1961 * Sets the dirty range for a buffer based on the status of the dirty
1962 * bits in the pages comprising the buffer.
1964 * The range is limited to the size of the buffer.
1966 * This routine is primarily used by NFS, but is generalized for the
1970 vfs_setdirty(struct buf *bp)
1976 * Degenerate case - empty buffer
1979 if (bp->b_bufsize == 0)
1983 * We qualify the scan for modified pages on whether the
1984 * object has been flushed yet. The OBJ_WRITEABLE flag
1985 * is not cleared simply by protecting pages off.
1988 if ((bp->b_flags & B_VMIO) == 0)
1991 object = bp->b_pages[0]->object;
1993 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
1994 printf("Warning: object %p writeable but not mightbedirty\n", object);
1995 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
1996 printf("Warning: object %p mightbedirty but not writeable\n", object);
1998 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
1999 vm_offset_t boffset;
2000 vm_offset_t eoffset;
2003 * test the pages to see if they have been modified directly
2004 * by users through the VM system.
2006 for (i = 0; i < bp->b_npages; i++) {
2007 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
2008 vm_page_test_dirty(bp->b_pages[i]);
2012 * Calculate the encompassing dirty range, boffset and eoffset,
2013 * (eoffset - boffset) bytes.
2016 for (i = 0; i < bp->b_npages; i++) {
2017 if (bp->b_pages[i]->dirty)
2020 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2022 for (i = bp->b_npages - 1; i >= 0; --i) {
2023 if (bp->b_pages[i]->dirty) {
2027 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2030 * Fit it to the buffer.
2033 if (eoffset > bp->b_bcount)
2034 eoffset = bp->b_bcount;
2037 * If we have a good dirty range, merge with the existing
2041 if (boffset < eoffset) {
2042 if (bp->b_dirtyoff > boffset)
2043 bp->b_dirtyoff = boffset;
2044 if (bp->b_dirtyend < eoffset)
2045 bp->b_dirtyend = eoffset;
2053 * Get a block given a specified block and offset into a file/device.
2054 * The buffers B_DONE bit will be cleared on return, making it almost
2055 * ready for an I/O initiation. B_INVAL may or may not be set on
2056 * return. The caller should clear B_INVAL prior to initiating a
2059 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2060 * an existing buffer.
2062 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2063 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2064 * and then cleared based on the backing VM. If the previous buffer is
2065 * non-0-sized but invalid, B_CACHE will be cleared.
2067 * If getblk() must create a new buffer, the new buffer is returned with
2068 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2069 * case it is returned with B_INVAL clear and B_CACHE set based on the
2072 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2073 * B_CACHE bit is clear.
2075 * What this means, basically, is that the caller should use B_CACHE to
2076 * determine whether the buffer is fully valid or not and should clear
2077 * B_INVAL prior to issuing a read. If the caller intends to validate
2078 * the buffer by loading its data area with something, the caller needs
2079 * to clear B_INVAL. If the caller does this without issuing an I/O,
2080 * the caller should set B_CACHE ( as an optimization ), else the caller
2081 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2082 * a write attempt or if it was a successfull read. If the caller
2083 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2084 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2087 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2091 struct bufhashhdr *bh;
2093 if (size > MAXBSIZE)
2094 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
2099 * Block if we are low on buffers. Certain processes are allowed
2100 * to completely exhaust the buffer cache.
2102 * If this check ever becomes a bottleneck it may be better to
2103 * move it into the else, when gbincore() fails. At the moment
2104 * it isn't a problem.
2106 * XXX remove, we cannot afford to block anywhere if holding a vnode
2107 * lock in low-memory situation, so take it to the max.
2109 if (numfreebuffers == 0) {
2112 needsbuffer |= VFS_BIO_NEED_ANY;
2113 tsleep(&needsbuffer, (PRIBIO + 4) | slpflag, "newbuf",
2117 if ((bp = gbincore(vp, blkno))) {
2119 * Buffer is in-core. If the buffer is not busy, it must
2123 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2124 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2125 "getblk", slpflag, slptimeo) == ENOLCK)
2128 return (struct buf *) NULL;
2132 * The buffer is locked. B_CACHE is cleared if the buffer is
2133 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2134 * and for a VMIO buffer B_CACHE is adjusted according to the
2137 if (bp->b_flags & B_INVAL)
2138 bp->b_flags &= ~B_CACHE;
2139 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2140 bp->b_flags |= B_CACHE;
2144 * check for size inconsistancies for non-VMIO case.
2147 if (bp->b_bcount != size) {
2148 if ((bp->b_flags & B_VMIO) == 0 ||
2149 (size > bp->b_kvasize)) {
2150 if (bp->b_flags & B_DELWRI) {
2151 bp->b_flags |= B_NOCACHE;
2152 VOP_BWRITE(bp->b_vp, bp);
2154 if ((bp->b_flags & B_VMIO) &&
2155 (LIST_FIRST(&bp->b_dep) == NULL)) {
2156 bp->b_flags |= B_RELBUF;
2159 bp->b_flags |= B_NOCACHE;
2160 VOP_BWRITE(bp->b_vp, bp);
2168 * If the size is inconsistant in the VMIO case, we can resize
2169 * the buffer. This might lead to B_CACHE getting set or
2170 * cleared. If the size has not changed, B_CACHE remains
2171 * unchanged from its previous state.
2174 if (bp->b_bcount != size)
2177 KASSERT(bp->b_offset != NOOFFSET,
2178 ("getblk: no buffer offset"));
2181 * A buffer with B_DELWRI set and B_CACHE clear must
2182 * be committed before we can return the buffer in
2183 * order to prevent the caller from issuing a read
2184 * ( due to B_CACHE not being set ) and overwriting
2187 * Most callers, including NFS and FFS, need this to
2188 * operate properly either because they assume they
2189 * can issue a read if B_CACHE is not set, or because
2190 * ( for example ) an uncached B_DELWRI might loop due
2191 * to softupdates re-dirtying the buffer. In the latter
2192 * case, B_CACHE is set after the first write completes,
2193 * preventing further loops.
2195 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2196 * above while extending the buffer, we cannot allow the
2197 * buffer to remain with B_CACHE set after the write
2198 * completes or it will represent a corrupt state. To
2199 * deal with this we set B_NOCACHE to scrap the buffer
2202 * We might be able to do something fancy, like setting
2203 * B_CACHE in bwrite() except if B_DELWRI is already set,
2204 * so the below call doesn't set B_CACHE, but that gets real
2205 * confusing. This is much easier.
2208 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2209 bp->b_flags |= B_NOCACHE;
2210 VOP_BWRITE(bp->b_vp, bp);
2215 bp->b_flags &= ~B_DONE;
2218 * Buffer is not in-core, create new buffer. The buffer
2219 * returned by getnewbuf() is locked. Note that the returned
2220 * buffer is also considered valid (not marked B_INVAL).
2222 int bsize, maxsize, vmio;
2225 if (vn_isdisk(vp, NULL))
2227 else if (vp->v_mountedhere)
2228 bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2229 else if (vp->v_mount)
2230 bsize = vp->v_mount->mnt_stat.f_iosize;
2234 offset = (off_t)blkno * bsize;
2235 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2236 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2237 maxsize = imax(maxsize, bsize);
2239 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2240 if (slpflag || slptimeo) {
2248 * This code is used to make sure that a buffer is not
2249 * created while the getnewbuf routine is blocked.
2250 * This can be a problem whether the vnode is locked or not.
2251 * If the buffer is created out from under us, we have to
2252 * throw away the one we just created. There is now window
2253 * race because we are safely running at splbio() from the
2254 * point of the duplicate buffer creation through to here,
2255 * and we've locked the buffer.
2257 if (gbincore(vp, blkno)) {
2258 bp->b_flags |= B_INVAL;
2264 * Insert the buffer into the hash, so that it can
2265 * be found by incore.
2267 bp->b_blkno = bp->b_lblkno = blkno;
2268 bp->b_offset = offset;
2271 LIST_REMOVE(bp, b_hash);
2272 bh = bufhash(vp, blkno);
2273 LIST_INSERT_HEAD(bh, bp, b_hash);
2276 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2277 * buffer size starts out as 0, B_CACHE will be set by
2278 * allocbuf() for the VMIO case prior to it testing the
2279 * backing store for validity.
2283 bp->b_flags |= B_VMIO;
2284 #if defined(VFS_BIO_DEBUG)
2285 if (vp->v_type != VREG && vp->v_type != VBLK)
2286 printf("getblk: vmioing file type %d???\n", vp->v_type);
2289 bp->b_flags &= ~B_VMIO;
2295 bp->b_flags &= ~B_DONE;
2301 * Get an empty, disassociated buffer of given size. The buffer is initially
2311 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2314 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2317 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2323 * This code constitutes the buffer memory from either anonymous system
2324 * memory (in the case of non-VMIO operations) or from an associated
2325 * VM object (in the case of VMIO operations). This code is able to
2326 * resize a buffer up or down.
2328 * Note that this code is tricky, and has many complications to resolve
2329 * deadlock or inconsistant data situations. Tread lightly!!!
2330 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2331 * the caller. Calling this code willy nilly can result in the loss of data.
2333 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2334 * B_CACHE for the non-VMIO case.
2338 allocbuf(struct buf *bp, int size)
2340 int newbsize, mbsize;
2343 if (BUF_REFCNT(bp) == 0)
2344 panic("allocbuf: buffer not busy");
2346 if (bp->b_kvasize < size)
2347 panic("allocbuf: buffer too small");
2349 if ((bp->b_flags & B_VMIO) == 0) {
2353 * Just get anonymous memory from the kernel. Don't
2354 * mess with B_CACHE.
2356 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2357 #if !defined(NO_B_MALLOC)
2358 if (bp->b_flags & B_MALLOC)
2362 newbsize = round_page(size);
2364 if (newbsize < bp->b_bufsize) {
2365 #if !defined(NO_B_MALLOC)
2367 * malloced buffers are not shrunk
2369 if (bp->b_flags & B_MALLOC) {
2371 bp->b_bcount = size;
2373 free(bp->b_data, M_BIOBUF);
2374 if (bp->b_bufsize) {
2375 bufmallocspace -= bp->b_bufsize;
2379 bp->b_data = bp->b_kvabase;
2381 bp->b_flags &= ~B_MALLOC;
2388 (vm_offset_t) bp->b_data + newbsize,
2389 (vm_offset_t) bp->b_data + bp->b_bufsize);
2390 } else if (newbsize > bp->b_bufsize) {
2391 #if !defined(NO_B_MALLOC)
2393 * We only use malloced memory on the first allocation.
2394 * and revert to page-allocated memory when the buffer
2397 if ( (bufmallocspace < maxbufmallocspace) &&
2398 (bp->b_bufsize == 0) &&
2399 (mbsize <= PAGE_SIZE/2)) {
2401 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2402 bp->b_bufsize = mbsize;
2403 bp->b_bcount = size;
2404 bp->b_flags |= B_MALLOC;
2405 bufmallocspace += mbsize;
2411 #if !defined(NO_B_MALLOC)
2413 * If the buffer is growing on its other-than-first allocation,
2414 * then we revert to the page-allocation scheme.
2416 if (bp->b_flags & B_MALLOC) {
2417 origbuf = bp->b_data;
2418 origbufsize = bp->b_bufsize;
2419 bp->b_data = bp->b_kvabase;
2420 if (bp->b_bufsize) {
2421 bufmallocspace -= bp->b_bufsize;
2425 bp->b_flags &= ~B_MALLOC;
2426 newbsize = round_page(newbsize);
2431 (vm_offset_t) bp->b_data + bp->b_bufsize,
2432 (vm_offset_t) bp->b_data + newbsize);
2433 #if !defined(NO_B_MALLOC)
2435 bcopy(origbuf, bp->b_data, origbufsize);
2436 free(origbuf, M_BIOBUF);
2444 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2445 desiredpages = (size == 0) ? 0 :
2446 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2448 #if !defined(NO_B_MALLOC)
2449 if (bp->b_flags & B_MALLOC)
2450 panic("allocbuf: VMIO buffer can't be malloced");
2453 * Set B_CACHE initially if buffer is 0 length or will become
2456 if (size == 0 || bp->b_bufsize == 0)
2457 bp->b_flags |= B_CACHE;
2459 if (newbsize < bp->b_bufsize) {
2461 * DEV_BSIZE aligned new buffer size is less then the
2462 * DEV_BSIZE aligned existing buffer size. Figure out
2463 * if we have to remove any pages.
2465 if (desiredpages < bp->b_npages) {
2466 for (i = desiredpages; i < bp->b_npages; i++) {
2468 * the page is not freed here -- it
2469 * is the responsibility of
2470 * vnode_pager_setsize
2473 KASSERT(m != bogus_page,
2474 ("allocbuf: bogus page found"));
2475 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2478 bp->b_pages[i] = NULL;
2479 vm_page_unwire(m, 0);
2481 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2482 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2483 bp->b_npages = desiredpages;
2485 } else if (size > bp->b_bcount) {
2487 * We are growing the buffer, possibly in a
2488 * byte-granular fashion.
2496 * Step 1, bring in the VM pages from the object,
2497 * allocating them if necessary. We must clear
2498 * B_CACHE if these pages are not valid for the
2499 * range covered by the buffer.
2503 VOP_GETVOBJECT(vp, &obj);
2505 while (bp->b_npages < desiredpages) {
2509 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2510 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2512 * note: must allocate system pages
2513 * since blocking here could intefere
2514 * with paging I/O, no matter which
2517 m = vm_page_alloc(obj, pi, VM_ALLOC_SYSTEM);
2520 vm_pageout_deficit += desiredpages - bp->b_npages;
2524 bp->b_flags &= ~B_CACHE;
2525 bp->b_pages[bp->b_npages] = m;
2532 * We found a page. If we have to sleep on it,
2533 * retry because it might have gotten freed out
2536 * We can only test PG_BUSY here. Blocking on
2537 * m->busy might lead to a deadlock:
2539 * vm_fault->getpages->cluster_read->allocbuf
2543 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2547 * We have a good page. Should we wakeup the
2550 if ((curproc != pageproc) &&
2551 ((m->queue - m->pc) == PQ_CACHE) &&
2552 ((cnt.v_free_count + cnt.v_cache_count) <
2553 (cnt.v_free_min + cnt.v_cache_min))) {
2554 pagedaemon_wakeup();
2556 vm_page_flag_clear(m, PG_ZERO);
2558 bp->b_pages[bp->b_npages] = m;
2563 * Step 2. We've loaded the pages into the buffer,
2564 * we have to figure out if we can still have B_CACHE
2565 * set. Note that B_CACHE is set according to the
2566 * byte-granular range ( bcount and size ), new the
2567 * aligned range ( newbsize ).
2569 * The VM test is against m->valid, which is DEV_BSIZE
2570 * aligned. Needless to say, the validity of the data
2571 * needs to also be DEV_BSIZE aligned. Note that this
2572 * fails with NFS if the server or some other client
2573 * extends the file's EOF. If our buffer is resized,
2574 * B_CACHE may remain set! XXX
2577 toff = bp->b_bcount;
2578 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2580 while ((bp->b_flags & B_CACHE) && toff < size) {
2583 if (tinc > (size - toff))
2586 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2601 * Step 3, fixup the KVM pmap. Remember that
2602 * bp->b_data is relative to bp->b_offset, but
2603 * bp->b_offset may be offset into the first page.
2606 bp->b_data = (caddr_t)
2607 trunc_page((vm_offset_t)bp->b_data);
2609 (vm_offset_t)bp->b_data,
2613 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2614 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2617 if (newbsize < bp->b_bufsize)
2619 bp->b_bufsize = newbsize; /* actual buffer allocation */
2620 bp->b_bcount = size; /* requested buffer size */
2627 * Wait for buffer I/O completion, returning error status. The buffer
2628 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2629 * error and cleared.
2632 biowait(register struct buf * bp)
2637 while ((bp->b_flags & B_DONE) == 0) {
2638 #if defined(NO_SCHEDULE_MODS)
2639 tsleep(bp, PRIBIO, "biowait", 0);
2641 if (bp->b_flags & B_READ)
2642 tsleep(bp, PRIBIO, "biord", 0);
2644 tsleep(bp, PRIBIO, "biowr", 0);
2648 if (bp->b_flags & B_EINTR) {
2649 bp->b_flags &= ~B_EINTR;
2652 if (bp->b_flags & B_ERROR) {
2653 return (bp->b_error ? bp->b_error : EIO);
2662 * Finish I/O on a buffer, optionally calling a completion function.
2663 * This is usually called from an interrupt so process blocking is
2666 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2667 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2668 * assuming B_INVAL is clear.
2670 * For the VMIO case, we set B_CACHE if the op was a read and no
2671 * read error occured, or if the op was a write. B_CACHE is never
2672 * set if the buffer is invalid or otherwise uncacheable.
2674 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2675 * initiator to leave B_INVAL set to brelse the buffer out of existance
2676 * in the biodone routine.
2679 biodone(register struct buf * bp)
2685 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2686 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2688 bp->b_flags |= B_DONE;
2689 runningbufwakeup(bp);
2691 if (bp->b_flags & B_FREEBUF) {
2697 if ((bp->b_flags & B_READ) == 0) {
2701 /* call optional completion function if requested */
2702 if (bp->b_flags & B_CALL) {
2703 bp->b_flags &= ~B_CALL;
2704 (*bp->b_iodone) (bp);
2708 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2709 (*bioops.io_complete)(bp);
2711 if (bp->b_flags & B_VMIO) {
2717 struct vnode *vp = bp->b_vp;
2719 error = VOP_GETVOBJECT(vp, &obj);
2721 #if defined(VFS_BIO_DEBUG)
2722 if (vp->v_usecount == 0) {
2723 panic("biodone: zero vnode ref count");
2727 panic("biodone: missing VM object");
2730 if ((vp->v_flag & VOBJBUF) == 0) {
2731 panic("biodone: vnode is not setup for merged cache");
2735 foff = bp->b_offset;
2736 KASSERT(bp->b_offset != NOOFFSET,
2737 ("biodone: no buffer offset"));
2740 panic("biodone: no object");
2742 #if defined(VFS_BIO_DEBUG)
2743 if (obj->paging_in_progress < bp->b_npages) {
2744 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2745 obj->paging_in_progress, bp->b_npages);
2750 * Set B_CACHE if the op was a normal read and no error
2751 * occured. B_CACHE is set for writes in the b*write()
2754 iosize = bp->b_bcount - bp->b_resid;
2755 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2756 bp->b_flags |= B_CACHE;
2759 for (i = 0; i < bp->b_npages; i++) {
2763 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2768 * cleanup bogus pages, restoring the originals
2771 if (m == bogus_page) {
2773 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2775 panic("biodone: page disappeared");
2777 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2779 #if defined(VFS_BIO_DEBUG)
2780 if (OFF_TO_IDX(foff) != m->pindex) {
2782 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2783 (unsigned long)foff, m->pindex);
2788 * In the write case, the valid and clean bits are
2789 * already changed correctly ( see bdwrite() ), so we
2790 * only need to do this here in the read case.
2792 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2793 vfs_page_set_valid(bp, foff, i, m);
2795 vm_page_flag_clear(m, PG_ZERO);
2798 * when debugging new filesystems or buffer I/O methods, this
2799 * is the most common error that pops up. if you see this, you
2800 * have not set the page busy flag correctly!!!
2803 printf("biodone: page busy < 0, "
2804 "pindex: %d, foff: 0x(%x,%x), "
2805 "resid: %d, index: %d\n",
2806 (int) m->pindex, (int)(foff >> 32),
2807 (int) foff & 0xffffffff, resid, i);
2808 if (!vn_isdisk(vp, NULL))
2809 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2810 bp->b_vp->v_mount->mnt_stat.f_iosize,
2812 bp->b_flags, bp->b_npages);
2814 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2816 bp->b_flags, bp->b_npages);
2817 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2818 m->valid, m->dirty, m->wire_count);
2819 panic("biodone: page busy < 0\n");
2821 vm_page_io_finish(m);
2822 vm_object_pip_subtract(obj, 1);
2823 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2827 vm_object_pip_wakeupn(obj, 0);
2831 * For asynchronous completions, release the buffer now. The brelse
2832 * will do a wakeup there if necessary - so no need to do a wakeup
2833 * here in the async case. The sync case always needs to do a wakeup.
2836 if (bp->b_flags & B_ASYNC) {
2837 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2848 * This routine is called in lieu of iodone in the case of
2849 * incomplete I/O. This keeps the busy status for pages
2853 vfs_unbusy_pages(struct buf * bp)
2857 runningbufwakeup(bp);
2858 if (bp->b_flags & B_VMIO) {
2859 struct vnode *vp = bp->b_vp;
2862 VOP_GETVOBJECT(vp, &obj);
2864 for (i = 0; i < bp->b_npages; i++) {
2865 vm_page_t m = bp->b_pages[i];
2867 if (m == bogus_page) {
2868 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2870 panic("vfs_unbusy_pages: page missing\n");
2873 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2875 vm_object_pip_subtract(obj, 1);
2876 vm_page_flag_clear(m, PG_ZERO);
2877 vm_page_io_finish(m);
2879 vm_object_pip_wakeupn(obj, 0);
2884 * vfs_page_set_valid:
2886 * Set the valid bits in a page based on the supplied offset. The
2887 * range is restricted to the buffer's size.
2889 * This routine is typically called after a read completes.
2892 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2894 vm_ooffset_t soff, eoff;
2897 * Start and end offsets in buffer. eoff - soff may not cross a
2898 * page boundry or cross the end of the buffer. The end of the
2899 * buffer, in this case, is our file EOF, not the allocation size
2903 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2904 if (eoff > bp->b_offset + bp->b_bcount)
2905 eoff = bp->b_offset + bp->b_bcount;
2908 * Set valid range. This is typically the entire buffer and thus the
2912 vm_page_set_validclean(
2914 (vm_offset_t) (soff & PAGE_MASK),
2915 (vm_offset_t) (eoff - soff)
2921 * This routine is called before a device strategy routine.
2922 * It is used to tell the VM system that paging I/O is in
2923 * progress, and treat the pages associated with the buffer
2924 * almost as being PG_BUSY. Also the object paging_in_progress
2925 * flag is handled to make sure that the object doesn't become
2928 * Since I/O has not been initiated yet, certain buffer flags
2929 * such as B_ERROR or B_INVAL may be in an inconsistant state
2930 * and should be ignored.
2933 vfs_busy_pages(struct buf * bp, int clear_modify)
2937 if (bp->b_flags & B_VMIO) {
2938 struct vnode *vp = bp->b_vp;
2942 VOP_GETVOBJECT(vp, &obj);
2943 foff = bp->b_offset;
2944 KASSERT(bp->b_offset != NOOFFSET,
2945 ("vfs_busy_pages: no buffer offset"));
2949 for (i = 0; i < bp->b_npages; i++) {
2950 vm_page_t m = bp->b_pages[i];
2951 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
2956 for (i = 0; i < bp->b_npages; i++) {
2957 vm_page_t m = bp->b_pages[i];
2959 vm_page_flag_clear(m, PG_ZERO);
2960 if ((bp->b_flags & B_CLUSTER) == 0) {
2961 vm_object_pip_add(obj, 1);
2962 vm_page_io_start(m);
2966 * When readying a buffer for a read ( i.e
2967 * clear_modify == 0 ), it is important to do
2968 * bogus_page replacement for valid pages in
2969 * partially instantiated buffers. Partially
2970 * instantiated buffers can, in turn, occur when
2971 * reconstituting a buffer from its VM backing store
2972 * base. We only have to do this if B_CACHE is
2973 * clear ( which causes the I/O to occur in the
2974 * first place ). The replacement prevents the read
2975 * I/O from overwriting potentially dirty VM-backed
2976 * pages. XXX bogus page replacement is, uh, bogus.
2977 * It may not work properly with small-block devices.
2978 * We need to find a better way.
2981 vm_page_protect(m, VM_PROT_NONE);
2983 vfs_page_set_valid(bp, foff, i, m);
2984 else if (m->valid == VM_PAGE_BITS_ALL &&
2985 (bp->b_flags & B_CACHE) == 0) {
2986 bp->b_pages[i] = bogus_page;
2989 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2992 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2997 * Tell the VM system that the pages associated with this buffer
2998 * are clean. This is used for delayed writes where the data is
2999 * going to go to disk eventually without additional VM intevention.
3001 * Note that while we only really need to clean through to b_bcount, we
3002 * just go ahead and clean through to b_bufsize.
3005 vfs_clean_pages(struct buf * bp)
3009 if (bp->b_flags & B_VMIO) {
3012 foff = bp->b_offset;
3013 KASSERT(bp->b_offset != NOOFFSET,
3014 ("vfs_clean_pages: no buffer offset"));
3015 for (i = 0; i < bp->b_npages; i++) {
3016 vm_page_t m = bp->b_pages[i];
3017 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3018 vm_ooffset_t eoff = noff;
3020 if (eoff > bp->b_offset + bp->b_bufsize)
3021 eoff = bp->b_offset + bp->b_bufsize;
3022 vfs_page_set_valid(bp, foff, i, m);
3023 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3030 * vfs_bio_set_validclean:
3032 * Set the range within the buffer to valid and clean. The range is
3033 * relative to the beginning of the buffer, b_offset. Note that b_offset
3034 * itself may be offset from the beginning of the first page.
3038 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3040 if (bp->b_flags & B_VMIO) {
3045 * Fixup base to be relative to beginning of first page.
3046 * Set initial n to be the maximum number of bytes in the
3047 * first page that can be validated.
3050 base += (bp->b_offset & PAGE_MASK);
3051 n = PAGE_SIZE - (base & PAGE_MASK);
3053 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
3054 vm_page_t m = bp->b_pages[i];
3059 vm_page_set_validclean(m, base & PAGE_MASK, n);
3070 * clear a buffer. This routine essentially fakes an I/O, so we need
3071 * to clear B_ERROR and B_INVAL.
3073 * Note that while we only theoretically need to clear through b_bcount,
3074 * we go ahead and clear through b_bufsize.
3078 vfs_bio_clrbuf(struct buf *bp)
3082 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3083 bp->b_flags &= ~(B_INVAL|B_ERROR);
3084 if ((bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3085 (bp->b_offset & PAGE_MASK) == 0) {
3086 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3087 if ((bp->b_pages[0]->valid & mask) == mask) {
3091 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
3092 ((bp->b_pages[0]->valid & mask) == 0)) {
3093 bzero(bp->b_data, bp->b_bufsize);
3094 bp->b_pages[0]->valid |= mask;
3099 ea = sa = bp->b_data;
3100 for(i=0;i<bp->b_npages;i++,sa=ea) {
3101 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3102 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3103 ea = (caddr_t)(vm_offset_t)ulmin(
3104 (u_long)(vm_offset_t)ea,
3105 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3106 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3107 if ((bp->b_pages[i]->valid & mask) == mask)
3109 if ((bp->b_pages[i]->valid & mask) == 0) {
3110 if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
3114 for (; sa < ea; sa += DEV_BSIZE, j++) {
3115 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
3116 (bp->b_pages[i]->valid & (1<<j)) == 0)
3117 bzero(sa, DEV_BSIZE);
3120 bp->b_pages[i]->valid |= mask;
3121 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3130 * vm_hold_load_pages and vm_hold_unload pages get pages into
3131 * a buffers address space. The pages are anonymous and are
3132 * not associated with a file object.
3135 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3141 to = round_page(to);
3142 from = round_page(from);
3143 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3145 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3150 * note: must allocate system pages since blocking here
3151 * could intefere with paging I/O, no matter which
3154 p = vm_page_alloc(kernel_object,
3155 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3158 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3163 p->valid = VM_PAGE_BITS_ALL;
3164 vm_page_flag_clear(p, PG_ZERO);
3165 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3166 bp->b_pages[index] = p;
3169 bp->b_npages = index;
3173 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3177 int index, newnpages;
3179 from = round_page(from);
3180 to = round_page(to);
3181 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3183 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3184 p = bp->b_pages[index];
3185 if (p && (index < bp->b_npages)) {
3187 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3188 bp->b_blkno, bp->b_lblkno);
3190 bp->b_pages[index] = NULL;
3193 vm_page_unwire(p, 0);
3197 bp->b_npages = newnpages;
3201 * Map an IO request into kernel virtual address space.
3203 * All requests are (re)mapped into kernel VA space.
3204 * Notice that we use b_bufsize for the size of the buffer
3205 * to be mapped. b_bcount might be modified by the driver.
3208 vmapbuf(struct buf *bp)
3210 caddr_t addr, v, kva;
3216 if ((bp->b_flags & B_PHYS) == 0)
3218 if (bp->b_bufsize < 0)
3220 for (v = bp->b_saveaddr,
3221 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3223 addr < bp->b_data + bp->b_bufsize;
3224 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3226 * Do the vm_fault if needed; do the copy-on-write thing
3227 * when reading stuff off device into memory.
3230 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3231 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3233 for (i = 0; i < pidx; ++i) {
3234 vm_page_unhold(bp->b_pages[i]);
3235 bp->b_pages[i] = NULL;
3241 * WARNING! If sparc support is MFCd in the future this will
3242 * have to be changed from pmap_kextract() to pmap_extract()
3246 #error "If MFCing sparc support use pmap_extract"
3248 pa = pmap_kextract((vm_offset_t)addr);
3250 printf("vmapbuf: warning, race against user address during I/O");
3253 m = PHYS_TO_VM_PAGE(pa);
3255 bp->b_pages[pidx] = m;
3257 if (pidx > btoc(MAXPHYS))
3258 panic("vmapbuf: mapped more than MAXPHYS");
3259 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_pages, pidx);
3261 kva = bp->b_saveaddr;
3262 bp->b_npages = pidx;
3263 bp->b_saveaddr = bp->b_data;
3264 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3269 * Free the io map PTEs associated with this IO operation.
3270 * We also invalidate the TLB entries and restore the original b_addr.
3274 register struct buf *bp;
3280 if ((bp->b_flags & B_PHYS) == 0)
3283 npages = bp->b_npages;
3284 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3287 for (pidx = 0; pidx < npages; pidx++)
3288 vm_page_unhold(*m++);
3290 bp->b_data = bp->b_saveaddr;
3293 #include "opt_ddb.h"
3295 #include <ddb/ddb.h>
3297 DB_SHOW_COMMAND(buffer, db_show_buffer)
3300 struct buf *bp = (struct buf *)addr;
3303 db_printf("usage: show buffer <addr>\n");
3307 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3308 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3309 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3310 "b_blkno = %d, b_pblkno = %d\n",
3311 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3312 major(bp->b_dev), minor(bp->b_dev),
3313 bp->b_data, bp->b_blkno, bp->b_pblkno);
3316 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3317 for (i = 0; i < bp->b_npages; i++) {
3320 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3321 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3322 if ((i + 1) < bp->b_npages)