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.46 2005/08/08 01:25:31 hmp 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 */
80 struct swqueue bswlist;
82 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
84 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
86 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
87 int pageno, vm_page_t m);
88 static void vfs_clean_pages(struct buf * bp);
89 static void vfs_setdirty(struct buf *bp);
90 static void vfs_vmio_release(struct buf *bp);
92 static void vfs_backgroundwritedone(struct buf *bp);
94 static int flushbufqueues(void);
96 static int bd_request;
98 static void buf_daemon (void);
100 * bogus page -- for I/O to/from partially complete buffers
101 * this is a temporary solution to the problem, but it is not
102 * really that bad. it would be better to split the buffer
103 * for input in the case of buffers partially already in memory,
104 * but the code is intricate enough already.
106 vm_page_t bogus_page;
107 int vmiodirenable = TRUE;
109 struct lwkt_token buftimetoken; /* Interlock on setting prio and timo */
111 static int bufspace, maxbufspace,
112 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
113 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
114 static int needsbuffer;
115 static int lorunningspace, hirunningspace, runningbufreq;
116 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
117 static int numfreebuffers, lofreebuffers, hifreebuffers;
118 static int getnewbufcalls;
119 static int getnewbufrestarts;
122 * Sysctls for operational control of the buffer cache.
124 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
125 "Number of dirty buffers to flush before bufdaemon becomes inactive");
126 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
127 "High water mark used to trigger explicit flushing of dirty buffers");
128 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
129 "Low watermark for calculating special reserve in low-memory situations");
130 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
131 "High watermark for calculating special reserve in low-memory situations");
132 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
133 "Minimum amount of buffer space required for active I/O");
134 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
135 "Maximum amount of buffer space to usable for active I/O");
136 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
137 "Use the VM system for performing directory writes");
139 * Sysctls determining current state of the buffer cache.
141 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
142 "Pending number of dirty buffers");
143 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
144 "Number of free buffers on the buffer cache free list");
145 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
146 "Amount of I/O bytes currently in progress due to asynchronous writes");
147 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
148 "Hard limit on maximum amount of memory usable for buffer space");
149 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
150 "Soft limit on maximum amount of memory usable for buffer space");
151 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
152 "Minimum amount of memory to reserve for system buffer space");
153 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
154 "Amount of memory available for buffers");
155 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
156 0, "Maximum amount of memory reserved for buffers using malloc-scheme");
157 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
158 "Amount of memory left for buffers using malloc-scheme");
159 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
160 "New buffer header acquisition requests");
161 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
162 0, "New buffer header acquisition restarts");
163 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
164 "Amount of time buffer acquisition restarted due to fragmented buffer map");
165 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
166 "Amount of time KVA space was deallocated in an arbitrary buffer");
167 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
168 "Amount of time buffer re-use operations were successful");
169 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
170 "sizeof(struct buf)");
174 * Disable background writes for now. There appear to be races in the
175 * flags tests and locking operations as well as races in the completion
176 * code modifying the original bp (origbp) without holding a lock, assuming
177 * critical section protection when there might not be critical section
180 * XXX disable also because the RB tree can't handle multiple blocks with
183 static int dobkgrdwrite = 0;
184 SYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
185 "Do background writes (honoring the BV_BKGRDWRITE flag)?");
188 static int bufhashmask;
189 static int bufhashshift;
190 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
191 char *buf_wmesg = BUF_WMESG;
193 extern int vm_swap_size;
195 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
196 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
197 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
198 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
201 * Buffer hash table code. Note that the logical block scans linearly, which
202 * gives us some L1 cache locality.
207 bufhash(struct vnode *vnp, daddr_t bn)
213 * A variation on the Fibonacci hash that Knuth credits to
214 * R. W. Floyd, see Knuth's _Art of Computer Programming,
215 * Volume 3 / Sorting and Searching_
217 * We reduce the argument to 32 bits before doing the hash to
218 * avoid the need for a slow 64x64 multiply on 32 bit platforms.
220 * sizeof(struct vnode) is 168 on i386, so toss some of the lower
221 * bits of the vnode address to reduce the key range, which
222 * improves the distribution of keys across buckets.
224 * The file system cylinder group blocks are very heavily
225 * used. They are located at invervals of fbg, which is
226 * on the order of 89 to 94 * 2^10, depending on other
227 * filesystem parameters, for a 16k block size. Smaller block
228 * sizes will reduce fpg approximately proportionally. This
229 * will cause the cylinder group index to be hashed using the
230 * lower bits of the hash multiplier, which will not distribute
231 * the keys as uniformly in a classic Fibonacci hash where a
232 * relatively small number of the upper bits of the result
233 * are used. Using 2^16 as a close-enough approximation to
234 * fpg, split the hash multiplier in half, with the upper 16
235 * bits being the inverse of the golden ratio, and the lower
236 * 16 bits being a fraction between 1/3 and 3/7 (closer to
237 * 3/7 in this case), that gives good experimental results.
239 hashkey64 = ((u_int64_t)(uintptr_t)vnp >> 3) + (u_int64_t)bn;
240 hashkey = (((u_int32_t)(hashkey64 + (hashkey64 >> 32)) * 0x9E376DB1u) >>
241 bufhashshift) & bufhashmask;
242 return(&bufhashtbl[hashkey]);
248 * If someone is blocked due to there being too many dirty buffers,
249 * and numdirtybuffers is now reasonable, wake them up.
253 numdirtywakeup(int level)
255 if (numdirtybuffers <= level) {
256 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
257 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
258 wakeup(&needsbuffer);
266 * Called when buffer space is potentially available for recovery.
267 * getnewbuf() will block on this flag when it is unable to free
268 * sufficient buffer space. Buffer space becomes recoverable when
269 * bp's get placed back in the queues.
276 * If someone is waiting for BUF space, wake them up. Even
277 * though we haven't freed the kva space yet, the waiting
278 * process will be able to now.
280 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
281 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
282 wakeup(&needsbuffer);
289 * Accounting for I/O in progress.
293 runningbufwakeup(struct buf *bp)
295 if (bp->b_runningbufspace) {
296 runningbufspace -= bp->b_runningbufspace;
297 bp->b_runningbufspace = 0;
298 if (runningbufreq && runningbufspace <= lorunningspace) {
300 wakeup(&runningbufreq);
308 * Called when a buffer has been added to one of the free queues to
309 * account for the buffer and to wakeup anyone waiting for free buffers.
310 * This typically occurs when large amounts of metadata are being handled
311 * by the buffer cache ( else buffer space runs out first, usually ).
319 needsbuffer &= ~VFS_BIO_NEED_ANY;
320 if (numfreebuffers >= hifreebuffers)
321 needsbuffer &= ~VFS_BIO_NEED_FREE;
322 wakeup(&needsbuffer);
327 * waitrunningbufspace()
329 * runningbufspace is a measure of the amount of I/O currently
330 * running. This routine is used in async-write situations to
331 * prevent creating huge backups of pending writes to a device.
332 * Only asynchronous writes are governed by this function.
334 * Reads will adjust runningbufspace, but will not block based on it.
335 * The read load has a side effect of reducing the allowed write load.
337 * This does NOT turn an async write into a sync write. It waits
338 * for earlier writes to complete and generally returns before the
339 * caller's write has reached the device.
342 waitrunningbufspace(void)
344 if (runningbufspace > hirunningspace) {
346 while (runningbufspace > hirunningspace) {
348 tsleep(&runningbufreq, 0, "wdrain", 0);
355 * vfs_buf_test_cache:
357 * Called when a buffer is extended. This function clears the B_CACHE
358 * bit if the newly extended portion of the buffer does not contain
363 vfs_buf_test_cache(struct buf *bp,
364 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
367 if (bp->b_flags & B_CACHE) {
368 int base = (foff + off) & PAGE_MASK;
369 if (vm_page_is_valid(m, base, size) == 0)
370 bp->b_flags &= ~B_CACHE;
377 * Wake up the buffer daemon if the number of outstanding dirty buffers
378 * is above specified threshold 'dirtybuflevel'.
380 * The buffer daemon is explicitly woken up when (a) the pending number
381 * of dirty buffers exceeds the recovery and stall mid-point value,
382 * (b) during bwillwrite() or (c) buf freelist was exhausted.
386 bd_wakeup(int dirtybuflevel)
388 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
397 * Speed up the buffer cache flushing process.
410 * Initialize buffer headers and related structures.
414 bufhashinit(caddr_t vaddr)
416 /* first, make a null hash table */
418 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
420 bufhashtbl = (void *)vaddr;
421 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
429 * Load time initialisation of the buffer cache, called from machine
430 * dependant initialization code.
436 vm_offset_t bogus_offset;
439 TAILQ_INIT(&bswlist);
440 LIST_INIT(&invalhash);
441 lwkt_token_init(&buftimetoken);
443 for (i = 0; i <= bufhashmask; i++)
444 LIST_INIT(&bufhashtbl[i]);
446 /* next, make a null set of free lists */
447 for (i = 0; i < BUFFER_QUEUES; i++)
448 TAILQ_INIT(&bufqueues[i]);
450 /* finally, initialize each buffer header and stick on empty q */
451 for (i = 0; i < nbuf; i++) {
453 bzero(bp, sizeof *bp);
454 bp->b_bio.bio_buf = bp; /* back pointer (temporary) */
455 bp->b_flags = B_INVAL; /* we're just an empty header */
457 bp->b_qindex = BQUEUE_EMPTY;
460 xio_init(&bp->b_xio);
461 LIST_INIT(&bp->b_dep);
463 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
464 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
468 * maxbufspace is the absolute maximum amount of buffer space we are
469 * allowed to reserve in KVM and in real terms. The absolute maximum
470 * is nominally used by buf_daemon. hibufspace is the nominal maximum
471 * used by most other processes. The differential is required to
472 * ensure that buf_daemon is able to run when other processes might
473 * be blocked waiting for buffer space.
475 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
476 * this may result in KVM fragmentation which is not handled optimally
479 maxbufspace = nbuf * BKVASIZE;
480 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
481 lobufspace = hibufspace - MAXBSIZE;
483 lorunningspace = 512 * 1024;
484 hirunningspace = 1024 * 1024;
487 * Limit the amount of malloc memory since it is wired permanently into
488 * the kernel space. Even though this is accounted for in the buffer
489 * allocation, we don't want the malloced region to grow uncontrolled.
490 * The malloc scheme improves memory utilization significantly on average
491 * (small) directories.
493 maxbufmallocspace = hibufspace / 20;
496 * Reduce the chance of a deadlock occuring by limiting the number
497 * of delayed-write dirty buffers we allow to stack up.
499 hidirtybuffers = nbuf / 4 + 20;
502 * To support extreme low-memory systems, make sure hidirtybuffers cannot
503 * eat up all available buffer space. This occurs when our minimum cannot
504 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
505 * BKVASIZE'd (8K) buffers.
507 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
508 hidirtybuffers >>= 1;
510 lodirtybuffers = hidirtybuffers / 2;
513 * Try to keep the number of free buffers in the specified range,
514 * and give special processes (e.g. like buf_daemon) access to an
517 lofreebuffers = nbuf / 18 + 5;
518 hifreebuffers = 2 * lofreebuffers;
519 numfreebuffers = nbuf;
522 * Maximum number of async ops initiated per buf_daemon loop. This is
523 * somewhat of a hack at the moment, we really need to limit ourselves
524 * based on the number of bytes of I/O in-transit that were initiated
528 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
529 bogus_page = vm_page_alloc(kernel_object,
530 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
532 vmstats.v_wire_count++;
539 * Free the KVA allocation for buffer 'bp'.
541 * Must be called from a critical section as this is the only locking for
544 * Since this call frees up buffer space, we call bufspacewakeup().
547 bfreekva(struct buf * bp)
553 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
554 vm_map_lock(buffer_map);
555 bufspace -= bp->b_kvasize;
556 vm_map_delete(buffer_map,
557 (vm_offset_t) bp->b_kvabase,
558 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
561 vm_map_unlock(buffer_map);
562 vm_map_entry_release(count);
571 * Remove the buffer from the appropriate free list.
574 bremfree(struct buf * bp)
579 old_qindex = bp->b_qindex;
581 if (bp->b_qindex != BQUEUE_NONE) {
582 KASSERT(BUF_REFCNTNB(bp) == 1,
583 ("bremfree: bp %p not locked",bp));
584 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
585 bp->b_qindex = BQUEUE_NONE;
587 if (BUF_REFCNTNB(bp) <= 1)
588 panic("bremfree: removing a buffer not on a queue");
592 * Fixup numfreebuffers count. If the buffer is invalid or not
593 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
594 * the buffer was free and we must decrement numfreebuffers.
596 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
601 case BQUEUE_EMPTYKVA:
615 * Get a buffer with the specified data. Look in the cache first. We
616 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
617 * is set, the buffer is valid and we do not have to do anything ( see
621 bread(struct vnode * vp, daddr_t blkno, int size, struct buf ** bpp)
625 bp = getblk(vp, blkno, size, 0, 0);
628 /* if not found in cache, do some I/O */
629 if ((bp->b_flags & B_CACHE) == 0) {
630 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
631 bp->b_flags |= B_READ;
632 bp->b_flags &= ~(B_ERROR | B_INVAL);
633 vfs_busy_pages(bp, 0);
634 VOP_STRATEGY(vp, bp);
635 return (biowait(bp));
643 * Operates like bread, but also starts asynchronous I/O on
644 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
645 * to initiating I/O . If B_CACHE is set, the buffer is valid
646 * and we do not have to do anything.
649 breadn(struct vnode * vp, daddr_t blkno, int size, daddr_t * rablkno,
650 int *rabsize, int cnt, struct buf ** bpp)
652 struct buf *bp, *rabp;
654 int rv = 0, readwait = 0;
656 *bpp = bp = getblk(vp, blkno, size, 0, 0);
658 /* if not found in cache, do some I/O */
659 if ((bp->b_flags & B_CACHE) == 0) {
660 bp->b_flags |= B_READ;
661 bp->b_flags &= ~(B_ERROR | B_INVAL);
662 vfs_busy_pages(bp, 0);
663 VOP_STRATEGY(vp, bp);
667 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
668 if (inmem(vp, *rablkno))
670 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
672 if ((rabp->b_flags & B_CACHE) == 0) {
673 rabp->b_flags |= B_READ | B_ASYNC;
674 rabp->b_flags &= ~(B_ERROR | B_INVAL);
675 vfs_busy_pages(rabp, 0);
677 VOP_STRATEGY(vp, rabp);
692 * Write, release buffer on completion. (Done by iodone
693 * if async). Do not bother writing anything if the buffer
696 * Note that we set B_CACHE here, indicating that buffer is
697 * fully valid and thus cacheable. This is true even of NFS
698 * now so we set it generally. This could be set either here
699 * or in biodone() since the I/O is synchronous. We put it
703 bwrite(struct buf * bp)
710 if (bp->b_flags & B_INVAL) {
715 oldflags = bp->b_flags;
717 if (BUF_REFCNTNB(bp) == 0)
718 panic("bwrite: buffer is not busy???");
721 * If a background write is already in progress, delay
722 * writing this block if it is asynchronous. Otherwise
723 * wait for the background write to complete.
725 if (bp->b_xflags & BX_BKGRDINPROG) {
726 if (bp->b_flags & B_ASYNC) {
731 bp->b_xflags |= BX_BKGRDWAIT;
732 tsleep(&bp->b_xflags, 0, "biord", 0);
733 if (bp->b_xflags & BX_BKGRDINPROG)
734 panic("bwrite: still writing");
737 /* Mark the buffer clean */
742 * If this buffer is marked for background writing and we
743 * do not have to wait for it, make a copy and write the
744 * copy so as to leave this buffer ready for further use.
746 * This optimization eats a lot of memory. If we have a page
747 * or buffer shortfull we can't do it.
749 * XXX DISABLED! This had to be removed to support the RB_TREE
750 * work and, really, this isn't the best place to do this sort
751 * of thing anyway. We really need a device copy-on-write feature.
754 (bp->b_xflags & BX_BKGRDWRITE) &&
755 (bp->b_flags & B_ASYNC) &&
756 !vm_page_count_severe() &&
757 !buf_dirty_count_severe()) {
759 panic("bwrite: need chained iodone");
761 /* get a new block */
762 newbp = geteblk(bp->b_bufsize);
764 /* set it to be identical to the old block */
765 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
766 newbp->b_lblkno = bp->b_lblkno;
767 newbp->b_blkno = bp->b_blkno;
768 newbp->b_offset = bp->b_offset;
769 newbp->b_iodone = vfs_backgroundwritedone;
770 newbp->b_flags |= B_ASYNC;
771 newbp->b_flags &= ~B_INVAL;
772 bgetvp(bp->b_vp, newbp);
774 /* move over the dependencies */
775 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
776 (*bioops.io_movedeps)(bp, newbp);
779 * Initiate write on the copy, release the original to
780 * the B_LOCKED queue so that it cannot go away until
781 * the background write completes. If not locked it could go
782 * away and then be reconstituted while it was being written.
783 * If the reconstituted buffer were written, we could end up
784 * with two background copies being written at the same time.
786 bp->b_xflags |= BX_BKGRDINPROG;
787 bp->b_flags |= B_LOCKED;
793 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
794 bp->b_flags |= B_CACHE;
796 bp->b_vp->v_numoutput++;
797 vfs_busy_pages(bp, 1);
800 * Normal bwrites pipeline writes
802 bp->b_runningbufspace = bp->b_bufsize;
803 runningbufspace += bp->b_runningbufspace;
806 if (oldflags & B_ASYNC)
808 VOP_STRATEGY(bp->b_vp, bp);
810 if ((oldflags & B_ASYNC) == 0) {
811 int rtval = biowait(bp);
814 } else if ((oldflags & B_NOWDRAIN) == 0) {
816 * don't allow the async write to saturate the I/O
817 * system. Deadlocks can occur only if a device strategy
818 * routine (like in VN) turns around and issues another
819 * high-level write, in which case B_NOWDRAIN is expected
820 * to be set. Otherwise we will not deadlock here because
821 * we are blocking waiting for I/O that is already in-progress
824 waitrunningbufspace();
832 * Complete a background write started from bwrite.
835 vfs_backgroundwritedone(struct buf *bp)
840 * Find the original buffer that we are writing.
842 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
843 panic("backgroundwritedone: lost buffer");
845 * Process dependencies then return any unfinished ones.
847 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
848 (*bioops.io_complete)(bp);
849 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
850 (*bioops.io_movedeps)(bp, origbp);
852 * Clear the BX_BKGRDINPROG flag in the original buffer
853 * and awaken it if it is waiting for the write to complete.
854 * If BX_BKGRDINPROG is not set in the original buffer it must
855 * have been released and re-instantiated - which is not legal.
857 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
858 origbp->b_xflags &= ~BX_BKGRDINPROG;
859 if (origbp->b_xflags & BX_BKGRDWAIT) {
860 origbp->b_xflags &= ~BX_BKGRDWAIT;
861 wakeup(&origbp->b_xflags);
864 * Clear the B_LOCKED flag and remove it from the locked
865 * queue if it currently resides there.
867 origbp->b_flags &= ~B_LOCKED;
868 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
873 * This buffer is marked B_NOCACHE, so when it is released
874 * by biodone, it will be tossed. We mark it with B_READ
875 * to avoid biodone doing a second vwakeup.
877 bp->b_flags |= B_NOCACHE | B_READ;
878 bp->b_flags &= ~(B_CACHE | B_DONE);
887 * Delayed write. (Buffer is marked dirty). Do not bother writing
888 * anything if the buffer is marked invalid.
890 * Note that since the buffer must be completely valid, we can safely
891 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
892 * biodone() in order to prevent getblk from writing the buffer
896 bdwrite(struct buf *bp)
898 if (BUF_REFCNTNB(bp) == 0)
899 panic("bdwrite: buffer is not busy");
901 if (bp->b_flags & B_INVAL) {
908 * Set B_CACHE, indicating that the buffer is fully valid. This is
909 * true even of NFS now.
911 bp->b_flags |= B_CACHE;
914 * This bmap keeps the system from needing to do the bmap later,
915 * perhaps when the system is attempting to do a sync. Since it
916 * is likely that the indirect block -- or whatever other datastructure
917 * that the filesystem needs is still in memory now, it is a good
918 * thing to do this. Note also, that if the pageout daemon is
919 * requesting a sync -- there might not be enough memory to do
920 * the bmap then... So, this is important to do.
922 if (bp->b_lblkno == bp->b_blkno) {
923 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
927 * Set the *dirty* buffer range based upon the VM system dirty pages.
932 * We need to do this here to satisfy the vnode_pager and the
933 * pageout daemon, so that it thinks that the pages have been
934 * "cleaned". Note that since the pages are in a delayed write
935 * buffer -- the VFS layer "will" see that the pages get written
936 * out on the next sync, or perhaps the cluster will be completed.
942 * Wakeup the buffer flushing daemon if we have a lot of dirty
943 * buffers (midpoint between our recovery point and our stall
946 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
949 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
950 * due to the softdep code.
957 * Turn buffer into delayed write request. We must clear B_READ and
958 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
959 * itself to properly update it in the dirty/clean lists. We mark it
960 * B_DONE to ensure that any asynchronization of the buffer properly
961 * clears B_DONE ( else a panic will occur later ).
963 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
964 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
965 * should only be called if the buffer is known-good.
967 * Since the buffer is not on a queue, we do not update the numfreebuffers
970 * Must be called from a critical section.
971 * The buffer must be on BQUEUE_NONE.
974 bdirty(struct buf *bp)
976 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
977 bp->b_flags &= ~(B_READ|B_RELBUF);
979 if ((bp->b_flags & B_DELWRI) == 0) {
980 bp->b_flags |= B_DONE | B_DELWRI;
981 reassignbuf(bp, bp->b_vp);
983 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
990 * Clear B_DELWRI for buffer.
992 * Since the buffer is not on a queue, we do not update the numfreebuffers
995 * Must be called from a critical section.
997 * The buffer is typically on BQUEUE_NONE but there is one case in
998 * brelse() that calls this function after placing the buffer on
1003 bundirty(struct buf *bp)
1005 if (bp->b_flags & B_DELWRI) {
1006 bp->b_flags &= ~B_DELWRI;
1007 reassignbuf(bp, bp->b_vp);
1009 numdirtywakeup(lodirtybuffers);
1012 * Since it is now being written, we can clear its deferred write flag.
1014 bp->b_flags &= ~B_DEFERRED;
1020 * Asynchronous write. Start output on a buffer, but do not wait for
1021 * it to complete. The buffer is released when the output completes.
1023 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1024 * B_INVAL buffers. Not us.
1027 bawrite(struct buf * bp)
1029 bp->b_flags |= B_ASYNC;
1030 (void) VOP_BWRITE(bp->b_vp, bp);
1036 * Ordered write. Start output on a buffer, and flag it so that the
1037 * device will write it in the order it was queued. The buffer is
1038 * released when the output completes. bwrite() ( or the VOP routine
1039 * anyway ) is responsible for handling B_INVAL buffers.
1042 bowrite(struct buf * bp)
1044 bp->b_flags |= B_ORDERED | B_ASYNC;
1045 return (VOP_BWRITE(bp->b_vp, bp));
1051 * Called prior to the locking of any vnodes when we are expecting to
1052 * write. We do not want to starve the buffer cache with too many
1053 * dirty buffers so we block here. By blocking prior to the locking
1054 * of any vnodes we attempt to avoid the situation where a locked vnode
1055 * prevents the various system daemons from flushing related buffers.
1061 if (numdirtybuffers >= hidirtybuffers) {
1063 while (numdirtybuffers >= hidirtybuffers) {
1065 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1066 tsleep(&needsbuffer, 0, "flswai", 0);
1073 * buf_dirty_count_severe:
1075 * Return true if we have too many dirty buffers.
1078 buf_dirty_count_severe(void)
1080 return(numdirtybuffers >= hidirtybuffers);
1086 * Release a busy buffer and, if requested, free its resources. The
1087 * buffer will be stashed in the appropriate bufqueue[] allowing it
1088 * to be accessed later as a cache entity or reused for other purposes.
1091 brelse(struct buf * bp)
1094 int saved_flags = bp->b_flags;
1097 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1101 if (bp->b_flags & B_LOCKED)
1102 bp->b_flags &= ~B_ERROR;
1104 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
1106 * Failed write, redirty. Must clear B_ERROR to prevent
1107 * pages from being scrapped. If B_INVAL is set then
1108 * this case is not run and the next case is run to
1109 * destroy the buffer. B_INVAL can occur if the buffer
1110 * is outside the range supported by the underlying device.
1112 bp->b_flags &= ~B_ERROR;
1114 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
1115 (bp->b_bufsize <= 0)) {
1117 * Either a failed I/O or we were asked to free or not
1120 bp->b_flags |= B_INVAL;
1121 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1122 (*bioops.io_deallocate)(bp);
1123 if (bp->b_flags & B_DELWRI) {
1125 numdirtywakeup(lodirtybuffers);
1127 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
1131 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1132 * is called with B_DELWRI set, the underlying pages may wind up
1133 * getting freed causing a previous write (bdwrite()) to get 'lost'
1134 * because pages associated with a B_DELWRI bp are marked clean.
1136 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1137 * if B_DELWRI is set.
1139 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1140 * on pages to return pages to the VM page queues.
1142 if (bp->b_flags & B_DELWRI)
1143 bp->b_flags &= ~B_RELBUF;
1144 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1145 bp->b_flags |= B_RELBUF;
1148 * At this point destroying the buffer is governed by the B_INVAL
1149 * or B_RELBUF flags.
1153 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1154 * constituted, not even NFS buffers now. Two flags effect this. If
1155 * B_INVAL, the struct buf is invalidated but the VM object is kept
1156 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1158 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1159 * invalidated. B_ERROR cannot be set for a failed write unless the
1160 * buffer is also B_INVAL because it hits the re-dirtying code above.
1162 * Normally we can do this whether a buffer is B_DELWRI or not. If
1163 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1164 * the commit state and we cannot afford to lose the buffer. If the
1165 * buffer has a background write in progress, we need to keep it
1166 * around to prevent it from being reconstituted and starting a second
1169 if ((bp->b_flags & B_VMIO)
1170 && !(bp->b_vp->v_tag == VT_NFS &&
1171 !vn_isdisk(bp->b_vp, NULL) &&
1172 (bp->b_flags & B_DELWRI))
1175 * Rundown for VMIO buffers which are not dirty NFS buffers.
1187 * Get the base offset and length of the buffer. Note that
1188 * in the VMIO case if the buffer block size is not
1189 * page-aligned then b_data pointer may not be page-aligned.
1190 * But our b_xio.xio_pages array *IS* page aligned.
1192 * block sizes less then DEV_BSIZE (usually 512) are not
1193 * supported due to the page granularity bits (m->valid,
1194 * m->dirty, etc...).
1196 * See man buf(9) for more information
1199 resid = bp->b_bufsize;
1200 foff = bp->b_offset;
1202 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1203 m = bp->b_xio.xio_pages[i];
1204 vm_page_flag_clear(m, PG_ZERO);
1206 * If we hit a bogus page, fixup *all* of them
1207 * now. Note that we left these pages wired
1208 * when we removed them so they had better exist,
1209 * and they cannot be ripped out from under us so
1210 * no critical section protection is necessary.
1212 if (m == bogus_page) {
1213 VOP_GETVOBJECT(vp, &obj);
1214 poff = OFF_TO_IDX(bp->b_offset);
1216 for (j = i; j < bp->b_xio.xio_npages; j++) {
1219 mtmp = bp->b_xio.xio_pages[j];
1220 if (mtmp == bogus_page) {
1221 mtmp = vm_page_lookup(obj, poff + j);
1223 panic("brelse: page missing");
1225 bp->b_xio.xio_pages[j] = mtmp;
1229 if ((bp->b_flags & B_INVAL) == 0) {
1230 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1231 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1233 m = bp->b_xio.xio_pages[i];
1237 * Invalidate the backing store if B_NOCACHE is set
1238 * (e.g. used with vinvalbuf()). If this is NFS
1239 * we impose a requirement that the block size be
1240 * a multiple of PAGE_SIZE and create a temporary
1241 * hack to basically invalidate the whole page. The
1242 * problem is that NFS uses really odd buffer sizes
1243 * especially when tracking piecemeal writes and
1244 * it also vinvalbuf()'s a lot, which would result
1245 * in only partial page validation and invalidation
1246 * here. If the file page is mmap()'d, however,
1247 * all the valid bits get set so after we invalidate
1248 * here we would end up with weird m->valid values
1249 * like 0xfc. nfs_getpages() can't handle this so
1250 * we clear all the valid bits for the NFS case
1251 * instead of just some of them.
1253 * The real bug is the VM system having to set m->valid
1254 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1255 * itself is an artifact of the whole 512-byte
1256 * granular mess that exists to support odd block
1257 * sizes and UFS meta-data block sizes (e.g. 6144).
1258 * A complete rewrite is required.
1260 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1261 int poffset = foff & PAGE_MASK;
1264 presid = PAGE_SIZE - poffset;
1265 if (bp->b_vp->v_tag == VT_NFS &&
1266 bp->b_vp->v_type == VREG) {
1268 } else if (presid > resid) {
1271 KASSERT(presid >= 0, ("brelse: extra page"));
1272 vm_page_set_invalid(m, poffset, presid);
1274 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1275 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1277 if (bp->b_flags & (B_INVAL | B_RELBUF))
1278 vfs_vmio_release(bp);
1279 } else if (bp->b_flags & B_VMIO) {
1281 * Rundown for VMIO buffers which are dirty NFS buffers. Such
1282 * buffers contain tracking ranges for NFS and cannot normally
1283 * be released. Due to the dirty check above this series of
1284 * conditionals, B_RELBUF probably will never be set in this
1287 if (bp->b_flags & (B_INVAL | B_RELBUF))
1288 vfs_vmio_release(bp);
1291 * Rundown for non-VMIO buffers.
1293 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1296 printf("brelse bp %p %08x/%08lx: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1305 if (bp->b_qindex != BQUEUE_NONE)
1306 panic("brelse: free buffer onto another queue???");
1307 if (BUF_REFCNTNB(bp) > 1) {
1308 /* Temporary panic to verify exclusive locking */
1309 /* This panic goes away when we allow shared refs */
1310 panic("brelse: multiple refs");
1311 /* do not release to free list */
1318 * Figure out the correct queue to place the cleaned up buffer on.
1319 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1320 * disassociated from their vnode.
1323 if (bp->b_bufsize == 0) {
1325 * Buffers with no memory. Due to conditionals near the top
1326 * of brelse() such buffers should probably already be
1327 * marked B_INVAL and disassociated from their vnode.
1329 bp->b_flags |= B_INVAL;
1330 bp->b_xflags &= ~BX_BKGRDWRITE;
1331 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08lx vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1332 if (bp->b_xflags & BX_BKGRDINPROG)
1333 panic("losing buffer 1");
1334 if (bp->b_kvasize) {
1335 bp->b_qindex = BQUEUE_EMPTYKVA;
1337 bp->b_qindex = BQUEUE_EMPTY;
1339 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1340 LIST_REMOVE(bp, b_hash);
1341 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1343 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1345 * Buffers with junk contents. Again these buffers had better
1346 * already be disassociated from their vnode.
1348 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08lx vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1349 bp->b_flags |= B_INVAL;
1350 bp->b_xflags &= ~BX_BKGRDWRITE;
1351 if (bp->b_xflags & BX_BKGRDINPROG)
1352 panic("losing buffer 2");
1353 bp->b_qindex = BQUEUE_CLEAN;
1354 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1355 LIST_REMOVE(bp, b_hash);
1356 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1358 } else if (bp->b_flags & B_LOCKED) {
1360 * Buffers that are locked.
1362 bp->b_qindex = BQUEUE_LOCKED;
1363 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1366 * Remaining buffers. These buffers are still associated with
1369 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1370 case B_DELWRI | B_AGE:
1371 bp->b_qindex = BQUEUE_DIRTY;
1372 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1375 bp->b_qindex = BQUEUE_DIRTY;
1376 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1379 bp->b_qindex = BQUEUE_CLEAN;
1380 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1383 bp->b_qindex = BQUEUE_CLEAN;
1384 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1390 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1391 * on the correct queue.
1393 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1397 * Fixup numfreebuffers count. The bp is on an appropriate queue
1398 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1399 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1400 * if B_INVAL is set ).
1402 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1406 * Something we can maybe free or reuse
1408 if (bp->b_bufsize || bp->b_kvasize)
1413 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1414 B_DIRECT | B_NOWDRAIN);
1421 * Release a buffer back to the appropriate queue but do not try to free
1422 * it. The buffer is expected to be used again soon.
1424 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1425 * biodone() to requeue an async I/O on completion. It is also used when
1426 * known good buffers need to be requeued but we think we may need the data
1429 * XXX we should be able to leave the B_RELBUF hint set on completion.
1432 bqrelse(struct buf * bp)
1436 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1438 if (bp->b_qindex != BQUEUE_NONE)
1439 panic("bqrelse: free buffer onto another queue???");
1440 if (BUF_REFCNTNB(bp) > 1) {
1441 /* do not release to free list */
1442 panic("bqrelse: multiple refs");
1447 if (bp->b_flags & B_LOCKED) {
1448 bp->b_flags &= ~B_ERROR;
1449 bp->b_qindex = BQUEUE_LOCKED;
1450 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1451 /* buffers with stale but valid contents */
1452 } else if (bp->b_flags & B_DELWRI) {
1453 bp->b_qindex = BQUEUE_DIRTY;
1454 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1455 } else if (vm_page_count_severe()) {
1457 * We are too low on memory, we have to try to free the
1458 * buffer (most importantly: the wired pages making up its
1459 * backing store) *now*.
1465 bp->b_qindex = BQUEUE_CLEAN;
1466 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1469 if ((bp->b_flags & B_LOCKED) == 0 &&
1470 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1475 * Something we can maybe free or reuse.
1477 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1481 * Final cleanup and unlock. Clear bits that are only used while a
1482 * buffer is actively locked.
1484 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1492 * Return backing pages held by the buffer 'bp' back to the VM system
1493 * if possible. The pages are freed if they are no longer valid or
1494 * attempt to free if it was used for direct I/O otherwise they are
1495 * sent to the page cache.
1497 * Pages that were marked busy are left alone and skipped.
1499 * The KVA mapping (b_data) for the underlying pages is removed by
1503 vfs_vmio_release(struct buf *bp)
1509 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1510 m = bp->b_xio.xio_pages[i];
1511 bp->b_xio.xio_pages[i] = NULL;
1513 * In order to keep page LRU ordering consistent, put
1514 * everything on the inactive queue.
1516 vm_page_unwire(m, 0);
1518 * We don't mess with busy pages, it is
1519 * the responsibility of the process that
1520 * busied the pages to deal with them.
1522 if ((m->flags & PG_BUSY) || (m->busy != 0))
1525 if (m->wire_count == 0) {
1526 vm_page_flag_clear(m, PG_ZERO);
1528 * Might as well free the page if we can and it has
1529 * no valid data. We also free the page if the
1530 * buffer was used for direct I/O.
1532 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1533 m->hold_count == 0) {
1535 vm_page_protect(m, VM_PROT_NONE);
1537 } else if (bp->b_flags & B_DIRECT) {
1538 vm_page_try_to_free(m);
1539 } else if (vm_page_count_severe()) {
1540 vm_page_try_to_cache(m);
1545 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1546 if (bp->b_bufsize) {
1550 bp->b_xio.xio_npages = 0;
1551 bp->b_flags &= ~B_VMIO;
1559 * Check to see if a block is currently memory resident.
1562 gbincore(struct vnode * vp, daddr_t blkno)
1565 struct bufhashhdr *bh;
1567 bh = bufhash(vp, blkno);
1568 LIST_FOREACH(bp, bh, b_hash) {
1569 if (bp->b_vp == vp && bp->b_lblkno == blkno)
1578 * Implement clustered async writes for clearing out B_DELWRI buffers.
1579 * This is much better then the old way of writing only one buffer at
1580 * a time. Note that we may not be presented with the buffers in the
1581 * correct order, so we search for the cluster in both directions.
1584 vfs_bio_awrite(struct buf * bp)
1588 daddr_t lblkno = bp->b_lblkno;
1589 struct vnode *vp = bp->b_vp;
1598 * right now we support clustered writing only to regular files. If
1599 * we find a clusterable block we could be in the middle of a cluster
1600 * rather then at the beginning.
1602 if ((vp->v_type == VREG) &&
1603 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1604 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1606 size = vp->v_mount->mnt_stat.f_iosize;
1607 maxcl = MAXPHYS / size;
1609 for (i = 1; i < maxcl; i++) {
1610 if ((bpa = gbincore(vp, lblkno + i)) &&
1611 BUF_REFCNT(bpa) == 0 &&
1612 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1613 (B_DELWRI | B_CLUSTEROK)) &&
1614 (bpa->b_bufsize == size)) {
1615 if ((bpa->b_blkno == bpa->b_lblkno) ||
1617 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1623 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1624 if ((bpa = gbincore(vp, lblkno - j)) &&
1625 BUF_REFCNT(bpa) == 0 &&
1626 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1627 (B_DELWRI | B_CLUSTEROK)) &&
1628 (bpa->b_bufsize == size)) {
1629 if ((bpa->b_blkno == bpa->b_lblkno) ||
1631 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1640 * this is a possible cluster write
1643 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1649 BUF_LOCK(bp, LK_EXCLUSIVE);
1651 bp->b_flags |= B_ASYNC;
1655 * default (old) behavior, writing out only one block
1657 * XXX returns b_bufsize instead of b_bcount for nwritten?
1659 nwritten = bp->b_bufsize;
1660 (void) VOP_BWRITE(bp->b_vp, bp);
1668 * Find and initialize a new buffer header, freeing up existing buffers
1669 * in the bufqueues as necessary. The new buffer is returned locked.
1671 * Important: B_INVAL is not set. If the caller wishes to throw the
1672 * buffer away, the caller must set B_INVAL prior to calling brelse().
1675 * We have insufficient buffer headers
1676 * We have insufficient buffer space
1677 * buffer_map is too fragmented ( space reservation fails )
1678 * If we have to flush dirty buffers ( but we try to avoid this )
1680 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1681 * Instead we ask the buf daemon to do it for us. We attempt to
1682 * avoid piecemeal wakeups of the pageout daemon.
1686 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1692 static int flushingbufs;
1695 * We can't afford to block since we might be holding a vnode lock,
1696 * which may prevent system daemons from running. We deal with
1697 * low-memory situations by proactively returning memory and running
1698 * async I/O rather then sync I/O.
1702 --getnewbufrestarts;
1704 ++getnewbufrestarts;
1707 * Setup for scan. If we do not have enough free buffers,
1708 * we setup a degenerate case that immediately fails. Note
1709 * that if we are specially marked process, we are allowed to
1710 * dip into our reserves.
1712 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1714 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1715 * However, there are a number of cases (defragging, reusing, ...)
1716 * where we cannot backup.
1718 nqindex = BQUEUE_EMPTYKVA;
1719 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1723 * If no EMPTYKVA buffers and we are either
1724 * defragging or reusing, locate a CLEAN buffer
1725 * to free or reuse. If bufspace useage is low
1726 * skip this step so we can allocate a new buffer.
1728 if (defrag || bufspace >= lobufspace) {
1729 nqindex = BQUEUE_CLEAN;
1730 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1734 * If we could not find or were not allowed to reuse a
1735 * CLEAN buffer, check to see if it is ok to use an EMPTY
1736 * buffer. We can only use an EMPTY buffer if allocating
1737 * its KVA would not otherwise run us out of buffer space.
1739 if (nbp == NULL && defrag == 0 &&
1740 bufspace + maxsize < hibufspace) {
1741 nqindex = BQUEUE_EMPTY;
1742 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1747 * Run scan, possibly freeing data and/or kva mappings on the fly
1751 while ((bp = nbp) != NULL) {
1752 int qindex = nqindex;
1755 * Calculate next bp ( we can only use it if we do not block
1756 * or do other fancy things ).
1758 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1761 nqindex = BQUEUE_EMPTYKVA;
1762 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1765 case BQUEUE_EMPTYKVA:
1766 nqindex = BQUEUE_CLEAN;
1767 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1781 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1784 * Note: we no longer distinguish between VMIO and non-VMIO
1788 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1791 * If we are defragging then we need a buffer with
1792 * b_kvasize != 0. XXX this situation should no longer
1793 * occur, if defrag is non-zero the buffer's b_kvasize
1794 * should also be non-zero at this point. XXX
1796 if (defrag && bp->b_kvasize == 0) {
1797 printf("Warning: defrag empty buffer %p\n", bp);
1802 * Start freeing the bp. This is somewhat involved. nbp
1803 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1804 * on the clean list must be disassociated from their
1805 * current vnode. Buffers on the empty[kva] lists have
1806 * already been disassociated.
1809 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1810 panic("getnewbuf: locked buf");
1813 if (qindex == BQUEUE_CLEAN) {
1814 if (bp->b_flags & B_VMIO) {
1815 bp->b_flags &= ~B_ASYNC;
1816 vfs_vmio_release(bp);
1823 * NOTE: nbp is now entirely invalid. We can only restart
1824 * the scan from this point on.
1826 * Get the rest of the buffer freed up. b_kva* is still
1827 * valid after this operation.
1830 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08lx vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1831 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1832 (*bioops.io_deallocate)(bp);
1833 if (bp->b_xflags & BX_BKGRDINPROG)
1834 panic("losing buffer 3");
1835 LIST_REMOVE(bp, b_hash);
1836 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1839 * critical section protection is not required when
1840 * scrapping a buffer's contents because it is already
1850 bp->b_blkno = bp->b_lblkno = 0;
1851 bp->b_offset = NOOFFSET;
1852 bp->b_iodone = NULL;
1856 bp->b_xio.xio_npages = 0;
1857 bp->b_dirtyoff = bp->b_dirtyend = 0;
1859 LIST_INIT(&bp->b_dep);
1862 * If we are defragging then free the buffer.
1865 bp->b_flags |= B_INVAL;
1873 * If we are overcomitted then recover the buffer and its
1874 * KVM space. This occurs in rare situations when multiple
1875 * processes are blocked in getnewbuf() or allocbuf().
1877 if (bufspace >= hibufspace)
1879 if (flushingbufs && bp->b_kvasize != 0) {
1880 bp->b_flags |= B_INVAL;
1885 if (bufspace < lobufspace)
1891 * If we exhausted our list, sleep as appropriate. We may have to
1892 * wakeup various daemons and write out some dirty buffers.
1894 * Generally we are sleeping due to insufficient buffer space.
1902 flags = VFS_BIO_NEED_BUFSPACE;
1904 } else if (bufspace >= hibufspace) {
1906 flags = VFS_BIO_NEED_BUFSPACE;
1909 flags = VFS_BIO_NEED_ANY;
1912 bd_speedup(); /* heeeelp */
1914 needsbuffer |= flags;
1915 while (needsbuffer & flags) {
1916 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
1921 * We finally have a valid bp. We aren't quite out of the
1922 * woods, we still have to reserve kva space. In order
1923 * to keep fragmentation sane we only allocate kva in
1926 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1928 if (maxsize != bp->b_kvasize) {
1929 vm_offset_t addr = 0;
1934 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1935 vm_map_lock(buffer_map);
1937 if (vm_map_findspace(buffer_map,
1938 vm_map_min(buffer_map), maxsize,
1941 * Uh oh. Buffer map is too fragmented. We
1942 * must defragment the map.
1944 vm_map_unlock(buffer_map);
1945 vm_map_entry_release(count);
1948 bp->b_flags |= B_INVAL;
1953 vm_map_insert(buffer_map, &count,
1955 addr, addr + maxsize,
1956 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1958 bp->b_kvabase = (caddr_t) addr;
1959 bp->b_kvasize = maxsize;
1960 bufspace += bp->b_kvasize;
1963 vm_map_unlock(buffer_map);
1964 vm_map_entry_release(count);
1966 bp->b_data = bp->b_kvabase;
1974 * Buffer flushing daemon. Buffers are normally flushed by the
1975 * update daemon but if it cannot keep up this process starts to
1976 * take the load in an attempt to prevent getnewbuf() from blocking.
1979 static struct thread *bufdaemonthread;
1981 static struct kproc_desc buf_kp = {
1986 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1992 * This process needs to be suspended prior to shutdown sync.
1994 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1995 bufdaemonthread, SHUTDOWN_PRI_LAST);
1998 * This process is allowed to take the buffer cache to the limit
2003 kproc_suspend_loop();
2006 * Do the flush. Limit the amount of in-transit I/O we
2007 * allow to build up, otherwise we would completely saturate
2008 * the I/O system. Wakeup any waiting processes before we
2009 * normally would so they can run in parallel with our drain.
2011 while (numdirtybuffers > lodirtybuffers) {
2012 if (flushbufqueues() == 0)
2014 waitrunningbufspace();
2015 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2019 * Only clear bd_request if we have reached our low water
2020 * mark. The buf_daemon normally waits 5 seconds and
2021 * then incrementally flushes any dirty buffers that have
2022 * built up, within reason.
2024 * If we were unable to hit our low water mark and couldn't
2025 * find any flushable buffers, we sleep half a second.
2026 * Otherwise we loop immediately.
2028 if (numdirtybuffers <= lodirtybuffers) {
2030 * We reached our low water mark, reset the
2031 * request and sleep until we are needed again.
2032 * The sleep is just so the suspend code works.
2035 tsleep(&bd_request, 0, "psleep", hz);
2038 * We couldn't find any flushable dirty buffers but
2039 * still have too many dirty buffers, we
2040 * have to sleep and try again. (rare)
2042 tsleep(&bd_request, 0, "qsleep", hz / 2);
2050 * Try to flush a buffer in the dirty queue. We must be careful to
2051 * free up B_INVAL buffers instead of write them, which NFS is
2052 * particularly sensitive to.
2056 flushbufqueues(void)
2061 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
2064 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
2065 if ((bp->b_flags & B_DELWRI) != 0 &&
2066 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
2067 if (bp->b_flags & B_INVAL) {
2068 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2069 panic("flushbufqueues: locked buf");
2075 if (LIST_FIRST(&bp->b_dep) != NULL &&
2076 bioops.io_countdeps &&
2077 (bp->b_flags & B_DEFERRED) == 0 &&
2078 (*bioops.io_countdeps)(bp, 0)) {
2079 TAILQ_REMOVE(&bufqueues[BQUEUE_DIRTY],
2081 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY],
2083 bp->b_flags |= B_DEFERRED;
2084 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
2091 bp = TAILQ_NEXT(bp, b_freelist);
2099 * Check to see if a block is currently resident in memory.
2102 incore(struct vnode * vp, daddr_t blkno)
2107 bp = gbincore(vp, blkno);
2115 * Returns true if no I/O is needed to access the associated VM object.
2116 * This is like incore except it also hunts around in the VM system for
2119 * Note that we ignore vm_page_free() races from interrupts against our
2120 * lookup, since if the caller is not protected our return value will not
2121 * be any more valid then otherwise once we exit the critical section.
2124 inmem(struct vnode * vp, daddr_t blkno)
2127 vm_offset_t toff, tinc, size;
2131 if (incore(vp, blkno))
2133 if (vp->v_mount == NULL)
2135 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
2139 if (size > vp->v_mount->mnt_stat.f_iosize)
2140 size = vp->v_mount->mnt_stat.f_iosize;
2141 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2143 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2144 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2148 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2149 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2150 if (vm_page_is_valid(m,
2151 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2160 * Sets the dirty range for a buffer based on the status of the dirty
2161 * bits in the pages comprising the buffer.
2163 * The range is limited to the size of the buffer.
2165 * This routine is primarily used by NFS, but is generalized for the
2169 vfs_setdirty(struct buf *bp)
2175 * Degenerate case - empty buffer
2178 if (bp->b_bufsize == 0)
2182 * We qualify the scan for modified pages on whether the
2183 * object has been flushed yet. The OBJ_WRITEABLE flag
2184 * is not cleared simply by protecting pages off.
2187 if ((bp->b_flags & B_VMIO) == 0)
2190 object = bp->b_xio.xio_pages[0]->object;
2192 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2193 printf("Warning: object %p writeable but not mightbedirty\n", object);
2194 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2195 printf("Warning: object %p mightbedirty but not writeable\n", object);
2197 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2198 vm_offset_t boffset;
2199 vm_offset_t eoffset;
2202 * test the pages to see if they have been modified directly
2203 * by users through the VM system.
2205 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2206 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2207 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2211 * Calculate the encompassing dirty range, boffset and eoffset,
2212 * (eoffset - boffset) bytes.
2215 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2216 if (bp->b_xio.xio_pages[i]->dirty)
2219 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2221 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2222 if (bp->b_xio.xio_pages[i]->dirty) {
2226 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2229 * Fit it to the buffer.
2232 if (eoffset > bp->b_bcount)
2233 eoffset = bp->b_bcount;
2236 * If we have a good dirty range, merge with the existing
2240 if (boffset < eoffset) {
2241 if (bp->b_dirtyoff > boffset)
2242 bp->b_dirtyoff = boffset;
2243 if (bp->b_dirtyend < eoffset)
2244 bp->b_dirtyend = eoffset;
2252 * Get a block given a specified block and offset into a file/device.
2253 * The buffers B_DONE bit will be cleared on return, making it almost
2254 * ready for an I/O initiation. B_INVAL may or may not be set on
2255 * return. The caller should clear B_INVAL prior to initiating a
2258 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2259 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2260 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2261 * without doing any of those things the system will likely believe
2262 * the buffer to be valid (especially if it is not B_VMIO), and the
2263 * next getblk() will return the buffer with B_CACHE set.
2265 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2266 * an existing buffer.
2268 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2269 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2270 * and then cleared based on the backing VM. If the previous buffer is
2271 * non-0-sized but invalid, B_CACHE will be cleared.
2273 * If getblk() must create a new buffer, the new buffer is returned with
2274 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2275 * case it is returned with B_INVAL clear and B_CACHE set based on the
2278 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2279 * B_CACHE bit is clear.
2281 * What this means, basically, is that the caller should use B_CACHE to
2282 * determine whether the buffer is fully valid or not and should clear
2283 * B_INVAL prior to issuing a read. If the caller intends to validate
2284 * the buffer by loading its data area with something, the caller needs
2285 * to clear B_INVAL. If the caller does this without issuing an I/O,
2286 * the caller should set B_CACHE ( as an optimization ), else the caller
2287 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2288 * a write attempt or if it was a successfull read. If the caller
2289 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2290 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2293 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2296 struct bufhashhdr *bh;
2298 if (size > MAXBSIZE)
2299 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2304 * Block if we are low on buffers. Certain processes are allowed
2305 * to completely exhaust the buffer cache.
2307 * If this check ever becomes a bottleneck it may be better to
2308 * move it into the else, when gbincore() fails. At the moment
2309 * it isn't a problem.
2311 * XXX remove, we cannot afford to block anywhere if holding a vnode
2312 * lock in low-memory situation, so take it to the max.
2314 if (numfreebuffers == 0) {
2317 needsbuffer |= VFS_BIO_NEED_ANY;
2318 tsleep(&needsbuffer, slpflag, "newbuf", slptimeo);
2321 if ((bp = gbincore(vp, blkno))) {
2323 * Buffer is in-core. If the buffer is not busy, it must
2327 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2328 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2329 "getblk", slpflag, slptimeo) == ENOLCK)
2332 return (struct buf *) NULL;
2336 * The buffer is locked. B_CACHE is cleared if the buffer is
2337 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
2338 * and for a VMIO buffer B_CACHE is adjusted according to the
2341 if (bp->b_flags & B_INVAL)
2342 bp->b_flags &= ~B_CACHE;
2343 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2344 bp->b_flags |= B_CACHE;
2348 * check for size inconsistancies for non-VMIO case.
2351 if (bp->b_bcount != size) {
2352 if ((bp->b_flags & B_VMIO) == 0 ||
2353 (size > bp->b_kvasize)) {
2354 if (bp->b_flags & B_DELWRI) {
2355 bp->b_flags |= B_NOCACHE;
2356 VOP_BWRITE(bp->b_vp, bp);
2358 if ((bp->b_flags & B_VMIO) &&
2359 (LIST_FIRST(&bp->b_dep) == NULL)) {
2360 bp->b_flags |= B_RELBUF;
2363 bp->b_flags |= B_NOCACHE;
2364 VOP_BWRITE(bp->b_vp, bp);
2372 * If the size is inconsistant in the VMIO case, we can resize
2373 * the buffer. This might lead to B_CACHE getting set or
2374 * cleared. If the size has not changed, B_CACHE remains
2375 * unchanged from its previous state.
2378 if (bp->b_bcount != size)
2381 KASSERT(bp->b_offset != NOOFFSET,
2382 ("getblk: no buffer offset"));
2385 * A buffer with B_DELWRI set and B_CACHE clear must
2386 * be committed before we can return the buffer in
2387 * order to prevent the caller from issuing a read
2388 * ( due to B_CACHE not being set ) and overwriting
2391 * Most callers, including NFS and FFS, need this to
2392 * operate properly either because they assume they
2393 * can issue a read if B_CACHE is not set, or because
2394 * ( for example ) an uncached B_DELWRI might loop due
2395 * to softupdates re-dirtying the buffer. In the latter
2396 * case, B_CACHE is set after the first write completes,
2397 * preventing further loops.
2399 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2400 * above while extending the buffer, we cannot allow the
2401 * buffer to remain with B_CACHE set after the write
2402 * completes or it will represent a corrupt state. To
2403 * deal with this we set B_NOCACHE to scrap the buffer
2406 * We might be able to do something fancy, like setting
2407 * B_CACHE in bwrite() except if B_DELWRI is already set,
2408 * so the below call doesn't set B_CACHE, but that gets real
2409 * confusing. This is much easier.
2412 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2413 bp->b_flags |= B_NOCACHE;
2414 VOP_BWRITE(bp->b_vp, bp);
2419 bp->b_flags &= ~B_DONE;
2422 * Buffer is not in-core, create new buffer. The buffer
2423 * returned by getnewbuf() is locked. Note that the returned
2424 * buffer is also considered valid (not marked B_INVAL).
2426 * Calculating the offset for the I/O requires figuring out
2427 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2428 * the mount's f_iosize otherwise. If the vnode does not
2429 * have an associated mount we assume that the passed size is
2432 * Note that vn_isdisk() cannot be used here since it may
2433 * return a failure for numerous reasons. Note that the
2434 * buffer size may be larger then the block size (the caller
2435 * will use block numbers with the proper multiple). Beware
2436 * of using any v_* fields which are part of unions. In
2437 * particular, in DragonFly the mount point overloading
2438 * mechanism is such that the underlying directory (with a
2439 * non-NULL v_mountedhere) is not a special case.
2441 int bsize, maxsize, vmio;
2444 if (vp->v_type == VBLK || vp->v_type == VCHR)
2446 else if (vp->v_mount)
2447 bsize = vp->v_mount->mnt_stat.f_iosize;
2451 offset = (off_t)blkno * bsize;
2452 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2453 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2454 maxsize = imax(maxsize, bsize);
2456 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2457 if (slpflag || slptimeo) {
2465 * This code is used to make sure that a buffer is not
2466 * created while the getnewbuf routine is blocked.
2467 * This can be a problem whether the vnode is locked or not.
2468 * If the buffer is created out from under us, we have to
2469 * throw away the one we just created. There is now window
2470 * race because we are safely running in a critical section
2471 * from the point of the duplicate buffer creation through
2472 * to here, and we've locked the buffer.
2474 if (gbincore(vp, blkno)) {
2475 bp->b_flags |= B_INVAL;
2481 * Insert the buffer into the hash, so that it can
2482 * be found by incore. bgetvp() and bufhash()
2483 * must be synchronized with each other.
2485 bp->b_blkno = bp->b_lblkno = blkno;
2486 bp->b_offset = offset;
2489 LIST_REMOVE(bp, b_hash);
2490 bh = bufhash(vp, blkno);
2491 LIST_INSERT_HEAD(bh, bp, b_hash);
2494 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2495 * buffer size starts out as 0, B_CACHE will be set by
2496 * allocbuf() for the VMIO case prior to it testing the
2497 * backing store for validity.
2501 bp->b_flags |= B_VMIO;
2502 #if defined(VFS_BIO_DEBUG)
2503 if (vn_canvmio(vp) != TRUE)
2504 printf("getblk: vmioing file type %d???\n", vp->v_type);
2507 bp->b_flags &= ~B_VMIO;
2513 bp->b_flags &= ~B_DONE;
2521 * Get an empty, disassociated buffer of given size. The buffer is
2522 * initially set to B_INVAL.
2524 * critical section protection is not required for the allocbuf()
2525 * call because races are impossible here.
2533 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2536 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2540 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2548 * This code constitutes the buffer memory from either anonymous system
2549 * memory (in the case of non-VMIO operations) or from an associated
2550 * VM object (in the case of VMIO operations). This code is able to
2551 * resize a buffer up or down.
2553 * Note that this code is tricky, and has many complications to resolve
2554 * deadlock or inconsistant data situations. Tread lightly!!!
2555 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2556 * the caller. Calling this code willy nilly can result in the loss of data.
2558 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2559 * B_CACHE for the non-VMIO case.
2561 * This routine does not need to be called from a critical section but you
2562 * must own the buffer.
2565 allocbuf(struct buf *bp, int size)
2567 int newbsize, mbsize;
2570 if (BUF_REFCNT(bp) == 0)
2571 panic("allocbuf: buffer not busy");
2573 if (bp->b_kvasize < size)
2574 panic("allocbuf: buffer too small");
2576 if ((bp->b_flags & B_VMIO) == 0) {
2580 * Just get anonymous memory from the kernel. Don't
2581 * mess with B_CACHE.
2583 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2584 #if !defined(NO_B_MALLOC)
2585 if (bp->b_flags & B_MALLOC)
2589 newbsize = round_page(size);
2591 if (newbsize < bp->b_bufsize) {
2592 #if !defined(NO_B_MALLOC)
2594 * malloced buffers are not shrunk
2596 if (bp->b_flags & B_MALLOC) {
2598 bp->b_bcount = size;
2600 free(bp->b_data, M_BIOBUF);
2601 if (bp->b_bufsize) {
2602 bufmallocspace -= bp->b_bufsize;
2606 bp->b_data = bp->b_kvabase;
2608 bp->b_flags &= ~B_MALLOC;
2615 (vm_offset_t) bp->b_data + newbsize,
2616 (vm_offset_t) bp->b_data + bp->b_bufsize);
2617 } else if (newbsize > bp->b_bufsize) {
2618 #if !defined(NO_B_MALLOC)
2620 * We only use malloced memory on the first allocation.
2621 * and revert to page-allocated memory when the buffer
2624 if ( (bufmallocspace < maxbufmallocspace) &&
2625 (bp->b_bufsize == 0) &&
2626 (mbsize <= PAGE_SIZE/2)) {
2628 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2629 bp->b_bufsize = mbsize;
2630 bp->b_bcount = size;
2631 bp->b_flags |= B_MALLOC;
2632 bufmallocspace += mbsize;
2638 #if !defined(NO_B_MALLOC)
2640 * If the buffer is growing on its other-than-first allocation,
2641 * then we revert to the page-allocation scheme.
2643 if (bp->b_flags & B_MALLOC) {
2644 origbuf = bp->b_data;
2645 origbufsize = bp->b_bufsize;
2646 bp->b_data = bp->b_kvabase;
2647 if (bp->b_bufsize) {
2648 bufmallocspace -= bp->b_bufsize;
2652 bp->b_flags &= ~B_MALLOC;
2653 newbsize = round_page(newbsize);
2658 (vm_offset_t) bp->b_data + bp->b_bufsize,
2659 (vm_offset_t) bp->b_data + newbsize);
2660 #if !defined(NO_B_MALLOC)
2662 bcopy(origbuf, bp->b_data, origbufsize);
2663 free(origbuf, M_BIOBUF);
2671 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2672 desiredpages = (size == 0) ? 0 :
2673 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2675 #if !defined(NO_B_MALLOC)
2676 if (bp->b_flags & B_MALLOC)
2677 panic("allocbuf: VMIO buffer can't be malloced");
2680 * Set B_CACHE initially if buffer is 0 length or will become
2683 if (size == 0 || bp->b_bufsize == 0)
2684 bp->b_flags |= B_CACHE;
2686 if (newbsize < bp->b_bufsize) {
2688 * DEV_BSIZE aligned new buffer size is less then the
2689 * DEV_BSIZE aligned existing buffer size. Figure out
2690 * if we have to remove any pages.
2692 if (desiredpages < bp->b_xio.xio_npages) {
2693 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2695 * the page is not freed here -- it
2696 * is the responsibility of
2697 * vnode_pager_setsize
2699 m = bp->b_xio.xio_pages[i];
2700 KASSERT(m != bogus_page,
2701 ("allocbuf: bogus page found"));
2702 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2705 bp->b_xio.xio_pages[i] = NULL;
2706 vm_page_unwire(m, 0);
2708 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2709 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2710 bp->b_xio.xio_npages = desiredpages;
2712 } else if (size > bp->b_bcount) {
2714 * We are growing the buffer, possibly in a
2715 * byte-granular fashion.
2723 * Step 1, bring in the VM pages from the object,
2724 * allocating them if necessary. We must clear
2725 * B_CACHE if these pages are not valid for the
2726 * range covered by the buffer.
2728 * critical section protection is required to protect
2729 * against interrupts unbusying and freeing pages
2730 * between our vm_page_lookup() and our
2731 * busycheck/wiring call.
2734 VOP_GETVOBJECT(vp, &obj);
2737 while (bp->b_xio.xio_npages < desiredpages) {
2741 pi = OFF_TO_IDX(bp->b_offset) + bp->b_xio.xio_npages;
2742 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2744 * note: must allocate system pages
2745 * since blocking here could intefere
2746 * with paging I/O, no matter which
2749 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2752 vm_pageout_deficit += desiredpages -
2753 bp->b_xio.xio_npages;
2757 bp->b_flags &= ~B_CACHE;
2758 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2759 ++bp->b_xio.xio_npages;
2765 * We found a page. If we have to sleep on it,
2766 * retry because it might have gotten freed out
2769 * We can only test PG_BUSY here. Blocking on
2770 * m->busy might lead to a deadlock:
2772 * vm_fault->getpages->cluster_read->allocbuf
2776 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2780 * We have a good page. Should we wakeup the
2783 if ((curthread != pagethread) &&
2784 ((m->queue - m->pc) == PQ_CACHE) &&
2785 ((vmstats.v_free_count + vmstats.v_cache_count) <
2786 (vmstats.v_free_min + vmstats.v_cache_min))) {
2787 pagedaemon_wakeup();
2789 vm_page_flag_clear(m, PG_ZERO);
2791 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2792 ++bp->b_xio.xio_npages;
2797 * Step 2. We've loaded the pages into the buffer,
2798 * we have to figure out if we can still have B_CACHE
2799 * set. Note that B_CACHE is set according to the
2800 * byte-granular range ( bcount and size ), not the
2801 * aligned range ( newbsize ).
2803 * The VM test is against m->valid, which is DEV_BSIZE
2804 * aligned. Needless to say, the validity of the data
2805 * needs to also be DEV_BSIZE aligned. Note that this
2806 * fails with NFS if the server or some other client
2807 * extends the file's EOF. If our buffer is resized,
2808 * B_CACHE may remain set! XXX
2811 toff = bp->b_bcount;
2812 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2814 while ((bp->b_flags & B_CACHE) && toff < size) {
2817 if (tinc > (size - toff))
2820 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2828 bp->b_xio.xio_pages[pi]
2835 * Step 3, fixup the KVM pmap. Remember that
2836 * bp->b_data is relative to bp->b_offset, but
2837 * bp->b_offset may be offset into the first page.
2840 bp->b_data = (caddr_t)
2841 trunc_page((vm_offset_t)bp->b_data);
2843 (vm_offset_t)bp->b_data,
2844 bp->b_xio.xio_pages,
2845 bp->b_xio.xio_npages
2847 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2848 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2851 if (newbsize < bp->b_bufsize)
2853 bp->b_bufsize = newbsize; /* actual buffer allocation */
2854 bp->b_bcount = size; /* requested buffer size */
2861 * Wait for buffer I/O completion, returning error status. The buffer
2862 * is left locked and B_DONE on return. B_EINTR is converted into an
2863 * EINTR error and cleared.
2866 biowait(struct buf * bp)
2869 while ((bp->b_flags & B_DONE) == 0) {
2870 if (bp->b_flags & B_READ)
2871 tsleep(bp, 0, "biord", 0);
2873 tsleep(bp, 0, "biowr", 0);
2876 if (bp->b_flags & B_EINTR) {
2877 bp->b_flags &= ~B_EINTR;
2880 if (bp->b_flags & B_ERROR) {
2881 return (bp->b_error ? bp->b_error : EIO);
2890 * Finish I/O on a buffer, optionally calling a completion function.
2891 * This is usually called from an interrupt so process blocking is
2894 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2895 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2896 * assuming B_INVAL is clear.
2898 * For the VMIO case, we set B_CACHE if the op was a read and no
2899 * read error occured, or if the op was a write. B_CACHE is never
2900 * set if the buffer is invalid or otherwise uncacheable.
2902 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2903 * initiator to leave B_INVAL set to brelse the buffer out of existance
2904 * in the biodone routine.
2906 * b_dev is required to be reinitialized prior to the top level strategy
2907 * call in a device stack. To avoid improper reuse, biodone() sets
2911 biodone(struct buf *bp)
2917 KASSERT(BUF_REFCNTNB(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
2918 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2919 biodone_t *biodone_func;
2921 bp->b_flags |= B_DONE;
2923 runningbufwakeup(bp);
2925 if (bp->b_flags & B_FREEBUF) {
2931 if ((bp->b_flags & B_READ) == 0) {
2935 /* call optional completion function if requested */
2936 if (bp->b_iodone != NULL) {
2937 biodone_func = bp->b_iodone;
2938 bp->b_iodone = NULL;
2939 (*biodone_func) (bp);
2943 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2944 (*bioops.io_complete)(bp);
2946 if (bp->b_flags & B_VMIO) {
2952 struct vnode *vp = bp->b_vp;
2954 error = VOP_GETVOBJECT(vp, &obj);
2956 #if defined(VFS_BIO_DEBUG)
2957 if (vp->v_holdcnt == 0) {
2958 panic("biodone: zero vnode hold count");
2962 panic("biodone: missing VM object");
2965 if ((vp->v_flag & VOBJBUF) == 0) {
2966 panic("biodone: vnode is not setup for merged cache");
2970 foff = bp->b_offset;
2971 KASSERT(bp->b_offset != NOOFFSET,
2972 ("biodone: no buffer offset"));
2975 panic("biodone: no object");
2977 #if defined(VFS_BIO_DEBUG)
2978 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
2979 printf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2980 obj->paging_in_progress, bp->b_xio.xio_npages);
2985 * Set B_CACHE if the op was a normal read and no error
2986 * occured. B_CACHE is set for writes in the b*write()
2989 iosize = bp->b_bcount - bp->b_resid;
2990 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2991 bp->b_flags |= B_CACHE;
2994 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2998 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3003 * cleanup bogus pages, restoring the originals. Since
3004 * the originals should still be wired, we don't have
3005 * to worry about interrupt/freeing races destroying
3006 * the VM object association.
3008 m = bp->b_xio.xio_pages[i];
3009 if (m == bogus_page) {
3011 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3013 panic("biodone: page disappeared");
3014 bp->b_xio.xio_pages[i] = m;
3015 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3016 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3018 #if defined(VFS_BIO_DEBUG)
3019 if (OFF_TO_IDX(foff) != m->pindex) {
3021 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3022 (unsigned long)foff, m->pindex);
3027 * In the write case, the valid and clean bits are
3028 * already changed correctly ( see bdwrite() ), so we
3029 * only need to do this here in the read case.
3031 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
3032 vfs_page_set_valid(bp, foff, i, m);
3034 vm_page_flag_clear(m, PG_ZERO);
3037 * when debugging new filesystems or buffer I/O methods, this
3038 * is the most common error that pops up. if you see this, you
3039 * have not set the page busy flag correctly!!!
3042 printf("biodone: page busy < 0, "
3043 "pindex: %d, foff: 0x(%x,%x), "
3044 "resid: %d, index: %d\n",
3045 (int) m->pindex, (int)(foff >> 32),
3046 (int) foff & 0xffffffff, resid, i);
3047 if (!vn_isdisk(vp, NULL))
3048 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
3049 bp->b_vp->v_mount->mnt_stat.f_iosize,
3051 bp->b_flags, bp->b_xio.xio_npages);
3053 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
3055 bp->b_flags, bp->b_xio.xio_npages);
3056 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3057 m->valid, m->dirty, m->wire_count);
3058 panic("biodone: page busy < 0");
3060 vm_page_io_finish(m);
3061 vm_object_pip_subtract(obj, 1);
3062 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3066 vm_object_pip_wakeupn(obj, 0);
3070 * For asynchronous completions, release the buffer now. The brelse
3071 * will do a wakeup there if necessary - so no need to do a wakeup
3072 * here in the async case. The sync case always needs to do a wakeup.
3075 if (bp->b_flags & B_ASYNC) {
3076 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3089 * This routine is called in lieu of iodone in the case of
3090 * incomplete I/O. This keeps the busy status for pages
3094 vfs_unbusy_pages(struct buf *bp)
3098 runningbufwakeup(bp);
3099 if (bp->b_flags & B_VMIO) {
3100 struct vnode *vp = bp->b_vp;
3103 VOP_GETVOBJECT(vp, &obj);
3105 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3106 vm_page_t m = bp->b_xio.xio_pages[i];
3109 * When restoring bogus changes the original pages
3110 * should still be wired, so we are in no danger of
3111 * losing the object association and do not need
3112 * critical section protection particularly.
3114 if (m == bogus_page) {
3115 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3117 panic("vfs_unbusy_pages: page missing");
3119 bp->b_xio.xio_pages[i] = m;
3120 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3121 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3123 vm_object_pip_subtract(obj, 1);
3124 vm_page_flag_clear(m, PG_ZERO);
3125 vm_page_io_finish(m);
3127 vm_object_pip_wakeupn(obj, 0);
3132 * vfs_page_set_valid:
3134 * Set the valid bits in a page based on the supplied offset. The
3135 * range is restricted to the buffer's size.
3137 * This routine is typically called after a read completes.
3140 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3142 vm_ooffset_t soff, eoff;
3145 * Start and end offsets in buffer. eoff - soff may not cross a
3146 * page boundry or cross the end of the buffer. The end of the
3147 * buffer, in this case, is our file EOF, not the allocation size
3151 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3152 if (eoff > bp->b_offset + bp->b_bcount)
3153 eoff = bp->b_offset + bp->b_bcount;
3156 * Set valid range. This is typically the entire buffer and thus the
3160 vm_page_set_validclean(
3162 (vm_offset_t) (soff & PAGE_MASK),
3163 (vm_offset_t) (eoff - soff)
3171 * This routine is called before a device strategy routine.
3172 * It is used to tell the VM system that paging I/O is in
3173 * progress, and treat the pages associated with the buffer
3174 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3175 * flag is handled to make sure that the object doesn't become
3178 * Since I/O has not been initiated yet, certain buffer flags
3179 * such as B_ERROR or B_INVAL may be in an inconsistant state
3180 * and should be ignored.
3183 vfs_busy_pages(struct buf *bp, int clear_modify)
3187 if (bp->b_flags & B_VMIO) {
3188 struct vnode *vp = bp->b_vp;
3192 VOP_GETVOBJECT(vp, &obj);
3193 foff = bp->b_offset;
3194 KASSERT(bp->b_offset != NOOFFSET,
3195 ("vfs_busy_pages: no buffer offset"));
3199 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3200 vm_page_t m = bp->b_xio.xio_pages[i];
3201 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3206 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3207 vm_page_t m = bp->b_xio.xio_pages[i];
3209 vm_page_flag_clear(m, PG_ZERO);
3210 if ((bp->b_flags & B_CLUSTER) == 0) {
3211 vm_object_pip_add(obj, 1);
3212 vm_page_io_start(m);
3216 * When readying a buffer for a read ( i.e
3217 * clear_modify == 0 ), it is important to do
3218 * bogus_page replacement for valid pages in
3219 * partially instantiated buffers. Partially
3220 * instantiated buffers can, in turn, occur when
3221 * reconstituting a buffer from its VM backing store
3222 * base. We only have to do this if B_CACHE is
3223 * clear ( which causes the I/O to occur in the
3224 * first place ). The replacement prevents the read
3225 * I/O from overwriting potentially dirty VM-backed
3226 * pages. XXX bogus page replacement is, uh, bogus.
3227 * It may not work properly with small-block devices.
3228 * We need to find a better way.
3231 vm_page_protect(m, VM_PROT_NONE);
3233 vfs_page_set_valid(bp, foff, i, m);
3234 else if (m->valid == VM_PAGE_BITS_ALL &&
3235 (bp->b_flags & B_CACHE) == 0) {
3236 bp->b_xio.xio_pages[i] = bogus_page;
3239 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3242 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3243 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3247 * This is the easiest place to put the process accounting for the I/O
3253 if ((p = curthread->td_proc) != NULL) {
3254 if (bp->b_flags & B_READ)
3255 p->p_stats->p_ru.ru_inblock++;
3257 p->p_stats->p_ru.ru_oublock++;
3265 * Tell the VM system that the pages associated with this buffer
3266 * are clean. This is used for delayed writes where the data is
3267 * going to go to disk eventually without additional VM intevention.
3269 * Note that while we only really need to clean through to b_bcount, we
3270 * just go ahead and clean through to b_bufsize.
3273 vfs_clean_pages(struct buf *bp)
3277 if (bp->b_flags & B_VMIO) {
3280 foff = bp->b_offset;
3281 KASSERT(bp->b_offset != NOOFFSET,
3282 ("vfs_clean_pages: no buffer offset"));
3283 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3284 vm_page_t m = bp->b_xio.xio_pages[i];
3285 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3286 vm_ooffset_t eoff = noff;
3288 if (eoff > bp->b_offset + bp->b_bufsize)
3289 eoff = bp->b_offset + bp->b_bufsize;
3290 vfs_page_set_valid(bp, foff, i, m);
3291 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3298 * vfs_bio_set_validclean:
3300 * Set the range within the buffer to valid and clean. The range is
3301 * relative to the beginning of the buffer, b_offset. Note that b_offset
3302 * itself may be offset from the beginning of the first page.
3306 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3308 if (bp->b_flags & B_VMIO) {
3313 * Fixup base to be relative to beginning of first page.
3314 * Set initial n to be the maximum number of bytes in the
3315 * first page that can be validated.
3318 base += (bp->b_offset & PAGE_MASK);
3319 n = PAGE_SIZE - (base & PAGE_MASK);
3321 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3322 vm_page_t m = bp->b_xio.xio_pages[i];
3327 vm_page_set_validclean(m, base & PAGE_MASK, n);
3338 * Clear a buffer. This routine essentially fakes an I/O, so we need
3339 * to clear B_ERROR and B_INVAL.
3341 * Note that while we only theoretically need to clear through b_bcount,
3342 * we go ahead and clear through b_bufsize.
3346 vfs_bio_clrbuf(struct buf *bp)
3350 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3351 bp->b_flags &= ~(B_INVAL|B_ERROR);
3352 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3353 (bp->b_offset & PAGE_MASK) == 0) {
3354 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3355 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3359 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3360 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3361 bzero(bp->b_data, bp->b_bufsize);
3362 bp->b_xio.xio_pages[0]->valid |= mask;
3367 ea = sa = bp->b_data;
3368 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3369 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3370 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3371 ea = (caddr_t)(vm_offset_t)ulmin(
3372 (u_long)(vm_offset_t)ea,
3373 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3374 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3375 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3377 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3378 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3382 for (; sa < ea; sa += DEV_BSIZE, j++) {
3383 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3384 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3385 bzero(sa, DEV_BSIZE);
3388 bp->b_xio.xio_pages[i]->valid |= mask;
3389 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3398 * vm_hold_load_pages:
3400 * Load pages into the buffer's address space. The pages are
3401 * allocated from the kernel object in order to reduce interference
3402 * with the any VM paging I/O activity. The range of loaded
3403 * pages will be wired.
3405 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3406 * retrieve the full range (to - from) of pages.
3410 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3416 to = round_page(to);
3417 from = round_page(from);
3418 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3420 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3425 * Note: must allocate system pages since blocking here
3426 * could intefere with paging I/O, no matter which
3429 p = vm_page_alloc(kernel_object,
3430 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3431 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3433 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3438 p->valid = VM_PAGE_BITS_ALL;
3439 vm_page_flag_clear(p, PG_ZERO);
3440 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3441 bp->b_xio.xio_pages[index] = p;
3444 bp->b_xio.xio_npages = index;
3448 * vm_hold_free_pages:
3450 * Return pages associated with the buffer back to the VM system.
3452 * The range of pages underlying the buffer's address space will
3453 * be unmapped and un-wired.
3456 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3460 int index, newnpages;
3462 from = round_page(from);
3463 to = round_page(to);
3464 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3466 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3467 p = bp->b_xio.xio_pages[index];
3468 if (p && (index < bp->b_xio.xio_npages)) {
3470 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3471 bp->b_blkno, bp->b_lblkno);
3473 bp->b_xio.xio_pages[index] = NULL;
3476 vm_page_unwire(p, 0);
3480 bp->b_xio.xio_npages = newnpages;
3486 * Map an IO request into kernel virtual address space.
3488 * All requests are (re)mapped into kernel VA space.
3489 * Notice that we use b_bufsize for the size of the buffer
3490 * to be mapped. b_bcount might be modified by the driver.
3493 vmapbuf(struct buf *bp)
3495 caddr_t addr, v, kva;
3501 if ((bp->b_flags & B_PHYS) == 0)
3503 if (bp->b_bufsize < 0)
3505 for (v = bp->b_saveaddr,
3506 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3508 addr < bp->b_data + bp->b_bufsize;
3509 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3511 * Do the vm_fault if needed; do the copy-on-write thing
3512 * when reading stuff off device into memory.
3515 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3516 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3518 for (i = 0; i < pidx; ++i) {
3519 vm_page_unhold(bp->b_xio.xio_pages[i]);
3520 bp->b_xio.xio_pages[i] = NULL;
3526 * WARNING! If sparc support is MFCd in the future this will
3527 * have to be changed from pmap_kextract() to pmap_extract()
3531 #error "If MFCing sparc support use pmap_extract"
3533 pa = pmap_kextract((vm_offset_t)addr);
3535 printf("vmapbuf: warning, race against user address during I/O");
3538 m = PHYS_TO_VM_PAGE(pa);
3540 bp->b_xio.xio_pages[pidx] = m;
3542 if (pidx > btoc(MAXPHYS))
3543 panic("vmapbuf: mapped more than MAXPHYS");
3544 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_xio.xio_pages, pidx);
3546 kva = bp->b_saveaddr;
3547 bp->b_xio.xio_npages = pidx;
3548 bp->b_saveaddr = bp->b_data;
3549 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3556 * Free the io map PTEs associated with this IO operation.
3557 * We also invalidate the TLB entries and restore the original b_addr.
3560 vunmapbuf(struct buf *bp)
3566 if ((bp->b_flags & B_PHYS) == 0)
3569 npages = bp->b_xio.xio_npages;
3570 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3572 m = bp->b_xio.xio_pages;
3573 for (pidx = 0; pidx < npages; pidx++)
3574 vm_page_unhold(*m++);
3576 bp->b_data = bp->b_saveaddr;
3580 * print out statistics from the current status of the buffer pool
3581 * this can be toggeled by the system control option debug.syncprt
3590 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3591 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3593 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3595 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3598 TAILQ_FOREACH(bp, dp, b_freelist) {
3599 counts[bp->b_bufsize/PAGE_SIZE]++;
3603 printf("%s: total-%d", bname[i], count);
3604 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3606 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
3612 #include "opt_ddb.h"
3614 #include <ddb/ddb.h>
3616 DB_SHOW_COMMAND(buffer, db_show_buffer)
3619 struct buf *bp = (struct buf *)addr;
3622 db_printf("usage: show buffer <addr>\n");
3626 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3627 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3628 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3629 "b_blkno = %d, b_pblkno = %d\n",
3630 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3631 major(bp->b_dev), minor(bp->b_dev),
3632 bp->b_data, bp->b_blkno, bp->b_pblkno);
3633 if (bp->b_xio.xio_npages) {
3635 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3636 bp->b_xio.xio_npages);
3637 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3639 m = bp->b_xio.xio_pages[i];
3640 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3641 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3642 if ((i + 1) < bp->b_xio.xio_npages)