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.53 2005/11/19 17:19:47 dillon Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
58 #include <sys/thread2.h>
59 #include <vm/vm_page2.h>
64 #define BUFFER_QUEUES 6
66 BQUEUE_NONE, /* not on any queue */
67 BQUEUE_LOCKED, /* locked buffers */
68 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
69 BQUEUE_DIRTY, /* B_DELWRI buffers */
70 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
71 BQUEUE_EMPTY /* empty buffer headers */
73 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
75 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
77 struct bio_ops bioops; /* I/O operation notification */
79 struct buf *buf; /* buffer header pool */
81 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
83 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
85 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
86 int pageno, vm_page_t m);
87 static void vfs_clean_pages(struct buf * bp);
88 static void vfs_setdirty(struct buf *bp);
89 static void vfs_vmio_release(struct buf *bp);
91 static void vfs_backgroundwritedone(struct buf *bp);
93 static int flushbufqueues(void);
95 static int bd_request;
97 static void buf_daemon (void);
99 * bogus page -- for I/O to/from partially complete buffers
100 * this is a temporary solution to the problem, but it is not
101 * really that bad. it would be better to split the buffer
102 * for input in the case of buffers partially already in memory,
103 * but the code is intricate enough already.
105 vm_page_t bogus_page;
106 int vmiodirenable = TRUE;
108 struct spinlock buftimespinlock; /* Interlock on setting prio and timo */
110 static int bufspace, maxbufspace,
111 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
112 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
113 static int needsbuffer;
114 static int lorunningspace, hirunningspace, runningbufreq;
115 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
116 static int numfreebuffers, lofreebuffers, hifreebuffers;
117 static int getnewbufcalls;
118 static int getnewbufrestarts;
121 * Sysctls for operational control of the buffer cache.
123 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
124 "Number of dirty buffers to flush before bufdaemon becomes inactive");
125 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
126 "High watermark used to trigger explicit flushing of dirty buffers");
127 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
128 "Low watermark for special reserve in low-memory situations");
129 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
130 "High watermark for special reserve in low-memory situations");
131 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
132 "Minimum amount of buffer space required for active I/O");
133 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
134 "Maximum amount of buffer space to usable for active I/O");
135 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
136 "Use the VM system for performing directory writes");
138 * Sysctls determining current state of the buffer cache.
140 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
141 "Pending number of dirty buffers");
142 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
143 "Number of free buffers on the buffer cache free list");
144 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
145 "I/O bytes currently in progress due to asynchronous writes");
146 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
147 "Hard limit on maximum amount of memory usable for buffer space");
148 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
149 "Soft limit on maximum amount of memory usable for buffer space");
150 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
151 "Minimum amount of memory to reserve for system buffer space");
152 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
153 "Amount of memory available for buffers");
154 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
155 0, "Maximum amount of memory reserved for buffers using malloc");
156 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
157 "Amount of memory left for buffers using malloc-scheme");
158 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
159 "New buffer header acquisition requests");
160 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
161 0, "New buffer header acquisition restarts");
162 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
163 "Buffer acquisition restarts due to fragmented buffer map");
164 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
165 "Amount of time KVA space was deallocated in an arbitrary buffer");
166 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
167 "Amount of time buffer re-use operations were successful");
168 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
169 "sizeof(struct buf)");
173 * Disable background writes for now. There appear to be races in the
174 * flags tests and locking operations as well as races in the completion
175 * code modifying the original bp (origbp) without holding a lock, assuming
176 * critical section protection when there might not be critical section
179 * XXX disable also because the RB tree can't handle multiple blocks with
182 static int dobkgrdwrite = 0;
183 SYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
184 "Do background writes (honoring the BV_BKGRDWRITE flag)?");
187 static int bufhashmask;
188 static int bufhashshift;
189 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
190 char *buf_wmesg = BUF_WMESG;
192 extern int vm_swap_size;
194 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
195 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
196 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
197 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
200 * Buffer hash table code. Note that the logical block scans linearly, which
201 * gives us some L1 cache locality.
206 bufhash(struct vnode *vnp, daddr_t bn)
212 * A variation on the Fibonacci hash that Knuth credits to
213 * R. W. Floyd, see Knuth's _Art of Computer Programming,
214 * Volume 3 / Sorting and Searching_
216 * We reduce the argument to 32 bits before doing the hash to
217 * avoid the need for a slow 64x64 multiply on 32 bit platforms.
219 * sizeof(struct vnode) is 168 on i386, so toss some of the lower
220 * bits of the vnode address to reduce the key range, which
221 * improves the distribution of keys across buckets.
223 * The file system cylinder group blocks are very heavily
224 * used. They are located at invervals of fbg, which is
225 * on the order of 89 to 94 * 2^10, depending on other
226 * filesystem parameters, for a 16k block size. Smaller block
227 * sizes will reduce fpg approximately proportionally. This
228 * will cause the cylinder group index to be hashed using the
229 * lower bits of the hash multiplier, which will not distribute
230 * the keys as uniformly in a classic Fibonacci hash where a
231 * relatively small number of the upper bits of the result
232 * are used. Using 2^16 as a close-enough approximation to
233 * fpg, split the hash multiplier in half, with the upper 16
234 * bits being the inverse of the golden ratio, and the lower
235 * 16 bits being a fraction between 1/3 and 3/7 (closer to
236 * 3/7 in this case), that gives good experimental results.
238 hashkey64 = ((u_int64_t)(uintptr_t)vnp >> 3) + (u_int64_t)bn;
239 hashkey = (((u_int32_t)(hashkey64 + (hashkey64 >> 32)) * 0x9E376DB1u) >>
240 bufhashshift) & bufhashmask;
241 return(&bufhashtbl[hashkey]);
247 * If someone is blocked due to there being too many dirty buffers,
248 * and numdirtybuffers is now reasonable, wake them up.
252 numdirtywakeup(int level)
254 if (numdirtybuffers <= level) {
255 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
256 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
257 wakeup(&needsbuffer);
265 * Called when buffer space is potentially available for recovery.
266 * getnewbuf() will block on this flag when it is unable to free
267 * sufficient buffer space. Buffer space becomes recoverable when
268 * bp's get placed back in the queues.
275 * If someone is waiting for BUF space, wake them up. Even
276 * though we haven't freed the kva space yet, the waiting
277 * process will be able to now.
279 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
280 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
281 wakeup(&needsbuffer);
288 * Accounting for I/O in progress.
292 runningbufwakeup(struct buf *bp)
294 if (bp->b_runningbufspace) {
295 runningbufspace -= bp->b_runningbufspace;
296 bp->b_runningbufspace = 0;
297 if (runningbufreq && runningbufspace <= lorunningspace) {
299 wakeup(&runningbufreq);
307 * Called when a buffer has been added to one of the free queues to
308 * account for the buffer and to wakeup anyone waiting for free buffers.
309 * This typically occurs when large amounts of metadata are being handled
310 * by the buffer cache ( else buffer space runs out first, usually ).
318 needsbuffer &= ~VFS_BIO_NEED_ANY;
319 if (numfreebuffers >= hifreebuffers)
320 needsbuffer &= ~VFS_BIO_NEED_FREE;
321 wakeup(&needsbuffer);
326 * waitrunningbufspace()
328 * runningbufspace is a measure of the amount of I/O currently
329 * running. This routine is used in async-write situations to
330 * prevent creating huge backups of pending writes to a device.
331 * Only asynchronous writes are governed by this function.
333 * Reads will adjust runningbufspace, but will not block based on it.
334 * The read load has a side effect of reducing the allowed write load.
336 * This does NOT turn an async write into a sync write. It waits
337 * for earlier writes to complete and generally returns before the
338 * caller's write has reached the device.
341 waitrunningbufspace(void)
343 if (runningbufspace > hirunningspace) {
345 while (runningbufspace > hirunningspace) {
347 tsleep(&runningbufreq, 0, "wdrain", 0);
354 * vfs_buf_test_cache:
356 * Called when a buffer is extended. This function clears the B_CACHE
357 * bit if the newly extended portion of the buffer does not contain
362 vfs_buf_test_cache(struct buf *bp,
363 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
366 if (bp->b_flags & B_CACHE) {
367 int base = (foff + off) & PAGE_MASK;
368 if (vm_page_is_valid(m, base, size) == 0)
369 bp->b_flags &= ~B_CACHE;
376 * Wake up the buffer daemon if the number of outstanding dirty buffers
377 * is above specified threshold 'dirtybuflevel'.
379 * The buffer daemon is explicitly woken up when (a) the pending number
380 * of dirty buffers exceeds the recovery and stall mid-point value,
381 * (b) during bwillwrite() or (c) buf freelist was exhausted.
385 bd_wakeup(int dirtybuflevel)
387 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
396 * Speed up the buffer cache flushing process.
409 * Initialize buffer headers and related structures.
413 bufhashinit(caddr_t vaddr)
415 /* first, make a null hash table */
417 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
419 bufhashtbl = (void *)vaddr;
420 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
428 * Load time initialisation of the buffer cache, called from machine
429 * dependant initialization code.
435 vm_offset_t bogus_offset;
438 LIST_INIT(&invalhash);
439 spin_init(&buftimespinlock);
441 for (i = 0; i <= bufhashmask; i++)
442 LIST_INIT(&bufhashtbl[i]);
444 /* next, make a null set of free lists */
445 for (i = 0; i < BUFFER_QUEUES; i++)
446 TAILQ_INIT(&bufqueues[i]);
448 /* finally, initialize each buffer header and stick on empty q */
449 for (i = 0; i < nbuf; i++) {
451 bzero(bp, sizeof *bp);
452 bp->b_bio.bio_buf = bp; /* back pointer (temporary) */
453 bp->b_flags = B_INVAL; /* we're just an empty header */
455 bp->b_qindex = BQUEUE_EMPTY;
458 xio_init(&bp->b_xio);
459 LIST_INIT(&bp->b_dep);
461 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
462 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
466 * maxbufspace is the absolute maximum amount of buffer space we are
467 * allowed to reserve in KVM and in real terms. The absolute maximum
468 * is nominally used by buf_daemon. hibufspace is the nominal maximum
469 * used by most other processes. The differential is required to
470 * ensure that buf_daemon is able to run when other processes might
471 * be blocked waiting for buffer space.
473 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
474 * this may result in KVM fragmentation which is not handled optimally
477 maxbufspace = nbuf * BKVASIZE;
478 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
479 lobufspace = hibufspace - MAXBSIZE;
481 lorunningspace = 512 * 1024;
482 hirunningspace = 1024 * 1024;
485 * Limit the amount of malloc memory since it is wired permanently into
486 * the kernel space. Even though this is accounted for in the buffer
487 * allocation, we don't want the malloced region to grow uncontrolled.
488 * The malloc scheme improves memory utilization significantly on average
489 * (small) directories.
491 maxbufmallocspace = hibufspace / 20;
494 * Reduce the chance of a deadlock occuring by limiting the number
495 * of delayed-write dirty buffers we allow to stack up.
497 hidirtybuffers = nbuf / 4 + 20;
500 * To support extreme low-memory systems, make sure hidirtybuffers cannot
501 * eat up all available buffer space. This occurs when our minimum cannot
502 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
503 * BKVASIZE'd (8K) buffers.
505 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
506 hidirtybuffers >>= 1;
508 lodirtybuffers = hidirtybuffers / 2;
511 * Try to keep the number of free buffers in the specified range,
512 * and give special processes (e.g. like buf_daemon) access to an
515 lofreebuffers = nbuf / 18 + 5;
516 hifreebuffers = 2 * lofreebuffers;
517 numfreebuffers = nbuf;
520 * Maximum number of async ops initiated per buf_daemon loop. This is
521 * somewhat of a hack at the moment, we really need to limit ourselves
522 * based on the number of bytes of I/O in-transit that were initiated
526 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
527 bogus_page = vm_page_alloc(kernel_object,
528 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
530 vmstats.v_wire_count++;
537 * Free the KVA allocation for buffer 'bp'.
539 * Must be called from a critical section as this is the only locking for
542 * Since this call frees up buffer space, we call bufspacewakeup().
545 bfreekva(struct buf * bp)
551 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
552 vm_map_lock(buffer_map);
553 bufspace -= bp->b_kvasize;
554 vm_map_delete(buffer_map,
555 (vm_offset_t) bp->b_kvabase,
556 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
559 vm_map_unlock(buffer_map);
560 vm_map_entry_release(count);
569 * Remove the buffer from the appropriate free list.
572 bremfree(struct buf * bp)
577 old_qindex = bp->b_qindex;
579 if (bp->b_qindex != BQUEUE_NONE) {
580 KASSERT(BUF_REFCNTNB(bp) == 1,
581 ("bremfree: bp %p not locked",bp));
582 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
583 bp->b_qindex = BQUEUE_NONE;
585 if (BUF_REFCNTNB(bp) <= 1)
586 panic("bremfree: removing a buffer not on a queue");
590 * Fixup numfreebuffers count. If the buffer is invalid or not
591 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
592 * the buffer was free and we must decrement numfreebuffers.
594 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
599 case BQUEUE_EMPTYKVA:
613 * Get a buffer with the specified data. Look in the cache first. We
614 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
615 * is set, the buffer is valid and we do not have to do anything ( see
619 bread(struct vnode * vp, daddr_t blkno, int size, struct buf ** bpp)
623 bp = getblk(vp, blkno, size, 0, 0);
626 /* if not found in cache, do some I/O */
627 if ((bp->b_flags & B_CACHE) == 0) {
628 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
629 bp->b_flags |= B_READ;
630 bp->b_flags &= ~(B_ERROR | B_INVAL);
631 vfs_busy_pages(bp, 0);
632 VOP_STRATEGY(vp, bp);
633 return (biowait(bp));
641 * Operates like bread, but also starts asynchronous I/O on
642 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
643 * to initiating I/O . If B_CACHE is set, the buffer is valid
644 * and we do not have to do anything.
647 breadn(struct vnode * vp, daddr_t blkno, int size, daddr_t * rablkno,
648 int *rabsize, int cnt, struct buf ** bpp)
650 struct buf *bp, *rabp;
652 int rv = 0, readwait = 0;
654 *bpp = bp = getblk(vp, blkno, size, 0, 0);
656 /* if not found in cache, do some I/O */
657 if ((bp->b_flags & B_CACHE) == 0) {
658 bp->b_flags |= B_READ;
659 bp->b_flags &= ~(B_ERROR | B_INVAL);
660 vfs_busy_pages(bp, 0);
661 VOP_STRATEGY(vp, bp);
665 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
666 if (inmem(vp, *rablkno))
668 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
670 if ((rabp->b_flags & B_CACHE) == 0) {
671 rabp->b_flags |= B_READ | B_ASYNC;
672 rabp->b_flags &= ~(B_ERROR | B_INVAL);
673 vfs_busy_pages(rabp, 0);
675 VOP_STRATEGY(vp, rabp);
690 * Write, release buffer on completion. (Done by iodone
691 * if async). Do not bother writing anything if the buffer
694 * Note that we set B_CACHE here, indicating that buffer is
695 * fully valid and thus cacheable. This is true even of NFS
696 * now so we set it generally. This could be set either here
697 * or in biodone() since the I/O is synchronous. We put it
701 bwrite(struct buf * bp)
708 if (bp->b_flags & B_INVAL) {
713 oldflags = bp->b_flags;
715 if (BUF_REFCNTNB(bp) == 0)
716 panic("bwrite: buffer is not busy???");
719 * If a background write is already in progress, delay
720 * writing this block if it is asynchronous. Otherwise
721 * wait for the background write to complete.
723 if (bp->b_xflags & BX_BKGRDINPROG) {
724 if (bp->b_flags & B_ASYNC) {
729 bp->b_xflags |= BX_BKGRDWAIT;
730 tsleep(&bp->b_xflags, 0, "biord", 0);
731 if (bp->b_xflags & BX_BKGRDINPROG)
732 panic("bwrite: still writing");
735 /* Mark the buffer clean */
740 * If this buffer is marked for background writing and we
741 * do not have to wait for it, make a copy and write the
742 * copy so as to leave this buffer ready for further use.
744 * This optimization eats a lot of memory. If we have a page
745 * or buffer shortfull we can't do it.
747 * XXX DISABLED! This had to be removed to support the RB_TREE
748 * work and, really, this isn't the best place to do this sort
749 * of thing anyway. We really need a device copy-on-write feature.
752 (bp->b_xflags & BX_BKGRDWRITE) &&
753 (bp->b_flags & B_ASYNC) &&
754 !vm_page_count_severe() &&
755 !buf_dirty_count_severe()) {
757 panic("bwrite: need chained iodone");
759 /* get a new block */
760 newbp = geteblk(bp->b_bufsize);
762 /* set it to be identical to the old block */
763 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
764 newbp->b_lblkno = bp->b_lblkno;
765 newbp->b_blkno = bp->b_blkno;
766 newbp->b_offset = bp->b_offset;
767 newbp->b_iodone = vfs_backgroundwritedone;
768 newbp->b_flags |= B_ASYNC;
769 newbp->b_flags &= ~B_INVAL;
770 bgetvp(bp->b_vp, newbp);
772 /* move over the dependencies */
773 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
774 (*bioops.io_movedeps)(bp, newbp);
777 * Initiate write on the copy, release the original to
778 * the B_LOCKED queue so that it cannot go away until
779 * the background write completes. If not locked it could go
780 * away and then be reconstituted while it was being written.
781 * If the reconstituted buffer were written, we could end up
782 * with two background copies being written at the same time.
784 bp->b_xflags |= BX_BKGRDINPROG;
785 bp->b_flags |= B_LOCKED;
791 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
792 bp->b_flags |= B_CACHE;
794 bp->b_vp->v_numoutput++;
795 vfs_busy_pages(bp, 1);
798 * Normal bwrites pipeline writes
800 bp->b_runningbufspace = bp->b_bufsize;
801 runningbufspace += bp->b_runningbufspace;
804 if (oldflags & B_ASYNC)
806 VOP_STRATEGY(bp->b_vp, bp);
808 if ((oldflags & B_ASYNC) == 0) {
809 int rtval = biowait(bp);
812 } else if ((oldflags & B_NOWDRAIN) == 0) {
814 * don't allow the async write to saturate the I/O
815 * system. Deadlocks can occur only if a device strategy
816 * routine (like in VN) turns around and issues another
817 * high-level write, in which case B_NOWDRAIN is expected
818 * to be set. Otherwise we will not deadlock here because
819 * we are blocking waiting for I/O that is already in-progress
822 waitrunningbufspace();
830 * Complete a background write started from bwrite.
833 vfs_backgroundwritedone(struct buf *bp)
838 * Find the original buffer that we are writing.
840 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
841 panic("backgroundwritedone: lost buffer");
843 * Process dependencies then return any unfinished ones.
845 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
846 (*bioops.io_complete)(bp);
847 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
848 (*bioops.io_movedeps)(bp, origbp);
850 * Clear the BX_BKGRDINPROG flag in the original buffer
851 * and awaken it if it is waiting for the write to complete.
852 * If BX_BKGRDINPROG is not set in the original buffer it must
853 * have been released and re-instantiated - which is not legal.
855 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
856 origbp->b_xflags &= ~BX_BKGRDINPROG;
857 if (origbp->b_xflags & BX_BKGRDWAIT) {
858 origbp->b_xflags &= ~BX_BKGRDWAIT;
859 wakeup(&origbp->b_xflags);
862 * Clear the B_LOCKED flag and remove it from the locked
863 * queue if it currently resides there.
865 origbp->b_flags &= ~B_LOCKED;
866 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
871 * This buffer is marked B_NOCACHE, so when it is released
872 * by biodone, it will be tossed. We mark it with B_READ
873 * to avoid biodone doing a second vwakeup.
875 bp->b_flags |= B_NOCACHE | B_READ;
876 bp->b_flags &= ~(B_CACHE | B_DONE);
885 * Delayed write. (Buffer is marked dirty). Do not bother writing
886 * anything if the buffer is marked invalid.
888 * Note that since the buffer must be completely valid, we can safely
889 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
890 * biodone() in order to prevent getblk from writing the buffer
894 bdwrite(struct buf *bp)
896 if (BUF_REFCNTNB(bp) == 0)
897 panic("bdwrite: buffer is not busy");
899 if (bp->b_flags & B_INVAL) {
906 * Set B_CACHE, indicating that the buffer is fully valid. This is
907 * true even of NFS now.
909 bp->b_flags |= B_CACHE;
912 * This bmap keeps the system from needing to do the bmap later,
913 * perhaps when the system is attempting to do a sync. Since it
914 * is likely that the indirect block -- or whatever other datastructure
915 * that the filesystem needs is still in memory now, it is a good
916 * thing to do this. Note also, that if the pageout daemon is
917 * requesting a sync -- there might not be enough memory to do
918 * the bmap then... So, this is important to do.
920 if (bp->b_lblkno == bp->b_blkno) {
921 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
925 * Set the *dirty* buffer range based upon the VM system dirty pages.
930 * We need to do this here to satisfy the vnode_pager and the
931 * pageout daemon, so that it thinks that the pages have been
932 * "cleaned". Note that since the pages are in a delayed write
933 * buffer -- the VFS layer "will" see that the pages get written
934 * out on the next sync, or perhaps the cluster will be completed.
940 * Wakeup the buffer flushing daemon if we have a lot of dirty
941 * buffers (midpoint between our recovery point and our stall
944 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
947 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
948 * due to the softdep code.
955 * Turn buffer into delayed write request. We must clear B_READ and
956 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
957 * itself to properly update it in the dirty/clean lists. We mark it
958 * B_DONE to ensure that any asynchronization of the buffer properly
959 * clears B_DONE ( else a panic will occur later ).
961 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
962 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
963 * should only be called if the buffer is known-good.
965 * Since the buffer is not on a queue, we do not update the numfreebuffers
968 * Must be called from a critical section.
969 * The buffer must be on BQUEUE_NONE.
972 bdirty(struct buf *bp)
974 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
975 bp->b_flags &= ~(B_READ|B_RELBUF);
977 if ((bp->b_flags & B_DELWRI) == 0) {
978 bp->b_flags |= B_DONE | B_DELWRI;
979 reassignbuf(bp, bp->b_vp);
981 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
988 * Clear B_DELWRI for buffer.
990 * Since the buffer is not on a queue, we do not update the numfreebuffers
993 * Must be called from a critical section.
995 * The buffer is typically on BQUEUE_NONE but there is one case in
996 * brelse() that calls this function after placing the buffer on
1001 bundirty(struct buf *bp)
1003 if (bp->b_flags & B_DELWRI) {
1004 bp->b_flags &= ~B_DELWRI;
1005 reassignbuf(bp, bp->b_vp);
1007 numdirtywakeup(lodirtybuffers);
1010 * Since it is now being written, we can clear its deferred write flag.
1012 bp->b_flags &= ~B_DEFERRED;
1018 * Asynchronous write. Start output on a buffer, but do not wait for
1019 * it to complete. The buffer is released when the output completes.
1021 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1022 * B_INVAL buffers. Not us.
1025 bawrite(struct buf * bp)
1027 bp->b_flags |= B_ASYNC;
1028 (void) VOP_BWRITE(bp->b_vp, bp);
1034 * Ordered write. Start output on a buffer, and flag it so that the
1035 * device will write it in the order it was queued. The buffer is
1036 * released when the output completes. bwrite() ( or the VOP routine
1037 * anyway ) is responsible for handling B_INVAL buffers.
1040 bowrite(struct buf * bp)
1042 bp->b_flags |= B_ORDERED | B_ASYNC;
1043 return (VOP_BWRITE(bp->b_vp, bp));
1049 * Called prior to the locking of any vnodes when we are expecting to
1050 * write. We do not want to starve the buffer cache with too many
1051 * dirty buffers so we block here. By blocking prior to the locking
1052 * of any vnodes we attempt to avoid the situation where a locked vnode
1053 * prevents the various system daemons from flushing related buffers.
1059 if (numdirtybuffers >= hidirtybuffers) {
1061 while (numdirtybuffers >= hidirtybuffers) {
1063 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1064 tsleep(&needsbuffer, 0, "flswai", 0);
1071 * buf_dirty_count_severe:
1073 * Return true if we have too many dirty buffers.
1076 buf_dirty_count_severe(void)
1078 return(numdirtybuffers >= hidirtybuffers);
1084 * Release a busy buffer and, if requested, free its resources. The
1085 * buffer will be stashed in the appropriate bufqueue[] allowing it
1086 * to be accessed later as a cache entity or reused for other purposes.
1089 brelse(struct buf * bp)
1092 int saved_flags = bp->b_flags;
1095 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1099 if (bp->b_flags & B_LOCKED)
1100 bp->b_flags &= ~B_ERROR;
1102 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
1104 * Failed write, redirty. Must clear B_ERROR to prevent
1105 * pages from being scrapped. If B_INVAL is set then
1106 * this case is not run and the next case is run to
1107 * destroy the buffer. B_INVAL can occur if the buffer
1108 * is outside the range supported by the underlying device.
1110 bp->b_flags &= ~B_ERROR;
1112 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
1113 (bp->b_bufsize <= 0)) {
1115 * Either a failed I/O or we were asked to free or not
1118 bp->b_flags |= B_INVAL;
1119 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1120 (*bioops.io_deallocate)(bp);
1121 if (bp->b_flags & B_DELWRI) {
1123 numdirtywakeup(lodirtybuffers);
1125 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
1129 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1130 * is called with B_DELWRI set, the underlying pages may wind up
1131 * getting freed causing a previous write (bdwrite()) to get 'lost'
1132 * because pages associated with a B_DELWRI bp are marked clean.
1134 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1135 * if B_DELWRI is set.
1137 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1138 * on pages to return pages to the VM page queues.
1140 if (bp->b_flags & B_DELWRI)
1141 bp->b_flags &= ~B_RELBUF;
1142 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1143 bp->b_flags |= B_RELBUF;
1146 * At this point destroying the buffer is governed by the B_INVAL
1147 * or B_RELBUF flags.
1151 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1152 * constituted, not even NFS buffers now. Two flags effect this. If
1153 * B_INVAL, the struct buf is invalidated but the VM object is kept
1154 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1156 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1157 * invalidated. B_ERROR cannot be set for a failed write unless the
1158 * buffer is also B_INVAL because it hits the re-dirtying code above.
1160 * Normally we can do this whether a buffer is B_DELWRI or not. If
1161 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1162 * the commit state and we cannot afford to lose the buffer. If the
1163 * buffer has a background write in progress, we need to keep it
1164 * around to prevent it from being reconstituted and starting a second
1167 if ((bp->b_flags & B_VMIO)
1168 && !(bp->b_vp->v_tag == VT_NFS &&
1169 !vn_isdisk(bp->b_vp, NULL) &&
1170 (bp->b_flags & B_DELWRI))
1173 * Rundown for VMIO buffers which are not dirty NFS buffers.
1185 * Get the base offset and length of the buffer. Note that
1186 * in the VMIO case if the buffer block size is not
1187 * page-aligned then b_data pointer may not be page-aligned.
1188 * But our b_xio.xio_pages array *IS* page aligned.
1190 * block sizes less then DEV_BSIZE (usually 512) are not
1191 * supported due to the page granularity bits (m->valid,
1192 * m->dirty, etc...).
1194 * See man buf(9) for more information
1197 resid = bp->b_bufsize;
1198 foff = bp->b_offset;
1200 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1201 m = bp->b_xio.xio_pages[i];
1202 vm_page_flag_clear(m, PG_ZERO);
1204 * If we hit a bogus page, fixup *all* of them
1205 * now. Note that we left these pages wired
1206 * when we removed them so they had better exist,
1207 * and they cannot be ripped out from under us so
1208 * no critical section protection is necessary.
1210 if (m == bogus_page) {
1211 VOP_GETVOBJECT(vp, &obj);
1212 poff = OFF_TO_IDX(bp->b_offset);
1214 for (j = i; j < bp->b_xio.xio_npages; j++) {
1217 mtmp = bp->b_xio.xio_pages[j];
1218 if (mtmp == bogus_page) {
1219 mtmp = vm_page_lookup(obj, poff + j);
1221 panic("brelse: page missing");
1223 bp->b_xio.xio_pages[j] = mtmp;
1227 if ((bp->b_flags & B_INVAL) == 0) {
1228 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1229 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1231 m = bp->b_xio.xio_pages[i];
1235 * Invalidate the backing store if B_NOCACHE is set
1236 * (e.g. used with vinvalbuf()). If this is NFS
1237 * we impose a requirement that the block size be
1238 * a multiple of PAGE_SIZE and create a temporary
1239 * hack to basically invalidate the whole page. The
1240 * problem is that NFS uses really odd buffer sizes
1241 * especially when tracking piecemeal writes and
1242 * it also vinvalbuf()'s a lot, which would result
1243 * in only partial page validation and invalidation
1244 * here. If the file page is mmap()'d, however,
1245 * all the valid bits get set so after we invalidate
1246 * here we would end up with weird m->valid values
1247 * like 0xfc. nfs_getpages() can't handle this so
1248 * we clear all the valid bits for the NFS case
1249 * instead of just some of them.
1251 * The real bug is the VM system having to set m->valid
1252 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1253 * itself is an artifact of the whole 512-byte
1254 * granular mess that exists to support odd block
1255 * sizes and UFS meta-data block sizes (e.g. 6144).
1256 * A complete rewrite is required.
1258 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1259 int poffset = foff & PAGE_MASK;
1262 presid = PAGE_SIZE - poffset;
1263 if (bp->b_vp->v_tag == VT_NFS &&
1264 bp->b_vp->v_type == VREG) {
1266 } else if (presid > resid) {
1269 KASSERT(presid >= 0, ("brelse: extra page"));
1270 vm_page_set_invalid(m, poffset, presid);
1272 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1273 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1275 if (bp->b_flags & (B_INVAL | B_RELBUF))
1276 vfs_vmio_release(bp);
1277 } else if (bp->b_flags & B_VMIO) {
1279 * Rundown for VMIO buffers which are dirty NFS buffers. Such
1280 * buffers contain tracking ranges for NFS and cannot normally
1281 * be released. Due to the dirty check above this series of
1282 * conditionals, B_RELBUF probably will never be set in this
1285 if (bp->b_flags & (B_INVAL | B_RELBUF))
1286 vfs_vmio_release(bp);
1289 * Rundown for non-VMIO buffers.
1291 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1294 printf("brelse bp %p %08x/%08lx: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1303 if (bp->b_qindex != BQUEUE_NONE)
1304 panic("brelse: free buffer onto another queue???");
1305 if (BUF_REFCNTNB(bp) > 1) {
1306 /* Temporary panic to verify exclusive locking */
1307 /* This panic goes away when we allow shared refs */
1308 panic("brelse: multiple refs");
1309 /* do not release to free list */
1316 * Figure out the correct queue to place the cleaned up buffer on.
1317 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1318 * disassociated from their vnode.
1321 if (bp->b_bufsize == 0) {
1323 * Buffers with no memory. Due to conditionals near the top
1324 * of brelse() such buffers should probably already be
1325 * marked B_INVAL and disassociated from their vnode.
1327 bp->b_flags |= B_INVAL;
1328 bp->b_xflags &= ~BX_BKGRDWRITE;
1329 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08lx vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1330 if (bp->b_xflags & BX_BKGRDINPROG)
1331 panic("losing buffer 1");
1332 if (bp->b_kvasize) {
1333 bp->b_qindex = BQUEUE_EMPTYKVA;
1335 bp->b_qindex = BQUEUE_EMPTY;
1337 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1338 LIST_REMOVE(bp, b_hash);
1339 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1341 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1343 * Buffers with junk contents. Again these buffers had better
1344 * already be disassociated from their vnode.
1346 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08lx vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1347 bp->b_flags |= B_INVAL;
1348 bp->b_xflags &= ~BX_BKGRDWRITE;
1349 if (bp->b_xflags & BX_BKGRDINPROG)
1350 panic("losing buffer 2");
1351 bp->b_qindex = BQUEUE_CLEAN;
1352 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1353 LIST_REMOVE(bp, b_hash);
1354 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1356 } else if (bp->b_flags & B_LOCKED) {
1358 * Buffers that are locked.
1360 bp->b_qindex = BQUEUE_LOCKED;
1361 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1364 * Remaining buffers. These buffers are still associated with
1367 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1368 case B_DELWRI | B_AGE:
1369 bp->b_qindex = BQUEUE_DIRTY;
1370 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1373 bp->b_qindex = BQUEUE_DIRTY;
1374 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1377 bp->b_qindex = BQUEUE_CLEAN;
1378 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1381 bp->b_qindex = BQUEUE_CLEAN;
1382 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1388 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1389 * on the correct queue.
1391 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1395 * Fixup numfreebuffers count. The bp is on an appropriate queue
1396 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1397 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1398 * if B_INVAL is set ).
1400 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1404 * Something we can maybe free or reuse
1406 if (bp->b_bufsize || bp->b_kvasize)
1411 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1412 B_DIRECT | B_NOWDRAIN);
1419 * Release a buffer back to the appropriate queue but do not try to free
1420 * it. The buffer is expected to be used again soon.
1422 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1423 * biodone() to requeue an async I/O on completion. It is also used when
1424 * known good buffers need to be requeued but we think we may need the data
1427 * XXX we should be able to leave the B_RELBUF hint set on completion.
1430 bqrelse(struct buf * bp)
1434 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1436 if (bp->b_qindex != BQUEUE_NONE)
1437 panic("bqrelse: free buffer onto another queue???");
1438 if (BUF_REFCNTNB(bp) > 1) {
1439 /* do not release to free list */
1440 panic("bqrelse: multiple refs");
1445 if (bp->b_flags & B_LOCKED) {
1446 bp->b_flags &= ~B_ERROR;
1447 bp->b_qindex = BQUEUE_LOCKED;
1448 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1449 /* buffers with stale but valid contents */
1450 } else if (bp->b_flags & B_DELWRI) {
1451 bp->b_qindex = BQUEUE_DIRTY;
1452 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1453 } else if (vm_page_count_severe()) {
1455 * We are too low on memory, we have to try to free the
1456 * buffer (most importantly: the wired pages making up its
1457 * backing store) *now*.
1463 bp->b_qindex = BQUEUE_CLEAN;
1464 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1467 if ((bp->b_flags & B_LOCKED) == 0 &&
1468 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1473 * Something we can maybe free or reuse.
1475 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1479 * Final cleanup and unlock. Clear bits that are only used while a
1480 * buffer is actively locked.
1482 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1490 * Return backing pages held by the buffer 'bp' back to the VM system
1491 * if possible. The pages are freed if they are no longer valid or
1492 * attempt to free if it was used for direct I/O otherwise they are
1493 * sent to the page cache.
1495 * Pages that were marked busy are left alone and skipped.
1497 * The KVA mapping (b_data) for the underlying pages is removed by
1501 vfs_vmio_release(struct buf *bp)
1507 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1508 m = bp->b_xio.xio_pages[i];
1509 bp->b_xio.xio_pages[i] = NULL;
1511 * In order to keep page LRU ordering consistent, put
1512 * everything on the inactive queue.
1514 vm_page_unwire(m, 0);
1516 * We don't mess with busy pages, it is
1517 * the responsibility of the process that
1518 * busied the pages to deal with them.
1520 if ((m->flags & PG_BUSY) || (m->busy != 0))
1523 if (m->wire_count == 0) {
1524 vm_page_flag_clear(m, PG_ZERO);
1526 * Might as well free the page if we can and it has
1527 * no valid data. We also free the page if the
1528 * buffer was used for direct I/O.
1530 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1531 m->hold_count == 0) {
1533 vm_page_protect(m, VM_PROT_NONE);
1535 } else if (bp->b_flags & B_DIRECT) {
1536 vm_page_try_to_free(m);
1537 } else if (vm_page_count_severe()) {
1538 vm_page_try_to_cache(m);
1543 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1544 if (bp->b_bufsize) {
1548 bp->b_xio.xio_npages = 0;
1549 bp->b_flags &= ~B_VMIO;
1557 * Check to see if a block is currently memory resident.
1560 gbincore(struct vnode * vp, daddr_t blkno)
1563 struct bufhashhdr *bh;
1565 bh = bufhash(vp, blkno);
1566 LIST_FOREACH(bp, bh, b_hash) {
1567 if (bp->b_vp == vp && bp->b_lblkno == blkno)
1576 * Implement clustered async writes for clearing out B_DELWRI buffers.
1577 * This is much better then the old way of writing only one buffer at
1578 * a time. Note that we may not be presented with the buffers in the
1579 * correct order, so we search for the cluster in both directions.
1582 vfs_bio_awrite(struct buf * bp)
1586 daddr_t lblkno = bp->b_lblkno;
1587 struct vnode *vp = bp->b_vp;
1596 * right now we support clustered writing only to regular files. If
1597 * we find a clusterable block we could be in the middle of a cluster
1598 * rather then at the beginning.
1600 if ((vp->v_type == VREG) &&
1601 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1602 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1604 size = vp->v_mount->mnt_stat.f_iosize;
1605 maxcl = MAXPHYS / size;
1607 for (i = 1; i < maxcl; i++) {
1608 if ((bpa = gbincore(vp, lblkno + i)) &&
1609 BUF_REFCNT(bpa) == 0 &&
1610 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1611 (B_DELWRI | B_CLUSTEROK)) &&
1612 (bpa->b_bufsize == size)) {
1613 if ((bpa->b_blkno == bpa->b_lblkno) ||
1615 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1621 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1622 if ((bpa = gbincore(vp, lblkno - j)) &&
1623 BUF_REFCNT(bpa) == 0 &&
1624 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1625 (B_DELWRI | B_CLUSTEROK)) &&
1626 (bpa->b_bufsize == size)) {
1627 if ((bpa->b_blkno == bpa->b_lblkno) ||
1629 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1638 * this is a possible cluster write
1641 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1647 BUF_LOCK(bp, LK_EXCLUSIVE);
1649 bp->b_flags |= B_ASYNC;
1653 * default (old) behavior, writing out only one block
1655 * XXX returns b_bufsize instead of b_bcount for nwritten?
1657 nwritten = bp->b_bufsize;
1658 (void) VOP_BWRITE(bp->b_vp, bp);
1666 * Find and initialize a new buffer header, freeing up existing buffers
1667 * in the bufqueues as necessary. The new buffer is returned locked.
1669 * Important: B_INVAL is not set. If the caller wishes to throw the
1670 * buffer away, the caller must set B_INVAL prior to calling brelse().
1673 * We have insufficient buffer headers
1674 * We have insufficient buffer space
1675 * buffer_map is too fragmented ( space reservation fails )
1676 * If we have to flush dirty buffers ( but we try to avoid this )
1678 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1679 * Instead we ask the buf daemon to do it for us. We attempt to
1680 * avoid piecemeal wakeups of the pageout daemon.
1684 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1690 static int flushingbufs;
1693 * We can't afford to block since we might be holding a vnode lock,
1694 * which may prevent system daemons from running. We deal with
1695 * low-memory situations by proactively returning memory and running
1696 * async I/O rather then sync I/O.
1700 --getnewbufrestarts;
1702 ++getnewbufrestarts;
1705 * Setup for scan. If we do not have enough free buffers,
1706 * we setup a degenerate case that immediately fails. Note
1707 * that if we are specially marked process, we are allowed to
1708 * dip into our reserves.
1710 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1712 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1713 * However, there are a number of cases (defragging, reusing, ...)
1714 * where we cannot backup.
1716 nqindex = BQUEUE_EMPTYKVA;
1717 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1721 * If no EMPTYKVA buffers and we are either
1722 * defragging or reusing, locate a CLEAN buffer
1723 * to free or reuse. If bufspace useage is low
1724 * skip this step so we can allocate a new buffer.
1726 if (defrag || bufspace >= lobufspace) {
1727 nqindex = BQUEUE_CLEAN;
1728 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1732 * If we could not find or were not allowed to reuse a
1733 * CLEAN buffer, check to see if it is ok to use an EMPTY
1734 * buffer. We can only use an EMPTY buffer if allocating
1735 * its KVA would not otherwise run us out of buffer space.
1737 if (nbp == NULL && defrag == 0 &&
1738 bufspace + maxsize < hibufspace) {
1739 nqindex = BQUEUE_EMPTY;
1740 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1745 * Run scan, possibly freeing data and/or kva mappings on the fly
1749 while ((bp = nbp) != NULL) {
1750 int qindex = nqindex;
1753 * Calculate next bp ( we can only use it if we do not block
1754 * or do other fancy things ).
1756 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1759 nqindex = BQUEUE_EMPTYKVA;
1760 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1763 case BQUEUE_EMPTYKVA:
1764 nqindex = BQUEUE_CLEAN;
1765 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1779 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1782 * Note: we no longer distinguish between VMIO and non-VMIO
1786 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1789 * If we are defragging then we need a buffer with
1790 * b_kvasize != 0. XXX this situation should no longer
1791 * occur, if defrag is non-zero the buffer's b_kvasize
1792 * should also be non-zero at this point. XXX
1794 if (defrag && bp->b_kvasize == 0) {
1795 printf("Warning: defrag empty buffer %p\n", bp);
1800 * Start freeing the bp. This is somewhat involved. nbp
1801 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1802 * on the clean list must be disassociated from their
1803 * current vnode. Buffers on the empty[kva] lists have
1804 * already been disassociated.
1807 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1808 printf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1809 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1812 if (bp->b_qindex != qindex) {
1813 printf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1819 if (qindex == BQUEUE_CLEAN) {
1820 if (bp->b_flags & B_VMIO) {
1821 bp->b_flags &= ~B_ASYNC;
1822 vfs_vmio_release(bp);
1829 * NOTE: nbp is now entirely invalid. We can only restart
1830 * the scan from this point on.
1832 * Get the rest of the buffer freed up. b_kva* is still
1833 * valid after this operation.
1836 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08lx vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1837 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1838 (*bioops.io_deallocate)(bp);
1839 if (bp->b_xflags & BX_BKGRDINPROG)
1840 panic("losing buffer 3");
1841 LIST_REMOVE(bp, b_hash);
1842 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1845 * critical section protection is not required when
1846 * scrapping a buffer's contents because it is already
1856 bp->b_blkno = bp->b_lblkno = 0;
1857 bp->b_offset = NOOFFSET;
1858 bp->b_iodone = NULL;
1862 bp->b_xio.xio_npages = 0;
1863 bp->b_dirtyoff = bp->b_dirtyend = 0;
1865 LIST_INIT(&bp->b_dep);
1868 * If we are defragging then free the buffer.
1871 bp->b_flags |= B_INVAL;
1879 * If we are overcomitted then recover the buffer and its
1880 * KVM space. This occurs in rare situations when multiple
1881 * processes are blocked in getnewbuf() or allocbuf().
1883 if (bufspace >= hibufspace)
1885 if (flushingbufs && bp->b_kvasize != 0) {
1886 bp->b_flags |= B_INVAL;
1891 if (bufspace < lobufspace)
1897 * If we exhausted our list, sleep as appropriate. We may have to
1898 * wakeup various daemons and write out some dirty buffers.
1900 * Generally we are sleeping due to insufficient buffer space.
1908 flags = VFS_BIO_NEED_BUFSPACE;
1910 } else if (bufspace >= hibufspace) {
1912 flags = VFS_BIO_NEED_BUFSPACE;
1915 flags = VFS_BIO_NEED_ANY;
1918 bd_speedup(); /* heeeelp */
1920 needsbuffer |= flags;
1921 while (needsbuffer & flags) {
1922 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
1927 * We finally have a valid bp. We aren't quite out of the
1928 * woods, we still have to reserve kva space. In order
1929 * to keep fragmentation sane we only allocate kva in
1932 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1934 if (maxsize != bp->b_kvasize) {
1935 vm_offset_t addr = 0;
1940 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1941 vm_map_lock(buffer_map);
1943 if (vm_map_findspace(buffer_map,
1944 vm_map_min(buffer_map), maxsize,
1947 * Uh oh. Buffer map is too fragmented. We
1948 * must defragment the map.
1950 vm_map_unlock(buffer_map);
1951 vm_map_entry_release(count);
1954 bp->b_flags |= B_INVAL;
1959 vm_map_insert(buffer_map, &count,
1961 addr, addr + maxsize,
1962 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1964 bp->b_kvabase = (caddr_t) addr;
1965 bp->b_kvasize = maxsize;
1966 bufspace += bp->b_kvasize;
1969 vm_map_unlock(buffer_map);
1970 vm_map_entry_release(count);
1972 bp->b_data = bp->b_kvabase;
1980 * Buffer flushing daemon. Buffers are normally flushed by the
1981 * update daemon but if it cannot keep up this process starts to
1982 * take the load in an attempt to prevent getnewbuf() from blocking.
1985 static struct thread *bufdaemonthread;
1987 static struct kproc_desc buf_kp = {
1992 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1998 * This process needs to be suspended prior to shutdown sync.
2000 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2001 bufdaemonthread, SHUTDOWN_PRI_LAST);
2004 * This process is allowed to take the buffer cache to the limit
2009 kproc_suspend_loop();
2012 * Do the flush. Limit the amount of in-transit I/O we
2013 * allow to build up, otherwise we would completely saturate
2014 * the I/O system. Wakeup any waiting processes before we
2015 * normally would so they can run in parallel with our drain.
2017 while (numdirtybuffers > lodirtybuffers) {
2018 if (flushbufqueues() == 0)
2020 waitrunningbufspace();
2021 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2025 * Only clear bd_request if we have reached our low water
2026 * mark. The buf_daemon normally waits 5 seconds and
2027 * then incrementally flushes any dirty buffers that have
2028 * built up, within reason.
2030 * If we were unable to hit our low water mark and couldn't
2031 * find any flushable buffers, we sleep half a second.
2032 * Otherwise we loop immediately.
2034 if (numdirtybuffers <= lodirtybuffers) {
2036 * We reached our low water mark, reset the
2037 * request and sleep until we are needed again.
2038 * The sleep is just so the suspend code works.
2041 tsleep(&bd_request, 0, "psleep", hz);
2044 * We couldn't find any flushable dirty buffers but
2045 * still have too many dirty buffers, we
2046 * have to sleep and try again. (rare)
2048 tsleep(&bd_request, 0, "qsleep", hz / 2);
2056 * Try to flush a buffer in the dirty queue. We must be careful to
2057 * free up B_INVAL buffers instead of write them, which NFS is
2058 * particularly sensitive to.
2062 flushbufqueues(void)
2067 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
2070 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
2071 if ((bp->b_flags & B_DELWRI) != 0 &&
2072 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
2073 if (bp->b_flags & B_INVAL) {
2074 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2075 panic("flushbufqueues: locked buf");
2081 if (LIST_FIRST(&bp->b_dep) != NULL &&
2082 bioops.io_countdeps &&
2083 (bp->b_flags & B_DEFERRED) == 0 &&
2084 (*bioops.io_countdeps)(bp, 0)) {
2085 TAILQ_REMOVE(&bufqueues[BQUEUE_DIRTY],
2087 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY],
2089 bp->b_flags |= B_DEFERRED;
2090 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
2097 bp = TAILQ_NEXT(bp, b_freelist);
2105 * Check to see if a block is currently resident in memory.
2108 incore(struct vnode * vp, daddr_t blkno)
2113 bp = gbincore(vp, blkno);
2121 * Returns true if no I/O is needed to access the associated VM object.
2122 * This is like incore except it also hunts around in the VM system for
2125 * Note that we ignore vm_page_free() races from interrupts against our
2126 * lookup, since if the caller is not protected our return value will not
2127 * be any more valid then otherwise once we exit the critical section.
2130 inmem(struct vnode * vp, daddr_t blkno)
2133 vm_offset_t toff, tinc, size;
2137 if (incore(vp, blkno))
2139 if (vp->v_mount == NULL)
2141 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
2145 if (size > vp->v_mount->mnt_stat.f_iosize)
2146 size = vp->v_mount->mnt_stat.f_iosize;
2147 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2149 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2150 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2154 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2155 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2156 if (vm_page_is_valid(m,
2157 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2166 * Sets the dirty range for a buffer based on the status of the dirty
2167 * bits in the pages comprising the buffer.
2169 * The range is limited to the size of the buffer.
2171 * This routine is primarily used by NFS, but is generalized for the
2175 vfs_setdirty(struct buf *bp)
2181 * Degenerate case - empty buffer
2184 if (bp->b_bufsize == 0)
2188 * We qualify the scan for modified pages on whether the
2189 * object has been flushed yet. The OBJ_WRITEABLE flag
2190 * is not cleared simply by protecting pages off.
2193 if ((bp->b_flags & B_VMIO) == 0)
2196 object = bp->b_xio.xio_pages[0]->object;
2198 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2199 printf("Warning: object %p writeable but not mightbedirty\n", object);
2200 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2201 printf("Warning: object %p mightbedirty but not writeable\n", object);
2203 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2204 vm_offset_t boffset;
2205 vm_offset_t eoffset;
2208 * test the pages to see if they have been modified directly
2209 * by users through the VM system.
2211 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2212 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2213 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2217 * Calculate the encompassing dirty range, boffset and eoffset,
2218 * (eoffset - boffset) bytes.
2221 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2222 if (bp->b_xio.xio_pages[i]->dirty)
2225 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2227 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2228 if (bp->b_xio.xio_pages[i]->dirty) {
2232 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2235 * Fit it to the buffer.
2238 if (eoffset > bp->b_bcount)
2239 eoffset = bp->b_bcount;
2242 * If we have a good dirty range, merge with the existing
2246 if (boffset < eoffset) {
2247 if (bp->b_dirtyoff > boffset)
2248 bp->b_dirtyoff = boffset;
2249 if (bp->b_dirtyend < eoffset)
2250 bp->b_dirtyend = eoffset;
2258 * Get a block given a specified block and offset into a file/device.
2259 * The buffers B_DONE bit will be cleared on return, making it almost
2260 * ready for an I/O initiation. B_INVAL may or may not be set on
2261 * return. The caller should clear B_INVAL prior to initiating a
2264 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2265 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2266 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2267 * without doing any of those things the system will likely believe
2268 * the buffer to be valid (especially if it is not B_VMIO), and the
2269 * next getblk() will return the buffer with B_CACHE set.
2271 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2272 * an existing buffer.
2274 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2275 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2276 * and then cleared based on the backing VM. If the previous buffer is
2277 * non-0-sized but invalid, B_CACHE will be cleared.
2279 * If getblk() must create a new buffer, the new buffer is returned with
2280 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2281 * case it is returned with B_INVAL clear and B_CACHE set based on the
2284 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2285 * B_CACHE bit is clear.
2287 * What this means, basically, is that the caller should use B_CACHE to
2288 * determine whether the buffer is fully valid or not and should clear
2289 * B_INVAL prior to issuing a read. If the caller intends to validate
2290 * the buffer by loading its data area with something, the caller needs
2291 * to clear B_INVAL. If the caller does this without issuing an I/O,
2292 * the caller should set B_CACHE ( as an optimization ), else the caller
2293 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2294 * a write attempt or if it was a successfull read. If the caller
2295 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2296 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2299 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2302 struct bufhashhdr *bh;
2304 if (size > MAXBSIZE)
2305 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2310 * Block if we are low on buffers. Certain processes are allowed
2311 * to completely exhaust the buffer cache.
2313 * If this check ever becomes a bottleneck it may be better to
2314 * move it into the else, when gbincore() fails. At the moment
2315 * it isn't a problem.
2317 * XXX remove, we cannot afford to block anywhere if holding a vnode
2318 * lock in low-memory situation, so take it to the max.
2320 if (numfreebuffers == 0) {
2323 needsbuffer |= VFS_BIO_NEED_ANY;
2324 tsleep(&needsbuffer, slpflag, "newbuf", slptimeo);
2327 if ((bp = gbincore(vp, blkno))) {
2329 * The buffer was found in the cache, but we need to lock it.
2330 * Even with LK_NOWAIT the lockmgr may break our critical
2331 * section, so double-check the validity of the buffer
2332 * once the lock has been obtained.
2334 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2335 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2336 "getblk", slpflag, slptimeo) == ENOLCK)
2339 return (struct buf *) NULL;
2343 * Once the buffer has been locked, make sure we didn't race
2344 * a buffer recyclement. Buffers that are no longer hashed
2345 * will have b_vp == NULL, so this takes care of that check
2348 if (bp->b_vp != vp || bp->b_lblkno != blkno) {
2349 printf("Warning buffer %p (vp %p lblkno %d) was recycled\n", bp, vp, (int)blkno);
2355 * Make sure that B_INVAL buffers do not have a cached
2356 * block number translation.
2358 if ((bp->b_flags & B_INVAL) && (bp->b_blkno != bp->b_lblkno)) {
2359 printf("Warning invalid buffer %p (vp %p lblkno %d) did not have cleared b_blkno cache\n", bp, vp, (int)blkno);
2360 bp->b_blkno = bp->b_lblkno;
2364 * The buffer is locked. B_CACHE is cleared if the buffer is
2365 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
2366 * and for a VMIO buffer B_CACHE is adjusted according to the
2369 if (bp->b_flags & B_INVAL)
2370 bp->b_flags &= ~B_CACHE;
2371 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2372 bp->b_flags |= B_CACHE;
2376 * check for size inconsistancies for non-VMIO case.
2379 if (bp->b_bcount != size) {
2380 if ((bp->b_flags & B_VMIO) == 0 ||
2381 (size > bp->b_kvasize)) {
2382 if (bp->b_flags & B_DELWRI) {
2383 bp->b_flags |= B_NOCACHE;
2384 VOP_BWRITE(bp->b_vp, bp);
2386 if ((bp->b_flags & B_VMIO) &&
2387 (LIST_FIRST(&bp->b_dep) == NULL)) {
2388 bp->b_flags |= B_RELBUF;
2391 bp->b_flags |= B_NOCACHE;
2392 VOP_BWRITE(bp->b_vp, bp);
2400 * If the size is inconsistant in the VMIO case, we can resize
2401 * the buffer. This might lead to B_CACHE getting set or
2402 * cleared. If the size has not changed, B_CACHE remains
2403 * unchanged from its previous state.
2406 if (bp->b_bcount != size)
2409 KASSERT(bp->b_offset != NOOFFSET,
2410 ("getblk: no buffer offset"));
2413 * A buffer with B_DELWRI set and B_CACHE clear must
2414 * be committed before we can return the buffer in
2415 * order to prevent the caller from issuing a read
2416 * ( due to B_CACHE not being set ) and overwriting
2419 * Most callers, including NFS and FFS, need this to
2420 * operate properly either because they assume they
2421 * can issue a read if B_CACHE is not set, or because
2422 * ( for example ) an uncached B_DELWRI might loop due
2423 * to softupdates re-dirtying the buffer. In the latter
2424 * case, B_CACHE is set after the first write completes,
2425 * preventing further loops.
2427 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2428 * above while extending the buffer, we cannot allow the
2429 * buffer to remain with B_CACHE set after the write
2430 * completes or it will represent a corrupt state. To
2431 * deal with this we set B_NOCACHE to scrap the buffer
2434 * We might be able to do something fancy, like setting
2435 * B_CACHE in bwrite() except if B_DELWRI is already set,
2436 * so the below call doesn't set B_CACHE, but that gets real
2437 * confusing. This is much easier.
2440 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2441 bp->b_flags |= B_NOCACHE;
2442 VOP_BWRITE(bp->b_vp, bp);
2447 bp->b_flags &= ~B_DONE;
2450 * Buffer is not in-core, create new buffer. The buffer
2451 * returned by getnewbuf() is locked. Note that the returned
2452 * buffer is also considered valid (not marked B_INVAL).
2454 * Calculating the offset for the I/O requires figuring out
2455 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2456 * the mount's f_iosize otherwise. If the vnode does not
2457 * have an associated mount we assume that the passed size is
2460 * Note that vn_isdisk() cannot be used here since it may
2461 * return a failure for numerous reasons. Note that the
2462 * buffer size may be larger then the block size (the caller
2463 * will use block numbers with the proper multiple). Beware
2464 * of using any v_* fields which are part of unions. In
2465 * particular, in DragonFly the mount point overloading
2466 * mechanism is such that the underlying directory (with a
2467 * non-NULL v_mountedhere) is not a special case.
2469 int bsize, maxsize, vmio;
2472 if (vp->v_type == VBLK || vp->v_type == VCHR)
2474 else if (vp->v_mount)
2475 bsize = vp->v_mount->mnt_stat.f_iosize;
2479 offset = (off_t)blkno * bsize;
2480 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2481 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2482 maxsize = imax(maxsize, bsize);
2484 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2485 if (slpflag || slptimeo) {
2493 * This code is used to make sure that a buffer is not
2494 * created while the getnewbuf routine is blocked.
2495 * This can be a problem whether the vnode is locked or not.
2496 * If the buffer is created out from under us, we have to
2497 * throw away the one we just created. There is now window
2498 * race because we are safely running in a critical section
2499 * from the point of the duplicate buffer creation through
2500 * to here, and we've locked the buffer.
2502 if (gbincore(vp, blkno)) {
2503 bp->b_flags |= B_INVAL;
2509 * Insert the buffer into the hash, so that it can
2510 * be found by incore. bgetvp() and bufhash()
2511 * must be synchronized with each other.
2513 bp->b_blkno = bp->b_lblkno = blkno;
2514 bp->b_offset = offset;
2517 LIST_REMOVE(bp, b_hash);
2518 bh = bufhash(vp, blkno);
2519 LIST_INSERT_HEAD(bh, bp, b_hash);
2522 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2523 * buffer size starts out as 0, B_CACHE will be set by
2524 * allocbuf() for the VMIO case prior to it testing the
2525 * backing store for validity.
2529 bp->b_flags |= B_VMIO;
2530 #if defined(VFS_BIO_DEBUG)
2531 if (vn_canvmio(vp) != TRUE)
2532 printf("getblk: vmioing file type %d???\n", vp->v_type);
2535 bp->b_flags &= ~B_VMIO;
2541 bp->b_flags &= ~B_DONE;
2549 * Get an empty, disassociated buffer of given size. The buffer is
2550 * initially set to B_INVAL.
2552 * critical section protection is not required for the allocbuf()
2553 * call because races are impossible here.
2561 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2564 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2568 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2576 * This code constitutes the buffer memory from either anonymous system
2577 * memory (in the case of non-VMIO operations) or from an associated
2578 * VM object (in the case of VMIO operations). This code is able to
2579 * resize a buffer up or down.
2581 * Note that this code is tricky, and has many complications to resolve
2582 * deadlock or inconsistant data situations. Tread lightly!!!
2583 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2584 * the caller. Calling this code willy nilly can result in the loss of data.
2586 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2587 * B_CACHE for the non-VMIO case.
2589 * This routine does not need to be called from a critical section but you
2590 * must own the buffer.
2593 allocbuf(struct buf *bp, int size)
2595 int newbsize, mbsize;
2598 if (BUF_REFCNT(bp) == 0)
2599 panic("allocbuf: buffer not busy");
2601 if (bp->b_kvasize < size)
2602 panic("allocbuf: buffer too small");
2604 if ((bp->b_flags & B_VMIO) == 0) {
2608 * Just get anonymous memory from the kernel. Don't
2609 * mess with B_CACHE.
2611 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2612 if (bp->b_flags & B_MALLOC)
2615 newbsize = round_page(size);
2617 if (newbsize < bp->b_bufsize) {
2619 * malloced buffers are not shrunk
2621 if (bp->b_flags & B_MALLOC) {
2623 bp->b_bcount = size;
2625 free(bp->b_data, M_BIOBUF);
2626 if (bp->b_bufsize) {
2627 bufmallocspace -= bp->b_bufsize;
2631 bp->b_data = bp->b_kvabase;
2633 bp->b_flags &= ~B_MALLOC;
2639 (vm_offset_t) bp->b_data + newbsize,
2640 (vm_offset_t) bp->b_data + bp->b_bufsize);
2641 } else if (newbsize > bp->b_bufsize) {
2643 * We only use malloced memory on the first allocation.
2644 * and revert to page-allocated memory when the buffer
2647 if ( (bufmallocspace < maxbufmallocspace) &&
2648 (bp->b_bufsize == 0) &&
2649 (mbsize <= PAGE_SIZE/2)) {
2651 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2652 bp->b_bufsize = mbsize;
2653 bp->b_bcount = size;
2654 bp->b_flags |= B_MALLOC;
2655 bufmallocspace += mbsize;
2661 * If the buffer is growing on its other-than-first allocation,
2662 * then we revert to the page-allocation scheme.
2664 if (bp->b_flags & B_MALLOC) {
2665 origbuf = bp->b_data;
2666 origbufsize = bp->b_bufsize;
2667 bp->b_data = bp->b_kvabase;
2668 if (bp->b_bufsize) {
2669 bufmallocspace -= bp->b_bufsize;
2673 bp->b_flags &= ~B_MALLOC;
2674 newbsize = round_page(newbsize);
2678 (vm_offset_t) bp->b_data + bp->b_bufsize,
2679 (vm_offset_t) bp->b_data + newbsize);
2681 bcopy(origbuf, bp->b_data, origbufsize);
2682 free(origbuf, M_BIOBUF);
2689 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2690 desiredpages = (size == 0) ? 0 :
2691 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2693 if (bp->b_flags & B_MALLOC)
2694 panic("allocbuf: VMIO buffer can't be malloced");
2696 * Set B_CACHE initially if buffer is 0 length or will become
2699 if (size == 0 || bp->b_bufsize == 0)
2700 bp->b_flags |= B_CACHE;
2702 if (newbsize < bp->b_bufsize) {
2704 * DEV_BSIZE aligned new buffer size is less then the
2705 * DEV_BSIZE aligned existing buffer size. Figure out
2706 * if we have to remove any pages.
2708 if (desiredpages < bp->b_xio.xio_npages) {
2709 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2711 * the page is not freed here -- it
2712 * is the responsibility of
2713 * vnode_pager_setsize
2715 m = bp->b_xio.xio_pages[i];
2716 KASSERT(m != bogus_page,
2717 ("allocbuf: bogus page found"));
2718 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2721 bp->b_xio.xio_pages[i] = NULL;
2722 vm_page_unwire(m, 0);
2724 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2725 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2726 bp->b_xio.xio_npages = desiredpages;
2728 } else if (size > bp->b_bcount) {
2730 * We are growing the buffer, possibly in a
2731 * byte-granular fashion.
2739 * Step 1, bring in the VM pages from the object,
2740 * allocating them if necessary. We must clear
2741 * B_CACHE if these pages are not valid for the
2742 * range covered by the buffer.
2744 * critical section protection is required to protect
2745 * against interrupts unbusying and freeing pages
2746 * between our vm_page_lookup() and our
2747 * busycheck/wiring call.
2750 VOP_GETVOBJECT(vp, &obj);
2753 while (bp->b_xio.xio_npages < desiredpages) {
2757 pi = OFF_TO_IDX(bp->b_offset) + bp->b_xio.xio_npages;
2758 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2760 * note: must allocate system pages
2761 * since blocking here could intefere
2762 * with paging I/O, no matter which
2765 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2768 vm_pageout_deficit += desiredpages -
2769 bp->b_xio.xio_npages;
2773 bp->b_flags &= ~B_CACHE;
2774 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2775 ++bp->b_xio.xio_npages;
2781 * We found a page. If we have to sleep on it,
2782 * retry because it might have gotten freed out
2785 * We can only test PG_BUSY here. Blocking on
2786 * m->busy might lead to a deadlock:
2788 * vm_fault->getpages->cluster_read->allocbuf
2792 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2796 * We have a good page. Should we wakeup the
2799 if ((curthread != pagethread) &&
2800 ((m->queue - m->pc) == PQ_CACHE) &&
2801 ((vmstats.v_free_count + vmstats.v_cache_count) <
2802 (vmstats.v_free_min + vmstats.v_cache_min))) {
2803 pagedaemon_wakeup();
2805 vm_page_flag_clear(m, PG_ZERO);
2807 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2808 ++bp->b_xio.xio_npages;
2813 * Step 2. We've loaded the pages into the buffer,
2814 * we have to figure out if we can still have B_CACHE
2815 * set. Note that B_CACHE is set according to the
2816 * byte-granular range ( bcount and size ), not the
2817 * aligned range ( newbsize ).
2819 * The VM test is against m->valid, which is DEV_BSIZE
2820 * aligned. Needless to say, the validity of the data
2821 * needs to also be DEV_BSIZE aligned. Note that this
2822 * fails with NFS if the server or some other client
2823 * extends the file's EOF. If our buffer is resized,
2824 * B_CACHE may remain set! XXX
2827 toff = bp->b_bcount;
2828 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2830 while ((bp->b_flags & B_CACHE) && toff < size) {
2833 if (tinc > (size - toff))
2836 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2844 bp->b_xio.xio_pages[pi]
2851 * Step 3, fixup the KVM pmap. Remember that
2852 * bp->b_data is relative to bp->b_offset, but
2853 * bp->b_offset may be offset into the first page.
2856 bp->b_data = (caddr_t)
2857 trunc_page((vm_offset_t)bp->b_data);
2859 (vm_offset_t)bp->b_data,
2860 bp->b_xio.xio_pages,
2861 bp->b_xio.xio_npages
2863 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2864 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2867 if (newbsize < bp->b_bufsize)
2869 bp->b_bufsize = newbsize; /* actual buffer allocation */
2870 bp->b_bcount = size; /* requested buffer size */
2877 * Wait for buffer I/O completion, returning error status. The buffer
2878 * is left locked and B_DONE on return. B_EINTR is converted into an
2879 * EINTR error and cleared.
2882 biowait(struct buf * bp)
2885 while ((bp->b_flags & B_DONE) == 0) {
2886 if (bp->b_flags & B_READ)
2887 tsleep(bp, 0, "biord", 0);
2889 tsleep(bp, 0, "biowr", 0);
2892 if (bp->b_flags & B_EINTR) {
2893 bp->b_flags &= ~B_EINTR;
2896 if (bp->b_flags & B_ERROR) {
2897 return (bp->b_error ? bp->b_error : EIO);
2906 * Finish I/O on a buffer, optionally calling a completion function.
2907 * This is usually called from an interrupt so process blocking is
2910 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2911 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2912 * assuming B_INVAL is clear.
2914 * For the VMIO case, we set B_CACHE if the op was a read and no
2915 * read error occured, or if the op was a write. B_CACHE is never
2916 * set if the buffer is invalid or otherwise uncacheable.
2918 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2919 * initiator to leave B_INVAL set to brelse the buffer out of existance
2920 * in the biodone routine.
2922 * b_dev is required to be reinitialized prior to the top level strategy
2923 * call in a device stack. To avoid improper reuse, biodone() sets
2927 biodone(struct buf *bp)
2933 KASSERT(BUF_REFCNTNB(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
2934 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2935 biodone_t *biodone_func;
2937 bp->b_flags |= B_DONE;
2939 runningbufwakeup(bp);
2941 if (bp->b_flags & B_FREEBUF) {
2947 if ((bp->b_flags & B_READ) == 0) {
2951 /* call optional completion function if requested */
2952 if (bp->b_iodone != NULL) {
2953 biodone_func = bp->b_iodone;
2954 bp->b_iodone = NULL;
2955 (*biodone_func) (bp);
2959 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2960 (*bioops.io_complete)(bp);
2962 if (bp->b_flags & B_VMIO) {
2968 struct vnode *vp = bp->b_vp;
2970 error = VOP_GETVOBJECT(vp, &obj);
2972 #if defined(VFS_BIO_DEBUG)
2973 if (vp->v_holdcnt == 0) {
2974 panic("biodone: zero vnode hold count");
2978 panic("biodone: missing VM object");
2981 if ((vp->v_flag & VOBJBUF) == 0) {
2982 panic("biodone: vnode is not setup for merged cache");
2986 foff = bp->b_offset;
2987 KASSERT(bp->b_offset != NOOFFSET,
2988 ("biodone: no buffer offset"));
2991 panic("biodone: no object");
2993 #if defined(VFS_BIO_DEBUG)
2994 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
2995 printf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2996 obj->paging_in_progress, bp->b_xio.xio_npages);
3001 * Set B_CACHE if the op was a normal read and no error
3002 * occured. B_CACHE is set for writes in the b*write()
3005 iosize = bp->b_bcount - bp->b_resid;
3006 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
3007 bp->b_flags |= B_CACHE;
3010 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3014 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3019 * cleanup bogus pages, restoring the originals. Since
3020 * the originals should still be wired, we don't have
3021 * to worry about interrupt/freeing races destroying
3022 * the VM object association.
3024 m = bp->b_xio.xio_pages[i];
3025 if (m == bogus_page) {
3027 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3029 panic("biodone: page disappeared");
3030 bp->b_xio.xio_pages[i] = m;
3031 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3032 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3034 #if defined(VFS_BIO_DEBUG)
3035 if (OFF_TO_IDX(foff) != m->pindex) {
3037 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3038 (unsigned long)foff, m->pindex);
3043 * In the write case, the valid and clean bits are
3044 * already changed correctly ( see bdwrite() ), so we
3045 * only need to do this here in the read case.
3047 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
3048 vfs_page_set_valid(bp, foff, i, m);
3050 vm_page_flag_clear(m, PG_ZERO);
3053 * when debugging new filesystems or buffer I/O methods, this
3054 * is the most common error that pops up. if you see this, you
3055 * have not set the page busy flag correctly!!!
3058 printf("biodone: page busy < 0, "
3059 "pindex: %d, foff: 0x(%x,%x), "
3060 "resid: %d, index: %d\n",
3061 (int) m->pindex, (int)(foff >> 32),
3062 (int) foff & 0xffffffff, resid, i);
3063 if (!vn_isdisk(vp, NULL))
3064 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
3065 bp->b_vp->v_mount->mnt_stat.f_iosize,
3067 bp->b_flags, bp->b_xio.xio_npages);
3069 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
3071 bp->b_flags, bp->b_xio.xio_npages);
3072 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3073 m->valid, m->dirty, m->wire_count);
3074 panic("biodone: page busy < 0");
3076 vm_page_io_finish(m);
3077 vm_object_pip_subtract(obj, 1);
3078 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3082 vm_object_pip_wakeupn(obj, 0);
3086 * For asynchronous completions, release the buffer now. The brelse
3087 * will do a wakeup there if necessary - so no need to do a wakeup
3088 * here in the async case. The sync case always needs to do a wakeup.
3091 if (bp->b_flags & B_ASYNC) {
3092 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3105 * This routine is called in lieu of iodone in the case of
3106 * incomplete I/O. This keeps the busy status for pages
3110 vfs_unbusy_pages(struct buf *bp)
3114 runningbufwakeup(bp);
3115 if (bp->b_flags & B_VMIO) {
3116 struct vnode *vp = bp->b_vp;
3119 VOP_GETVOBJECT(vp, &obj);
3121 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3122 vm_page_t m = bp->b_xio.xio_pages[i];
3125 * When restoring bogus changes the original pages
3126 * should still be wired, so we are in no danger of
3127 * losing the object association and do not need
3128 * critical section protection particularly.
3130 if (m == bogus_page) {
3131 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3133 panic("vfs_unbusy_pages: page missing");
3135 bp->b_xio.xio_pages[i] = m;
3136 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3137 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3139 vm_object_pip_subtract(obj, 1);
3140 vm_page_flag_clear(m, PG_ZERO);
3141 vm_page_io_finish(m);
3143 vm_object_pip_wakeupn(obj, 0);
3148 * vfs_page_set_valid:
3150 * Set the valid bits in a page based on the supplied offset. The
3151 * range is restricted to the buffer's size.
3153 * This routine is typically called after a read completes.
3156 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3158 vm_ooffset_t soff, eoff;
3161 * Start and end offsets in buffer. eoff - soff may not cross a
3162 * page boundry or cross the end of the buffer. The end of the
3163 * buffer, in this case, is our file EOF, not the allocation size
3167 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3168 if (eoff > bp->b_offset + bp->b_bcount)
3169 eoff = bp->b_offset + bp->b_bcount;
3172 * Set valid range. This is typically the entire buffer and thus the
3176 vm_page_set_validclean(
3178 (vm_offset_t) (soff & PAGE_MASK),
3179 (vm_offset_t) (eoff - soff)
3187 * This routine is called before a device strategy routine.
3188 * It is used to tell the VM system that paging I/O is in
3189 * progress, and treat the pages associated with the buffer
3190 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3191 * flag is handled to make sure that the object doesn't become
3194 * Since I/O has not been initiated yet, certain buffer flags
3195 * such as B_ERROR or B_INVAL may be in an inconsistant state
3196 * and should be ignored.
3199 vfs_busy_pages(struct buf *bp, int clear_modify)
3202 struct proc *p = curthread->td_proc;
3204 if (bp->b_flags & B_VMIO) {
3205 struct vnode *vp = bp->b_vp;
3209 VOP_GETVOBJECT(vp, &obj);
3210 foff = bp->b_offset;
3211 KASSERT(bp->b_offset != NOOFFSET,
3212 ("vfs_busy_pages: no buffer offset"));
3216 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3217 vm_page_t m = bp->b_xio.xio_pages[i];
3218 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3223 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3224 vm_page_t m = bp->b_xio.xio_pages[i];
3226 vm_page_flag_clear(m, PG_ZERO);
3227 if ((bp->b_flags & B_CLUSTER) == 0) {
3228 vm_object_pip_add(obj, 1);
3229 vm_page_io_start(m);
3233 * When readying a buffer for a read ( i.e
3234 * clear_modify == 0 ), it is important to do
3235 * bogus_page replacement for valid pages in
3236 * partially instantiated buffers. Partially
3237 * instantiated buffers can, in turn, occur when
3238 * reconstituting a buffer from its VM backing store
3239 * base. We only have to do this if B_CACHE is
3240 * clear ( which causes the I/O to occur in the
3241 * first place ). The replacement prevents the read
3242 * I/O from overwriting potentially dirty VM-backed
3243 * pages. XXX bogus page replacement is, uh, bogus.
3244 * It may not work properly with small-block devices.
3245 * We need to find a better way.
3248 vm_page_protect(m, VM_PROT_NONE);
3250 vfs_page_set_valid(bp, foff, i, m);
3251 else if (m->valid == VM_PAGE_BITS_ALL &&
3252 (bp->b_flags & B_CACHE) == 0) {
3253 bp->b_xio.xio_pages[i] = bogus_page;
3256 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3259 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3260 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3264 * This is the easiest place to put the process accounting for the I/O
3268 if (bp->b_flags & B_READ)
3269 p->p_stats->p_ru.ru_inblock++;
3271 p->p_stats->p_ru.ru_oublock++;
3278 * Tell the VM system that the pages associated with this buffer
3279 * are clean. This is used for delayed writes where the data is
3280 * going to go to disk eventually without additional VM intevention.
3282 * Note that while we only really need to clean through to b_bcount, we
3283 * just go ahead and clean through to b_bufsize.
3286 vfs_clean_pages(struct buf *bp)
3290 if (bp->b_flags & B_VMIO) {
3293 foff = bp->b_offset;
3294 KASSERT(bp->b_offset != NOOFFSET,
3295 ("vfs_clean_pages: no buffer offset"));
3296 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3297 vm_page_t m = bp->b_xio.xio_pages[i];
3298 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3299 vm_ooffset_t eoff = noff;
3301 if (eoff > bp->b_offset + bp->b_bufsize)
3302 eoff = bp->b_offset + bp->b_bufsize;
3303 vfs_page_set_valid(bp, foff, i, m);
3304 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3311 * vfs_bio_set_validclean:
3313 * Set the range within the buffer to valid and clean. The range is
3314 * relative to the beginning of the buffer, b_offset. Note that b_offset
3315 * itself may be offset from the beginning of the first page.
3319 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3321 if (bp->b_flags & B_VMIO) {
3326 * Fixup base to be relative to beginning of first page.
3327 * Set initial n to be the maximum number of bytes in the
3328 * first page that can be validated.
3331 base += (bp->b_offset & PAGE_MASK);
3332 n = PAGE_SIZE - (base & PAGE_MASK);
3334 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3335 vm_page_t m = bp->b_xio.xio_pages[i];
3340 vm_page_set_validclean(m, base & PAGE_MASK, n);
3351 * Clear a buffer. This routine essentially fakes an I/O, so we need
3352 * to clear B_ERROR and B_INVAL.
3354 * Note that while we only theoretically need to clear through b_bcount,
3355 * we go ahead and clear through b_bufsize.
3359 vfs_bio_clrbuf(struct buf *bp)
3363 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3364 bp->b_flags &= ~(B_INVAL|B_ERROR);
3365 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3366 (bp->b_offset & PAGE_MASK) == 0) {
3367 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3368 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3372 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3373 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3374 bzero(bp->b_data, bp->b_bufsize);
3375 bp->b_xio.xio_pages[0]->valid |= mask;
3380 ea = sa = bp->b_data;
3381 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3382 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3383 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3384 ea = (caddr_t)(vm_offset_t)ulmin(
3385 (u_long)(vm_offset_t)ea,
3386 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3387 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3388 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3390 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3391 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3395 for (; sa < ea; sa += DEV_BSIZE, j++) {
3396 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3397 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3398 bzero(sa, DEV_BSIZE);
3401 bp->b_xio.xio_pages[i]->valid |= mask;
3402 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3411 * vm_hold_load_pages:
3413 * Load pages into the buffer's address space. The pages are
3414 * allocated from the kernel object in order to reduce interference
3415 * with the any VM paging I/O activity. The range of loaded
3416 * pages will be wired.
3418 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3419 * retrieve the full range (to - from) of pages.
3423 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3429 to = round_page(to);
3430 from = round_page(from);
3431 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3433 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3438 * Note: must allocate system pages since blocking here
3439 * could intefere with paging I/O, no matter which
3442 p = vm_page_alloc(kernel_object,
3443 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3444 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3446 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3451 p->valid = VM_PAGE_BITS_ALL;
3452 vm_page_flag_clear(p, PG_ZERO);
3453 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3454 bp->b_xio.xio_pages[index] = p;
3457 bp->b_xio.xio_npages = index;
3461 * vm_hold_free_pages:
3463 * Return pages associated with the buffer back to the VM system.
3465 * The range of pages underlying the buffer's address space will
3466 * be unmapped and un-wired.
3469 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3473 int index, newnpages;
3475 from = round_page(from);
3476 to = round_page(to);
3477 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3479 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3480 p = bp->b_xio.xio_pages[index];
3481 if (p && (index < bp->b_xio.xio_npages)) {
3483 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3484 bp->b_blkno, bp->b_lblkno);
3486 bp->b_xio.xio_pages[index] = NULL;
3489 vm_page_unwire(p, 0);
3493 bp->b_xio.xio_npages = newnpages;
3499 * Map an IO request into kernel virtual address space.
3501 * All requests are (re)mapped into kernel VA space.
3502 * Notice that we use b_bufsize for the size of the buffer
3503 * to be mapped. b_bcount might be modified by the driver.
3506 vmapbuf(struct buf *bp)
3508 caddr_t addr, v, kva;
3514 if ((bp->b_flags & B_PHYS) == 0)
3516 if (bp->b_bufsize < 0)
3518 for (v = bp->b_saveaddr,
3519 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3521 addr < bp->b_data + bp->b_bufsize;
3522 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3524 * Do the vm_fault if needed; do the copy-on-write thing
3525 * when reading stuff off device into memory.
3528 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3529 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3531 for (i = 0; i < pidx; ++i) {
3532 vm_page_unhold(bp->b_xio.xio_pages[i]);
3533 bp->b_xio.xio_pages[i] = NULL;
3539 * WARNING! If sparc support is MFCd in the future this will
3540 * have to be changed from pmap_kextract() to pmap_extract()
3544 #error "If MFCing sparc support use pmap_extract"
3546 pa = pmap_kextract((vm_offset_t)addr);
3548 printf("vmapbuf: warning, race against user address during I/O");
3551 m = PHYS_TO_VM_PAGE(pa);
3553 bp->b_xio.xio_pages[pidx] = m;
3555 if (pidx > btoc(MAXPHYS))
3556 panic("vmapbuf: mapped more than MAXPHYS");
3557 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_xio.xio_pages, pidx);
3559 kva = bp->b_saveaddr;
3560 bp->b_xio.xio_npages = pidx;
3561 bp->b_saveaddr = bp->b_data;
3562 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3569 * Free the io map PTEs associated with this IO operation.
3570 * We also invalidate the TLB entries and restore the original b_addr.
3573 vunmapbuf(struct buf *bp)
3579 if ((bp->b_flags & B_PHYS) == 0)
3582 npages = bp->b_xio.xio_npages;
3583 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3585 m = bp->b_xio.xio_pages;
3586 for (pidx = 0; pidx < npages; pidx++)
3587 vm_page_unhold(*m++);
3589 bp->b_data = bp->b_saveaddr;
3593 * print out statistics from the current status of the buffer pool
3594 * this can be toggeled by the system control option debug.syncprt
3603 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3604 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3606 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3608 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3611 TAILQ_FOREACH(bp, dp, b_freelist) {
3612 counts[bp->b_bufsize/PAGE_SIZE]++;
3616 printf("%s: total-%d", bname[i], count);
3617 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3619 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
3625 #include "opt_ddb.h"
3627 #include <ddb/ddb.h>
3629 DB_SHOW_COMMAND(buffer, db_show_buffer)
3632 struct buf *bp = (struct buf *)addr;
3635 db_printf("usage: show buffer <addr>\n");
3639 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3640 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3641 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3642 "b_blkno = %d, b_pblkno = %d\n",
3643 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3644 major(bp->b_dev), minor(bp->b_dev),
3645 bp->b_data, bp->b_blkno, bp->b_pblkno);
3646 if (bp->b_xio.xio_npages) {
3648 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3649 bp->b_xio.xio_npages);
3650 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3652 m = bp->b_xio.xio_pages[i];
3653 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3654 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3655 if ((i + 1) < bp->b_xio.xio_npages)